You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@cassandra.apache.org by jb...@apache.org on 2010/10/25 18:10:32 UTC

svn commit: r1027181 - in /cassandra/branches/cassandra-0.7/src/java/org/apache/cassandra/cli: CliClient.java CliCompiler.java CliMain.java CliUtils.java

Author: jbellis
Date: Mon Oct 25 16:10:31 2010
New Revision: 1027181

URL: http://svn.apache.org/viewvc?rev=1027181&view=rev
Log:
cli code cleanup.  patch by Pavel Yaskevich; reviewed by jbellis for CASSANDRA-615

Modified:
    cassandra/branches/cassandra-0.7/src/java/org/apache/cassandra/cli/CliClient.java
    cassandra/branches/cassandra-0.7/src/java/org/apache/cassandra/cli/CliCompiler.java
    cassandra/branches/cassandra-0.7/src/java/org/apache/cassandra/cli/CliMain.java
    cassandra/branches/cassandra-0.7/src/java/org/apache/cassandra/cli/CliUtils.java

Modified: cassandra/branches/cassandra-0.7/src/java/org/apache/cassandra/cli/CliClient.java
URL: http://svn.apache.org/viewvc/cassandra/branches/cassandra-0.7/src/java/org/apache/cassandra/cli/CliClient.java?rev=1027181&r1=1027180&r2=1027181&view=diff
==============================================================================
--- cassandra/branches/cassandra-0.7/src/java/org/apache/cassandra/cli/CliClient.java (original)
+++ cassandra/branches/cassandra-0.7/src/java/org/apache/cassandra/cli/CliClient.java Mon Oct 25 16:10:31 2010
@@ -17,12 +17,7 @@
  */
 package org.apache.cassandra.cli;
 
-import java.math.BigInteger;
-import java.nio.ByteBuffer;
-import java.util.*;
-
 import com.google.common.base.Charsets;
-
 import org.antlr.runtime.tree.CommonTree;
 import org.antlr.runtime.tree.Tree;
 import org.apache.cassandra.auth.SimpleAuthenticator;
@@ -34,15 +29,19 @@ import org.apache.cassandra.utils.FBUtil
 import org.apache.cassandra.utils.UUIDGen;
 import org.apache.thrift.TException;
 
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import java.util.*;
+
 // Cli Client Side Library
-public class CliClient 
+public class CliClient extends CliUserHelp 
 {
 
     /**
      * Available value conversion functions
      * Used by convertValueByFunction(Tree functionCall) method
      */
-    private enum Function
+    public enum Function
     {
         BYTES       (BytesType.instance),
         INTEGER     (IntegerType.instance),
@@ -80,50 +79,6 @@ public class CliClient 
     }
     
     /*
-     * the <i>add column family</i> command requires a list of arguments, 
-     *  this enum defines which arguments are valid.
-     */
-    private enum ColumnFamilyArgument
-    {
-        COLUMN_TYPE,
-        COMPARATOR,
-        SUBCOMPARATOR,
-        COMMENT,
-        ROWS_CACHED,
-        ROW_CACHE_SAVE_PERIOD,
-        KEYS_CACHED,
-        KEY_CACHE_SAVE_PERIOD,
-        READ_REPAIR_CHANCE,
-        GC_GRACE,
-        COLUMN_METADATA,
-        MEMTABLE_OPERATIONS,
-        MEMTABLE_THROUGHPUT,
-        MEMTABLE_FLUSH_AFTER,
-        DEFAULT_VALIDATION_CLASS,
-        MIN_COMPACTION_THRESHOLD,
-        MAX_COMPACTION_THRESHOLD,
-    }
-
-    private EnumMap<ColumnFamilyArgument, String> argumentExplanations = new EnumMap<ColumnFamilyArgument, String>(ColumnFamilyArgument.class)
-    {{
-        put(ColumnFamilyArgument.COLUMN_TYPE, "Super or Standard");
-        put(ColumnFamilyArgument.COMMENT, "Human-readable column family description. Any string is acceptable");
-        put(ColumnFamilyArgument.COMPARATOR, "The class used as a comparator when sorting column names.\n                  Valid options include: AsciiType, BytesType, LexicalUUIDType,\n                  LongType, TimeUUIDType, and UTF8Type");
-        put(ColumnFamilyArgument.SUBCOMPARATOR, "Comparator for sorting subcolumn names, for Super columns only");
-        put(ColumnFamilyArgument.MEMTABLE_OPERATIONS, "Flush memtables after this many operations");
-        put(ColumnFamilyArgument.MEMTABLE_THROUGHPUT, "... or after this many bytes have been written");
-        put(ColumnFamilyArgument.MEMTABLE_FLUSH_AFTER, "... or after this many seconds");
-        put(ColumnFamilyArgument.ROWS_CACHED, "Number or percentage of rows to cache");
-        put(ColumnFamilyArgument.ROW_CACHE_SAVE_PERIOD, "Period with which to persist the row cache, in seconds");
-        put(ColumnFamilyArgument.KEYS_CACHED, "Number or percentage of keys to cache");
-        put(ColumnFamilyArgument.KEY_CACHE_SAVE_PERIOD, "Period with which to persist the key cache, in seconds");
-        put(ColumnFamilyArgument.READ_REPAIR_CHANCE, "Probability (0.0-1.0) with which to perform read repairs on CL.ONE reads");
-        put(ColumnFamilyArgument.GC_GRACE, "Discard tombstones after this many seconds");
-        put(ColumnFamilyArgument.MIN_COMPACTION_THRESHOLD, "Avoid minor compactions of less than this number of sstable files");
-        put(ColumnFamilyArgument.MAX_COMPACTION_THRESHOLD, "Compact no more than this number of sstable files at once");
-    }};
-
-    /*
      * the <i>add keyspace</i> command requires a list of arguments,
      *  this enum defines which arguments are valid
      */
@@ -133,8 +88,8 @@ public class CliClient 
         STRATEGY_OPTIONS
     }
 
-    private Cassandra.Client thriftClient_ = null;
-    private CliSessionState css_ = null;
+    private Cassandra.Client thriftClient = null;
+    private CliSessionState sessionState  = null;
     private String keySpace = null;
     private String username = null;
     private Map<String, KsDef> keyspacesMap = new HashMap<String, KsDef>();
@@ -143,349 +98,97 @@ public class CliClient 
     
     public CliClient(CliSessionState cliSessionState, Cassandra.Client thriftClient)
     {
-        css_ = cliSessionState;
-        thriftClient_ = thriftClient;
+        this.sessionState = cliSessionState;
+        this.thriftClient = thriftClient;
     }
 
     // Execute a CLI Statement 
-    public void executeCLIStmt(String stmt) throws TException, NotFoundException, InvalidRequestException, UnavailableException, TimedOutException, IllegalAccessException, ClassNotFoundException, InstantiationException, NoSuchFieldException
+    public void executeCLIStatement(String statement)
     {
-        CommonTree ast = CliCompiler.compileQuery(stmt);
-
-        switch (ast.getType())
-        {
-            case CliParser.NODE_EXIT:
-                cleanupAndExit();
-                break;
-            case CliParser.NODE_THRIFT_GET:
-                executeGet(ast);
-                break;
-            case CliParser.NODE_THRIFT_GET_WITH_CONDITIONS:
-                executeGetWithConditions(ast);
-                break;
-            case CliParser.NODE_HELP:
-                printCmdHelp(ast);
-                break;
-            case CliParser.NODE_THRIFT_SET:
-                executeSet(ast);
-                break;
-            case CliParser.NODE_THRIFT_DEL:
-                executeDelete(ast);
-                break;
-            case CliParser.NODE_THRIFT_COUNT:
-                executeCount(ast);
-                break;
-            case CliParser.NODE_ADD_KEYSPACE:
-                executeAddKeyspace(ast.getChild(0));
-                break;
-            case CliParser.NODE_ADD_COLUMN_FAMILY:
-                executeAddColumnFamily(ast.getChild(0));
-                break;
-            case CliParser.NODE_UPDATE_KEYSPACE:
-                executeUpdateKeyspace(ast.getChild(0));
-                break;
-            case CliParser.NODE_UPDATE_COLUMN_FAMILY:
-                executeUpdateColumnFamily(ast.getChild(0));
-                break;
-            case CliParser.NODE_DEL_COLUMN_FAMILY:
-                executeDelColumnFamily(ast);
-                break;
-            case CliParser.NODE_DEL_KEYSPACE:
-                executeDelKeyspace(ast);
-                break;
-            case CliParser.NODE_SHOW_CLUSTER_NAME:
-                executeShowClusterName();
-                break;
-            case CliParser.NODE_SHOW_VERSION:
-                executeShowVersion();
-                break;
-            case CliParser.NODE_SHOW_TABLES:
-                executeShowTables();
-                break;
-            case CliParser.NODE_DESCRIBE_TABLE:
-                executeDescribeTable(ast);
-                break;
-            case CliParser.NODE_USE_TABLE:
-                executeUseTable(ast);
-                break;
-            case CliParser.NODE_CONNECT:
-                executeConnect(ast);
-                break;
-            case CliParser.NODE_LIST:
-                executeList(ast);
-                break;
-            case CliParser.NODE_NO_OP:
-                // comment lines come here; they are treated as no ops.
-                break;
-            default:
-                css_.err.println("Invalid Statement (Type: " + ast.getType() + ")");
-                if (css_.batch)
-                    System.exit(2);
-                break;
-        }
-    }
+        Tree tree = CliCompiler.compileQuery(statement);
 
-    private void printCmdHelp(CommonTree ast)
-    {
-        if (ast.getChildCount() > 0)
+        try
         {
-            int helpType = ast.getChild(0).getType();
-                    
-            switch(helpType)
+            switch (tree.getType())
             {
-            case CliParser.NODE_HELP:
-                css_.out.println("help <command>\n");
-                css_.out.println("Display the general help page with a list of available commands.");
-                break;
-            case CliParser.NODE_CONNECT:
-                css_.out.println("connect <hostname>/<port>\n");
-                css_.out.println("Connect to the specified host on the specified port.\n");
-                css_.out.println("example:");
-                css_.out.println("connect localhost/9160");
-                break;
-                
-            case CliParser.NODE_USE_TABLE:
-                css_.out.println("use <keyspace>");
-                css_.out.println("use <keyspace> <username> '<password>'\n");
-                css_.out.println("Switch to the specified keyspace. The optional username and password fields");
-                css_.out.println("are needed when performing authentication.\n");
-                break;
-                
-            case CliParser.NODE_DESCRIBE_TABLE:
-                css_.out.println("describe keyspace <keyspace>\n");
-                css_.out.println("Show additional information about the specified keyspace.\n");
-                css_.out.println("example:");
-                css_.out.println("describe keyspace system");
-                break;
-                
-            case CliParser.NODE_EXIT:
-                css_.out.println("exit");
-                css_.out.println("quit\n");
-                css_.out.println("Exit this utility.");
-                break;
-                
-            case CliParser.NODE_SHOW_CLUSTER_NAME:
-                css_.out.println("show cluster name\n");
-                css_.out.println("Displays the name of the currently connected cluster.");
-                break;
-                
-            case CliParser.NODE_SHOW_VERSION:
-                css_.out.println("show api version\n");
-                css_.out.println("Displays the API version number.");
-                break;
-                
-            case CliParser.NODE_SHOW_TABLES:  
-                css_.out.println("show keyspaces\n");
-                css_.out.println("Displays a list of the keyspaces available on the currently connected cluster.");
-                break;
-                
-            case CliParser.NODE_ADD_KEYSPACE:
-                css_.out.println("create keyspace <keyspace>");
-                css_.out.println("create keyspace <keyspace> with <att1>=<value1>");
-                css_.out.println("create keyspace <keyspace> with <att1>=<value1> and <att2>=<value2> ...\n");
-                css_.out.println("Create a new keyspace with the specified values for the given set of attributes.\n");
-                css_.out.println("valid attributes are:");
-                css_.out.println("    replication_factor: to how many nodes should entries to this keyspace be");
-                css_.out.println("                        replicated. Valid entries are integers greater than 0.");
-                css_.out.println("    placement_strategy: the fully qualified class used to place replicas in");
-                css_.out.println("                        this keyspace. Valid values are");
-                css_.out.println("                        org.apache.cassandra.locator.SimpleStrategy,");
-                css_.out.println("                        org.apache.cassandra.locator.NetworkTopologyStrategy,");
-                css_.out.println("                        and org.apache.cassandra.locator.OldNetworkTopologyStrategy");
-                css_.out.println("      strategy_options: additional options for placement_strategy.\n");
-                css_.out.println("example:");
-                css_.out.println("create keyspace foo with replication_factor = 3 and ");
-                css_.out.println("        placement_strategy = 'org.apache.cassandra.locator.SimpleStrategy'");
-                css_.out.println("        and strategy_options=[{DC1:2, DC2:2}]");
-                break;
-
-            case CliParser.NODE_UPDATE_KEYSPACE:
-                css_.out.println("update keyspace <keyspace>");
-                css_.out.println("update keyspace <keyspace> with <att1>=<value1>");
-                css_.out.println("update keyspace <keyspace> with <att1>=<value1> and <att2>=<value2> ...\n");
-                css_.out.println("Update a keyspace with the specified values for the given set of attributes.\n");
-                css_.out.println("valid attributes are:");
-                css_.out.println("    replication_factor: to how many nodes should entries to this keyspace be");
-                css_.out.println("                        replicated. Valid entries are integers greater than 0.");
-                css_.out.println("    placement_strategy: the fully qualified class used to place replicas in");
-                css_.out.println("                        this keyspace. Valid values are");
-                css_.out.println("                        org.apache.cassandra.locator.SimpleStrategy,");
-                css_.out.println("                        org.apache.cassandra.locator.NetworkTopologyStrategy,");
-                css_.out.println("                        and org.apache.cassandra.locator.OldNetworkTopologyStrategy");
-                css_.out.println("      strategy_options: additional options for placement_strategy.\n");
-                css_.out.println("example:");
-                css_.out.println("update keyspace foo with replication_factor = 2 and ");
-                css_.out.println("        placement_strategy = 'org.apache.cassandra.locator.LocalStrategy'");
-                css_.out.println("        and strategy_options=[{DC1:1, DC2:4, DC3:2}]");
-                break;
-
-            case CliParser.NODE_ADD_COLUMN_FAMILY:
-                css_.out.println("create column family Bar");
-                css_.out.println("create column family Bar with <att1>=<value1>");
-                css_.out.println("create column family Bar with <att1>=<value1> and <att2>=<value2>...\n");
-                css_.out.println("Create a new column family with the specified values for the given set of");
-                css_.out.println("attributes. Note that you must be using a keyspace.\n");
-                css_.out.println("valid attributes are:");
-                for (ColumnFamilyArgument argument : ColumnFamilyArgument.values())
-                    css_.out.printf("    - %s: %s\n", argument.toString().toLowerCase(), argumentExplanations.get(argument));
-                css_.out.println("    - column_metadata: Metadata which describes columns of column family.");
-                css_.out.println("        Supported format is [{ k:v, k:v, ... }, { ... }, ...]");
-                css_.out.println("        Valid attributes: column_name, validation_class (see comparator),");
-                css_.out.println("                          index_type (integer), index_name.");
-                css_.out.println("example:\n");
-                css_.out.println("create column family Bar with column_type = 'Super' and comparator = 'AsciiType'");
-                css_.out.println("      and rows_cached = 10000");
-                css_.out.println("create column family Baz with comparator = 'LongType' and rows_cached = 10000");
-                css_.out.print("create column family Foo with comparator=LongType and column_metadata=");
-                css_.out.print("[{ column_name:Test, validation_class:IntegerType, index_type:0, index_name:IdxName");
-                css_.out.println("}, { column_name:'other name', validation_class:LongType }]");
-                break;
-
-            case CliParser.NODE_UPDATE_COLUMN_FAMILY:
-                css_.out.println("update column family Bar");
-                css_.out.println("update column family Bar with <att1>=<value1>");
-                css_.out.println("update column family Bar with <att1>=<value1> and <att2>=<value2>...\n");
-                css_.out.println("Update a column family with the specified values for the given set of");
-                css_.out.println("attributes. Note that you must be using a keyspace.\n");
-                css_.out.println("valid attributes are:");
-                for (ColumnFamilyArgument argument : ColumnFamilyArgument.values())
-                {
-                    if (argument == ColumnFamilyArgument.COMPARATOR || argument == ColumnFamilyArgument.SUBCOMPARATOR)
-                        continue;
-                    css_.out.printf("    - %s: %s\n", argument.toString().toLowerCase(), argumentExplanations.get(argument));
-                }
-                css_.out.println("    - column_metadata: Metadata which describes columns of column family.");
-                css_.out.println("        Supported format is [{ k:v, k:v, ... }, { ... }, ...]");
-                css_.out.println("        Valid attributes: column_name, validation_class (see comparator),");
-                css_.out.println("                          index_type (integer), index_name.");
-                css_.out.println("example:\n");
-                css_.out.print("update column family Foo with column_metadata=");
-                css_.out.print("[{ column_name:Test, validation_class:IntegerType, index_type:0, index_name:IdxName");
-                css_.out.println("}] and rows_cached=100 and comment='this is helpful comment.'");
-                break;
-                
-            case CliParser.NODE_DEL_KEYSPACE:
-                css_.out.println("drop keyspace <keyspace>\n");
-                css_.out.println("Drops the specified keyspace.\n");
-                css_.out.println("example:");
-                css_.out.println("drop keyspace foo");
-                break;
-                
-            case CliParser.NODE_DEL_COLUMN_FAMILY:
-                css_.out.println("drop column family <name>\n");
-                css_.out.println("Drops the specified column family.\n");
-                css_.out.println("example:");
-                css_.out.println("drop column family foo");
-                break;
-                
-            case CliParser.NODE_THRIFT_GET :
-                css_.out.println("get <cf>['<key>']");
-                css_.out.println("get <cf>['<key>']['<col>'] (as <type>)*");
-                css_.out.println("get <cf>['<key>']['<super>']");
-                css_.out.println("get <cf> where <column> = <value> [and <column> > <value> and ...] [limit <integer>]");
-                css_.out.println("Default LIMIT is 100. Available operations: =, >, >=, <, <=\n");
-                css_.out.println("get <cf>['<key>']['<super>']['<col>'] (as <type>)*");
-                css_.out.print("Note: `as <type>` is optional, it dynamically converts column value to the specified type");
-                css_.out.println(", column value validator will be set to <type>.");
-                css_.out.println("Available types: IntegerType, LongType, UTF8Type, ASCIIType, TimeUUIDType, LexicalUUIDType.\n");
-                css_.out.println("examples:");
-                css_.out.println("get bar[testkey]");
-                css_.out.println("get bar[testkey][test_column] as IntegerType");
-                break;
-                
-            case CliParser.NODE_THRIFT_SET:
-                css_.out.println("set <cf>['<key>']['<col>'] = <value>");
-                css_.out.println("set <cf>['<key>']['<super>']['<col>'] = <value>");
-                css_.out.println("set <cf>['<key>']['<col>'] = <function>(<argument>)");
-                css_.out.println("set <cf>['<key>']['<super>']['<col>'] = <function>(<argument>)");
-                css_.out.println("Available functions: " + Function.getFunctionNames() + "\n");
-                css_.out.println("examples:");
-                css_.out.println("set bar['testkey']['my super']['test col']='this is a test'");
-                css_.out.println("set baz['testkey']['test col']='this is also a test'");
-                css_.out.println("set diz[testkey][testcol] = utf8('this is utf8 string.')");
-                break;
-                
-            case CliParser.NODE_THRIFT_DEL:
-                css_.out.println("del <cf>['<key>'] ");
-                css_.out.println("del <cf>['<key>']['<col>'] ");
-                css_.out.println("del <cf>['<key>']['<super>']['<col>']\n");
-                css_.out.println("Deletes a record, a column, or a subcolumn.\n");
-                css_.out.println("example:");
-                css_.out.println("del bar['testkey']['my super']['test col']");
-                css_.out.println("del baz['testkey']['test col']");
-                css_.out.println("del baz['testkey']");
-                break;
-                
-            case CliParser.NODE_THRIFT_COUNT:
-                css_.out.println("count <cf>['<key>']");
-                css_.out.println("count <cf>['<key>']['<super>']\n");
-                css_.out.println("Count the number of columns in the specified key or subcolumns in the specified");
-                css_.out.println("super column.\n");
-                css_.out.println("example:");
-                css_.out.println("count bar['testkey']['my super']");
-                css_.out.println("count baz['testkey']");
-                break;
-
-            case CliParser.NODE_LIST:
-                css_.out.println("list <cf>");
-                css_.out.println("list <cf>[<startKey>:]");
-                css_.out.println("list <cf>[<startKey>:<endKey>]");
-                css_.out.println("list ... limit N");
-                css_.out.println("List a range of rows in the column or supercolumn family.\n");
-                css_.out.println("example:");
-                css_.out.println("list Users[j:] limit 40");
-                break;
-                
-            default:
-                css_.out.println("?");
-                break;
+                case CliParser.NODE_EXIT:
+                    cleanupAndExit();
+                    break;
+                case CliParser.NODE_THRIFT_GET:
+                    executeGet(tree);
+                    break;
+                case CliParser.NODE_THRIFT_GET_WITH_CONDITIONS:
+                    executeGetWithConditions(tree);
+                    break;
+                case CliParser.NODE_HELP:
+                    printCmdHelp(tree, sessionState);
+                    break;
+                case CliParser.NODE_THRIFT_SET:
+                    executeSet(tree);
+                    break;
+                case CliParser.NODE_THRIFT_DEL:
+                    executeDelete(tree);
+                    break;
+                case CliParser.NODE_THRIFT_COUNT:
+                    executeCount(tree);
+                    break;
+                case CliParser.NODE_ADD_KEYSPACE:
+                    executeAddKeySpace(tree.getChild(0));
+                    break;
+                case CliParser.NODE_ADD_COLUMN_FAMILY:
+                    executeAddColumnFamily(tree.getChild(0));
+                    break;
+                case CliParser.NODE_UPDATE_KEYSPACE:
+                    executeUpdateKeySpace(tree.getChild(0));
+                    break;
+                case CliParser.NODE_UPDATE_COLUMN_FAMILY:
+                    executeUpdateColumnFamily(tree.getChild(0));
+                    break;
+                case CliParser.NODE_DEL_COLUMN_FAMILY:
+                    executeDelColumnFamily(tree);
+                    break;
+                case CliParser.NODE_DEL_KEYSPACE:
+                    executeDelKeySpace(tree);
+                    break;
+                case CliParser.NODE_SHOW_CLUSTER_NAME:
+                    executeShowClusterName();
+                    break;
+                case CliParser.NODE_SHOW_VERSION:
+                    executeShowVersion();
+                    break;
+                case CliParser.NODE_SHOW_TABLES:
+                    executeShowKeySpaces();
+                    break;
+                case CliParser.NODE_DESCRIBE_TABLE:
+                    executeDescribeKeySpace(tree);
+                    break;
+                case CliParser.NODE_USE_TABLE:
+                    executeUseKeySpace(tree);
+                    break;
+                case CliParser.NODE_CONNECT:
+                    executeConnect(tree);
+                    break;
+                case CliParser.NODE_LIST:
+                    executeList(tree);
+                    break;
+                case CliParser.NODE_NO_OP:
+                    // comment lines come here; they are treated as no ops.
+                    break;
+                default:
+                    sessionState.err.println("Invalid Statement (Type: " + tree.getType() + ")");
+                    if (sessionState.batch)
+                        System.exit(2);
+                    break;
             }
         }
-        else
+        catch (InvalidRequestException e)
         {
-            css_.out.println("List of all CLI commands:");
-            css_.out.println("?                                                          Display this message.");
-            css_.out.println("help                                                          Display this help.");
-            css_.out.println("help <command>                          Display detailed, command-specific help.");
-            css_.out.println("connect <hostname>/<port>                             Connect to thrift service.");
-            css_.out.println("use <keyspace> [<username> 'password']                     Switch to a keyspace.");
-            css_.out.println("describe keyspace <keyspacename>                              Describe keyspace.");
-            css_.out.println("exit                                                                   Exit CLI.");
-            css_.out.println("quit                                                                   Exit CLI.");
-            css_.out.println("show cluster name                                          Display cluster name.");
-            css_.out.println("show keyspaces                                           Show list of keyspaces.");
-            css_.out.println("show api version                                        Show server API version.");
-            css_.out.println("create keyspace <keyspace> [with <att1>=<value1> [and <att2>=<value2> ...]]");
-            css_.out.println("                Add a new keyspace with the specified attribute(s) and value(s).");
-            css_.out.println("update keyspace <keyspace> [with <att1>=<value1> [and <att2>=<value2> ...]]");
-            css_.out.println("                 Update a keyspace with the specified attribute(s) and value(s).");
-            css_.out.println("create column family <cf> [with <att1>=<value1> [and <att2>=<value2> ...]]");
-            css_.out.println("        Create a new column family with the specified attribute(s) and value(s).");
-            css_.out.println("update column family <cf> [with <att1>=<value1> [and <att2>=<value2> ...]]");
-            css_.out.println("            Update a column family with the specified attribute(s) and value(s).");
-            css_.out.println("drop keyspace <keyspace>                                      Delete a keyspace.");
-            css_.out.println("drop column family <cf>                                  Delete a column family.");
-            css_.out.println("rename keyspace <keyspace> <keyspace_new_name>                Rename a keyspace.");
-            css_.out.println("rename column family <cf> <new_name>                     Rename a column family.");
-            css_.out.println("get <cf>['<key>']                                        Get a slice of columns.");
-            css_.out.println("get <cf>['<key>']['<super>']                         Get a slice of sub columns.");
-            css_.out.println("get <cf> where <column> = <value> [and <column> > <value> and ...] [limit int]. ");
-            css_.out.println("get <cf>['<key>']['<col>'] (as <type>)*                      Get a column value.");
-            css_.out.println("get <cf>['<key>']['<super>']['<col>'] (as <type>)*       Get a sub column value.");
-            css_.out.println("set <cf>['<key>']['<col>'] = <value>                               Set a column.");
-            css_.out.println("set <cf>['<key>']['<super>']['<col>'] = <value>                Set a sub column.");
-            css_.out.println("del <cf>['<key>']                                                 Delete record.");
-            css_.out.println("del <cf>['<key>']['<col>']                                        Delete column.");
-            css_.out.println("del <cf>['<key>']['<super>']['<col>']                         Delete sub column.");
-            css_.out.println("count <cf>['<key>']                                     Count columns in record.");
-            css_.out.println("count <cf>['<key>']['<super>']                  Count columns in a super column.");
-            css_.out.println("list <cf>                                  List all rows in the column family.");
-            css_.out.println("list <cf>[<startKey>:]");
-            css_.out.println("                       List rows in the column family beginning with <startKey>.");
-            css_.out.println("list <cf>[<startKey>:<endKey>]");
-            css_.out.println("        List rows in the column family in the range from <startKey> to <endKey>.");
-            css_.out.println("list ... limit N                                    Limit the list results to N.");
-        } 
+            throw new RuntimeException(e.getWhy());
+        }
+        catch (Exception e)
+        {
+            throw new RuntimeException(e.getMessage());
+        }
     }
 
     private void cleanupAndExit()
@@ -494,58 +197,50 @@ public class CliClient 
         System.exit(0);
     }
     
-    KsDef getKSMetaData(String keyspace) throws NotFoundException, InvalidRequestException, TException
+    public KsDef getKSMetaData(String keyspace)
+            throws NotFoundException, InvalidRequestException, TException
     {
         // Lazily lookup keyspace meta-data.
         if (!(keyspacesMap.containsKey(keyspace)))
-            keyspacesMap.put(keyspace, thriftClient_.describe_keyspace(keyspace));
+            keyspacesMap.put(keyspace, thriftClient.describe_keyspace(keyspace));
+        
         return keyspacesMap.get(keyspace);
     }
     
-    private void executeCount(CommonTree ast) throws TException, InvalidRequestException, UnavailableException, TimedOutException
+    private void executeCount(Tree statement)
+            throws TException, InvalidRequestException, UnavailableException, TimedOutException
     {
        if (!CliMain.isConnected() || !hasKeySpace())
            return;
 
-       int childCount = ast.getChildCount();
-       assert(childCount == 1);
-
-       CommonTree columnFamilySpec = (CommonTree)ast.getChild(0);
-       assert(columnFamilySpec.getType() == CliParser.NODE_COLUMN_ACCESS);
+       Tree columnFamilySpec = statement.getChild(0);
 
        String key = CliCompiler.getKey(columnFamilySpec);
        String columnFamily = CliCompiler.getColumnFamily(columnFamilySpec);
        int columnSpecCnt = CliCompiler.numColumnSpecifiers(columnFamilySpec);
        
-       ColumnParent colParent;
+       ColumnParent colParent = new ColumnParent(columnFamily).setSuper_column((ByteBuffer) null);
        
-       if (columnSpecCnt == 0)
+       if (columnSpecCnt != 0)
        {
-           colParent = new ColumnParent(columnFamily).setSuper_column((ByteBuffer)null);
-       }
-       else
-       {
-           assert (columnSpecCnt == 1);
-           colParent = new ColumnParent(columnFamily).setSuper_column(CliCompiler.getColumn(columnFamilySpec, 0).getBytes(Charsets.UTF_8));
+           byte[] superColumn = CliCompiler.getColumn(columnFamilySpec, 0).getBytes(Charsets.UTF_8);
+           colParent = new ColumnParent(columnFamily).setSuper_column(superColumn);
        }
 
        SliceRange range = new SliceRange(FBUtilities.EMPTY_BYTE_BUFFER, FBUtilities.EMPTY_BYTE_BUFFER, false, Integer.MAX_VALUE);
        SlicePredicate predicate = new SlicePredicate().setColumn_names(null).setSlice_range(range);
        
-       int count = thriftClient_.get_count(ByteBuffer.wrap(key.getBytes(Charsets.UTF_8)), colParent, predicate, ConsistencyLevel.ONE);
-       css_.out.printf("%d columns\n", count);
+       int count = thriftClient.get_count(ByteBuffer.wrap(key.getBytes(Charsets.UTF_8)), colParent, predicate, ConsistencyLevel.ONE);
+       sessionState.out.printf("%d columns\n", count);
     }
     
-    private void executeDelete(CommonTree ast) throws TException, InvalidRequestException, UnavailableException, TimedOutException
+    private void executeDelete(Tree statement) 
+            throws TException, InvalidRequestException, UnavailableException, TimedOutException
     {
         if (!CliMain.isConnected() || !hasKeySpace())
             return;
 
-        int childCount = ast.getChildCount();
-        assert(childCount == 1);
-
-        CommonTree columnFamilySpec = (CommonTree)ast.getChild(0);
-        assert(columnFamilySpec.getType() == CliParser.NODE_COLUMN_ACCESS);
+        Tree columnFamilySpec = statement.getChild(0);
 
         String key = CliCompiler.getKey(columnFamilySpec);
         String columnFamily = CliCompiler.getColumnFamily(columnFamilySpec);
@@ -553,25 +248,11 @@ public class CliClient 
 
         byte[] superColumnName = null;
         byte[] columnName = null;
-        boolean isSuper;
-
-        List<String> cfnames = new ArrayList<String>();
-        for (CfDef cfd : keyspacesMap.get(keySpace).cf_defs) {
-            cfnames.add(cfd.name);
-        }
-
-        int idx = cfnames.indexOf(columnFamily);
-        if (idx == -1)
-        {
-            css_.out.println("No such column family: " + columnFamily);
-            return;
-        }
-            
-        isSuper = keyspacesMap.get(keySpace).cf_defs.get(idx).column_type.equals("Super");
+        boolean isSuper = getCfDef(columnFamily).column_type.equals("Super");
      
         if ((columnSpecCnt < 0) || (columnSpecCnt > 2))
         {
-            css_.out.println("Invalid row, super column, or column specification.");
+            sessionState.out.println("Invalid row, super column, or column specification.");
             return;
         }
         
@@ -597,9 +278,9 @@ public class CliClient 
         if(columnName != null)
             path.setColumn(columnName);
         
-        thriftClient_.remove(ByteBuffer.wrap(key.getBytes(Charsets.UTF_8)), path,
+        thriftClient.remove(ByteBuffer.wrap(key.getBytes(Charsets.UTF_8)), path,
                              FBUtilities.timestampMicros(), ConsistencyLevel.ONE);
-        css_.out.println(String.format("%s removed.", (columnSpecCnt == 0) ? "row" : "column"));
+        sessionState.out.println(String.format("%s removed.", (columnSpecCnt == 0) ? "row" : "column"));
     }
 
     private void doSlice(String keyspace, String key, String columnFamily, byte[] superColumnName)
@@ -611,9 +292,8 @@ public class CliClient 
             parent.setSuper_column(superColumnName);
                 
         SliceRange range = new SliceRange(FBUtilities.EMPTY_BYTE_BUFFER, FBUtilities.EMPTY_BYTE_BUFFER, true, 1000000);
-        List<ColumnOrSuperColumn> columns = thriftClient_.get_slice(ByteBuffer.wrap(key.getBytes(Charsets.UTF_8)),parent,
+        List<ColumnOrSuperColumn> columns = thriftClient.get_slice(ByteBuffer.wrap(key.getBytes(Charsets.UTF_8)),parent,
                                                                     new SlicePredicate().setColumn_names(null).setSlice_range(range), ConsistencyLevel.ONE);
-        int size = columns.size();
 
         AbstractType validator;
         CfDef cfDef = getCfDef(columnFamily);
@@ -625,46 +305,32 @@ public class CliClient 
             {
                 SuperColumn superColumn = cosc.super_column;
 
-                css_.out.printf("=> (super_column=%s,", formatSuperColumnName(keyspace, columnFamily, superColumn));
+                sessionState.out.printf("=> (super_column=%s,", formatSuperColumnName(keyspace, columnFamily, superColumn));
                 for (Column col : superColumn.getColumns())
                 {
                     validator = getValidatorForValue(cfDef, col.getName());
-                    css_.out.printf("\n     (column=%s, value=%s, timestamp=%d)", formatSubcolumnName(keyspace, columnFamily, col),
+                    sessionState.out.printf("\n     (column=%s, value=%s, timestamp=%d)", formatSubcolumnName(keyspace, columnFamily, col),
                                     validator.getString(col.value), col.timestamp);
                 }
                 
-                css_.out.println(")");
+                sessionState.out.println(")");
             }
             else
             {
                 Column column = cosc.column;
                 validator = getValidatorForValue(cfDef, column.getName());
-                css_.out.printf("=> (column=%s, value=%s, timestamp=%d)\n", formatColumnName(keyspace, columnFamily, column),
+                sessionState.out.printf("=> (column=%s, value=%s, timestamp=%d)\n", formatColumnName(keyspace, columnFamily, column),
                                 validator.getString(column.value), column.timestamp);
             }
         }
         
-        css_.out.println("Returned " + size + " results.");
-    }
- 
-    private String formatSuperColumnName(String keyspace, String columnFamily, SuperColumn column) throws NotFoundException, TException, IllegalAccessException, InstantiationException, NoSuchFieldException
-    {
-        return getFormatTypeForColumn(getCfDef(keyspace,columnFamily).comparator_type).getString(column.name);
-    }
-
-    private String formatSubcolumnName(String keyspace, String columnFamily, Column subcolumn) throws NotFoundException, TException, IllegalAccessException, InstantiationException, NoSuchFieldException
-    {
-        return getFormatTypeForColumn(getCfDef(keyspace,columnFamily).subcomparator_type).getString(subcolumn.name);
-    }
-
-    private String formatColumnName(String keyspace, String columnFamily, Column column) throws NotFoundException, TException, IllegalAccessException, InstantiationException, NoSuchFieldException
-    {
-        return getFormatTypeForColumn(getCfDef(keyspace,columnFamily).comparator_type).getString(column.name);
+        sessionState.out.println("Returned " + columns.size() + " results.");
     }
 
     private AbstractType getFormatTypeForColumn(String compareWith)
     {
         Function function;
+        
         try
         {
             function = Function.valueOf(compareWith.toUpperCase());
@@ -675,7 +341,7 @@ public class CliClient 
             {
                 return FBUtilities.getComparator(compareWith);
             }
-            catch (ConfigurationException e1)
+            catch (ConfigurationException ce)
             {
                 StringBuilder errorMessage = new StringBuilder("Unknown comparator '" + compareWith + "'. ");
                 errorMessage.append("Available functions: ");
@@ -683,16 +349,17 @@ public class CliClient 
             }
         }
 
-        return function.validator;
+        return function.getValidator();
     }
 
     // Execute GET statement
-    private void executeGet(CommonTree ast) throws TException, NotFoundException, InvalidRequestException, UnavailableException, TimedOutException, IllegalAccessException, InstantiationException, ClassNotFoundException, NoSuchFieldException
+    private void executeGet(Tree statement)
+            throws TException, NotFoundException, InvalidRequestException, UnavailableException, TimedOutException, IllegalAccessException, InstantiationException, ClassNotFoundException, NoSuchFieldException
     {
         if (!CliMain.isConnected() || !hasKeySpace())
             return;
 
-        CommonTree columnFamilySpec = (CommonTree) ast.getChild(0);
+        Tree columnFamilySpec = statement.getChild(0);
         
         String key = CliCompiler.getKey(columnFamilySpec);
         String columnFamily = CliCompiler.getColumnFamily(columnFamilySpec);
@@ -709,9 +376,8 @@ public class CliClient 
             doSlice(keySpace, key, columnFamily, superColumnName);
             return;
         }
-        
         // table.cf['key']['column'] -- slice of a super, or get of a standard
-        if (columnSpecCnt == 1)
+        else if (columnSpecCnt == 1)
         {
             if (isSuper)
             {
@@ -733,7 +399,7 @@ public class CliClient 
         // The parser groks an arbitrary number of these so it is possible to get here.
         else
         {
-            css_.out.println("Invalid row, super column, or column specification.");
+            sessionState.out.println("Invalid row, super column, or column specification.");
             return;
         }
 
@@ -743,8 +409,8 @@ public class CliClient 
         // Perform a get()
         ColumnPath path = new ColumnPath(columnFamily);
         if(superColumnName != null) path.setSuper_column(superColumnName);
-        if(columnNameInBytes != null) path.setColumn(columnNameInBytes);
-        Column column = thriftClient_.get(ByteBuffer.wrap(key.getBytes(Charsets.UTF_8)), path, ConsistencyLevel.ONE).column;
+        path.setColumn(columnNameInBytes);
+        Column column = thriftClient.get(ByteBuffer.wrap(key.getBytes(Charsets.UTF_8)), path, ConsistencyLevel.ONE).column;
 
         byte[] columnValue = column.getValue();       
         String valueAsString;
@@ -752,10 +418,10 @@ public class CliClient 
         // we have ^(CONVERT_TO_TYPE <type>) inside of GET statement
         // which means that we should try to represent byte[] value according
         // to specified type
-        if (ast.getChildCount() == 2)
+        if (statement.getChildCount() == 2)
         {
             // getting ^(CONVERT_TO_TYPE <type>) tree 
-            Tree typeTree = ast.getChild(1).getChild(0);
+            Tree typeTree = statement.getChild(1).getChild(0);
             // .getText() will give us <type>
             String typeName = CliUtils.unescapeSQLString(typeTree.getText());
             // building AbstractType from <type>
@@ -772,7 +438,7 @@ public class CliClient 
         }
 
         // print results
-        css_.out.printf("=> (column=%s, value=%s, timestamp=%d)\n",
+        sessionState.out.printf("=> (column=%s, value=%s, timestamp=%d)\n",
                         formatColumnName(keySpace, columnFamily, column), valueAsString, column.timestamp);
     }
 
@@ -857,7 +523,7 @@ public class CliClient 
         try
         {
             ColumnParent parent = new ColumnParent(columnFamily);
-            slices = thriftClient_.get_indexed_slices(parent, clause, predicate, ConsistencyLevel.ONE);
+            slices = thriftClient.get_indexed_slices(parent, clause, predicate, ConsistencyLevel.ONE);
             printSliceList(columnFamilyDef, slices);
         }
         catch (InvalidRequestException e)
@@ -871,20 +537,20 @@ public class CliClient 
     }
 
     // Execute SET statement
-    private void executeSet(CommonTree ast)
-    throws TException, InvalidRequestException, UnavailableException, TimedOutException, NoSuchFieldException, InstantiationException, IllegalAccessException
+    private void executeSet(Tree statement)
+        throws TException, InvalidRequestException, UnavailableException, TimedOutException, NoSuchFieldException, InstantiationException, IllegalAccessException
     {
         if (!CliMain.isConnected() || !hasKeySpace())
             return;
         
         // ^(NODE_COLUMN_ACCESS <cf> <key> <column>)
-        CommonTree columnFamilySpec = (CommonTree) ast.getChild(0);
+        Tree columnFamilySpec = statement.getChild(0);
         
         String key = CliCompiler.getKey(columnFamilySpec);
         String columnFamily = CliCompiler.getColumnFamily(columnFamilySpec);
         int columnSpecCnt = CliCompiler.numColumnSpecifiers(columnFamilySpec);
-        String value = CliUtils.unescapeSQLString(ast.getChild(1).getText());
-        Tree valueTree = ast.getChild(1);
+        String value = CliUtils.unescapeSQLString(statement.getChild(1).getText());
+        Tree valueTree = statement.getChild(1);
         
         byte[] superColumnName = null;
         String columnName;
@@ -892,7 +558,7 @@ public class CliClient 
         // table.cf['key']
         if (columnSpecCnt == 0)
         {
-            css_.err.println("No column name specified, (type 'help' or '?' for help on syntax).");
+            sessionState.err.println("No column name specified, (type 'help' or '?' for help on syntax).");
             return;
         }
         // table.cf['key']['column'] = 'value'
@@ -929,42 +595,38 @@ public class CliClient 
             parent.setSuper_column(superColumnName);
         
         // do the insert
-        thriftClient_.insert(ByteBuffer.wrap(key.getBytes(Charsets.UTF_8)), parent,
+        thriftClient.insert(ByteBuffer.wrap(key.getBytes(Charsets.UTF_8)), parent,
                              new Column(columnNameInBytes, columnValueInBytes, FBUtilities.timestampMicros()), ConsistencyLevel.ONE);
         
-        css_.out.println("Value inserted.");
+        sessionState.out.println("Value inserted.");
     }
     
     private void executeShowClusterName() throws TException
     {
         if (!CliMain.isConnected())
             return;
-        css_.out.println(thriftClient_.describe_cluster_name());
+        
+        sessionState.out.println(thriftClient.describe_cluster_name());
     }
 
     /**
      * Add a keyspace
      * @param statement - a token tree representing current statement
      */
-    private void executeAddKeyspace(Tree statement)
+    private void executeAddKeySpace(Tree statement)
     {
 
         if (!CliMain.isConnected())
-        {
             return;
-        }
-        
-        // defaults
-        List<CfDef> columnList = new LinkedList<CfDef>();
         
         // first value is the keyspace name, after that it is all key=value
         String keyspaceName = statement.getChild(0).getText();
-        KsDef ksDef = new KsDef(keyspaceName, DEFAULT_PLACEMENT_STRATEGY, 1, columnList);
+        KsDef ksDef = new KsDef(keyspaceName, DEFAULT_PLACEMENT_STRATEGY, 1, new LinkedList<CfDef>());
 
         try
         {
-            css_.out.println(thriftClient_.system_add_keyspace(updateKsDefAttributes(statement, ksDef)));
-            keyspacesMap.put(keyspaceName, thriftClient_.describe_keyspace(keyspaceName));
+            sessionState.out.println(thriftClient.system_add_keyspace(updateKsDefAttributes(statement, ksDef)));
+            keyspacesMap.put(keyspaceName, thriftClient.describe_keyspace(keyspaceName));
         }
         catch (InvalidRequestException e)
         {
@@ -984,18 +646,15 @@ public class CliClient 
     private void executeAddColumnFamily(Tree statement)
     {
         if (!CliMain.isConnected() || !hasKeySpace())
-        {
             return;
-        }
 
         // first value is the column family name, after that it is all key=value
-        String columnFamilyName = statement.getChild(0).getText();
-        CfDef cfDef = new CfDef(keySpace, columnFamilyName);
+        CfDef cfDef = new CfDef(keySpace, statement.getChild(0).getText());
 
         try
         {
-            css_.out.println(thriftClient_.system_add_column_family(updateCfDefAttributes(statement, cfDef)));
-            keyspacesMap.put(keySpace, thriftClient_.describe_keyspace(keySpace));
+            sessionState.out.println(thriftClient.system_add_column_family(updateCfDefAttributes(statement, cfDef)));
+            keyspacesMap.put(keySpace, thriftClient.describe_keyspace(keySpace));
         }
         catch (InvalidRequestException e)
         {
@@ -1011,12 +670,10 @@ public class CliClient 
      * Update existing keyspace identified by name
      * @param statement - tree represeting statement
      */
-    private void executeUpdateKeyspace(Tree statement)
+    private void executeUpdateKeySpace(Tree statement)
     {
         if (!CliMain.isConnected())
-        {
             return;
-        }
 
         String keyspaceName = statement.getChild(0).getText();
         
@@ -1025,8 +682,8 @@ public class CliClient 
             KsDef currentKsDef = getKSMetaData(keyspaceName);
             KsDef updatedKsDef = updateKsDefAttributes(statement, currentKsDef);
 
-            css_.out.println(thriftClient_.system_update_keyspace(updatedKsDef));
-            keyspacesMap.put(keyspaceName, thriftClient_.describe_keyspace(keyspaceName));
+            sessionState.out.println(thriftClient.system_update_keyspace(updatedKsDef));
+            keyspacesMap.put(keyspaceName, thriftClient.describe_keyspace(keyspaceName));
         }
         catch (InvalidRequestException e)
         {
@@ -1045,17 +702,15 @@ public class CliClient 
     private void executeUpdateColumnFamily(Tree statement)
     {
         if (!CliMain.isConnected() || !hasKeySpace())
-        {
             return;
-        }
 
-        String columnFamilyName = statement.getChild(0).getText();
-        CfDef cfDef = getCfDef(columnFamilyName);
+        // first child is a column family name
+        CfDef cfDef = getCfDef(statement.getChild(0).getText());
 
         try
         {
-            css_.out.println(thriftClient_.system_update_column_family(updateCfDefAttributes(statement, cfDef)));
-            keyspacesMap.put(keySpace, thriftClient_.describe_keyspace(keySpace));
+            sessionState.out.println(thriftClient.system_update_column_family(updateCfDefAttributes(statement, cfDef)));
+            keyspacesMap.put(keySpace, thriftClient.describe_keyspace(keySpace));
         }
         catch (InvalidRequestException e)
         {
@@ -1190,59 +845,55 @@ public class CliClient 
 
     /**
      * Delete a keyspace
-     * @param ast - a token tree representing current statement
+     * @param statement - a token tree representing current statement
      * @throws TException - exception
      * @throws InvalidRequestException - exception
      * @throws NotFoundException - exception
      */
-    private void executeDelKeyspace(CommonTree ast) throws TException, InvalidRequestException, NotFoundException
+    private void executeDelKeySpace(Tree statement)
+            throws TException, InvalidRequestException, NotFoundException
     {
         if (!CliMain.isConnected())
-        {
             return;
-        }
 
-        String keyspaceName = ast.getChild(0).getText();
-
-        css_.out.println(thriftClient_.system_drop_keyspace(keyspaceName));
+        String keyspaceName = statement.getChild(0).getText();
+        sessionState.out.println(thriftClient.system_drop_keyspace(keyspaceName));
     }
 
     /**
      * Delete a column family
-     * @param ast - a token tree representing current statement
+     * @param statement - a token tree representing current statement
      * @throws TException - exception
      * @throws InvalidRequestException - exception
      * @throws NotFoundException - exception
      */
-    private void executeDelColumnFamily(CommonTree ast) throws TException, InvalidRequestException, NotFoundException
+    private void executeDelColumnFamily(Tree statement) 
+            throws TException, InvalidRequestException, NotFoundException
     {
         if (!CliMain.isConnected() || !hasKeySpace())
-        {
             return;
-        }
-        String columnName = ast.getChild(0).getText();
-        css_.out.println(thriftClient_.system_drop_column_family(columnName));
+
+        String columnName = statement.getChild(0).getText();
+        sessionState.out.println(thriftClient.system_drop_column_family(columnName));
     }
 
-    private void executeList(CommonTree ast)
-    throws TException, InvalidRequestException, NotFoundException, IllegalAccessException, InstantiationException, NoSuchFieldException, UnavailableException, TimedOutException
+    private void executeList(Tree statement)
+        throws TException, InvalidRequestException, NotFoundException, IllegalAccessException, InstantiationException, NoSuchFieldException, UnavailableException, TimedOutException
     {
         if (!CliMain.isConnected())
             return;
-
-        Iterator<CommonTree> iter = ast.getChildren().iterator();
-
+        
         // extract column family
-        String columnFamily = iter.next().getText();
+        String columnFamily = statement.getChild(0).getText();
 
         String startKey = "";
         String endKey = "";
         int limitCount = Integer.MAX_VALUE; // will reset to default later if it's not specified
 
         // optional arguments: key range and limit
-        while (iter.hasNext())
+        for (int i = 1; i < statement.getChildCount(); i++)
         {
-            CommonTree child = iter.next();
+            Tree child = statement.getChild(i);
             if (child.getType() == CliParser.NODE_KEY_RANGE)
             {
                 if (child.getChildCount() > 0)
@@ -1256,13 +907,13 @@ public class CliClient 
             {
                 if (child.getChildCount() != 1)
                 {
-                    css_.out.println("Invalid limit clause");
+                    sessionState.out.println("Invalid limit clause");
                     return;
                 }
                 limitCount = Integer.parseInt(child.getChild(0).getText());
                 if (limitCount <= 0)
                 {
-                    css_.out.println("Invalid limit " + limitCount);
+                    sessionState.out.println("Invalid limit " + limitCount);
                     return;
                 }
             }
@@ -1271,7 +922,7 @@ public class CliClient 
         if (limitCount == Integer.MAX_VALUE)
         {
             limitCount = 100;
-            css_.out.println("Using default limit of 100");
+            sessionState.out.println("Using default limit of 100");
         }
 
         CfDef columnFamilyDef = getCfDef(columnFamily);
@@ -1280,6 +931,7 @@ public class CliClient 
         SlicePredicate predicate = new SlicePredicate();
         SliceRange sliceRange = new SliceRange();
         sliceRange.setStart(new byte[0]).setFinish(new byte[0]);
+        sliceRange.setCount(limitCount);
         predicate.setSlice_range(sliceRange);
 
         // set the key range
@@ -1287,46 +939,42 @@ public class CliClient 
         range.setStart_key(startKey.getBytes()).setEnd_key(endKey.getBytes());
 
         ColumnParent columnParent = new ColumnParent(columnFamily);
-        List<KeySlice> keySlices = thriftClient_.get_range_slices(columnParent, predicate, range, ConsistencyLevel.ONE);
-        int toIndex = keySlices.size();
-
-        if (limitCount < keySlices.size())
-        {
-
-            // limitCount could be Integer.MAX_VALUE
-            toIndex = limitCount;
-        }
-
-
-        printSliceList(columnFamilyDef, keySlices.subList(0, toIndex));
+        List<KeySlice> keySlices = thriftClient.get_range_slices(columnParent, predicate, range, ConsistencyLevel.ONE);
+        printSliceList(columnFamilyDef, keySlices);
     }
 
+    // SHOW API VERSION
     private void executeShowVersion() throws TException
     {
         if (!CliMain.isConnected())
             return;
-        css_.out.println(thriftClient_.describe_version());
+        
+        sessionState.out.println(thriftClient.describe_version());
     }
 
-    // process "show tables" statement
-    private void executeShowTables() throws TException, InvalidRequestException
+    // SHOW KEYSPACES
+    private void executeShowKeySpaces() throws TException, InvalidRequestException
     {
         if (!CliMain.isConnected())
             return;
         
-        List<KsDef> tables = thriftClient_.describe_keyspaces();
-        for (KsDef t : tables) {
-            describeTableInternal(t.name, t);
+        for (KsDef keySpace : thriftClient.describe_keyspaces()) {
+            describeKeySpace(keySpace.name, keySpace);
         }
     }
-    
+
+    /**
+     * Returns true if this.keySpace is set, false otherwise
+     * @return boolean
+     */
     private boolean hasKeySpace() 
     {
     	if (keySpace == null)
         {
-            css_.out.println("Not authenticated to a working keyspace.");
+            sessionState.out.println("Not authenticated to a working keyspace.");
             return false;
         }
+        
         return true;
     }
     
@@ -1335,11 +983,10 @@ public class CliClient 
         return keySpace == null ? "unknown" : keySpace;
     }
     
-    public void setKeyspace(String keySpace) throws NotFoundException, InvalidRequestException, TException 
+    public void setKeySpace(String keySpace) throws NotFoundException, InvalidRequestException, TException 
     {
         this.keySpace = keySpace;
-        //We do nothing with the return value, but it hits a cache and
-        // the tab-completer.
+        // We do nothing with the return value, but it hits a cache and the tab-completer.
         getKSMetaData(keySpace);
     }
     
@@ -1352,27 +999,27 @@ public class CliClient 
     {
         this.username = username;
     }
-    
-    private void executeUseTable(CommonTree ast) throws TException
+
+    // USE <keyspace_name>
+    private void executeUseKeySpace(Tree statement) throws TException
     {
         if (!CliMain.isConnected())
             return;
-    	
-        int childCount = ast.getChildCount();
-        String tableName, username = null, password = null;
-        assert(childCount > 0);
+
+        int childCount = statement.getChildCount();
+        String keySpaceName, username = null, password = null;
 
         // Get table name
-        tableName = ast.getChild(0).getText();
+        keySpaceName = statement.getChild(0).getText();
         
         if (childCount == 3) {
-            username  = ast.getChild(1).getText();
-            password  = ast.getChild(2).getText();
+            username  = statement.getChild(1).getText();
+            password  = statement.getChild(2).getText();
         }
         
-        if( tableName == null ) 
+        if (keySpaceName == null)
         {
-            css_.out.println("Keyspace argument required");
+            sessionState.out.println("Keyspace argument required");
             return;
         }
         
@@ -1382,7 +1029,7 @@ public class CliClient 
         	Map<String, String> credentials = new HashMap<String, String>();
         	
         	
-        	thriftClient_.set_keyspace(tableName);
+        	thriftClient.set_keyspace(keySpaceName);
    
         	if (username != null && password != null) 
         	{
@@ -1391,74 +1038,74 @@ public class CliClient 
         	    credentials.put(SimpleAuthenticator.USERNAME_KEY, username);
                 credentials.put(SimpleAuthenticator.PASSWORD_KEY, password);
                 authRequest = new AuthenticationRequest(credentials);
-                thriftClient_.login(authRequest);
+                thriftClient.login(authRequest);
         	}
         	
-            keySpace = tableName;
+            keySpace = keySpaceName;
             this.username = username != null ? username : "default";
             
-            if (!(keyspacesMap.containsKey(keySpace))) 
-            {
-                keyspacesMap.put(keySpace, thriftClient_.describe_keyspace(keySpace));
-            }
-            Set<String> cfnames = new HashSet<String>();
-            KsDef ksd = keyspacesMap.get(keySpace);
-            for (CfDef cfd : ksd.cf_defs) {
-                cfnames.add(cfd.name);
-            }
-            CliMain.updateCompletor(cfnames);
-            css_.out.println("Authenticated to keyspace: " + keySpace);
+            CliMain.updateCompletor(CliUtils.getCfNamesByKeySpace(getKSMetaData(keySpace)));
+            sessionState.out.println("Authenticated to keyspace: " + keySpace);
         } 
         catch (AuthenticationException e) 
         {
-            css_.err.println("Exception during authentication to the cassandra node: " +
-            		"verify keyspace exists, and you are using correct credentials.");
+            sessionState.err.println("Exception during authentication to the cassandra node: " +
+            		                 "verify keyspace exists, and you are using correct credentials.");
         } 
         catch (AuthorizationException e) 
         {
-            css_.err.println("You are not authorized to use keyspace: " + tableName);
+            sessionState.err.println("You are not authorized to use keyspace: " + keySpaceName);
         }
         catch (InvalidRequestException e)
         {
-            css_.err.println(tableName + " does not exist.");
+            sessionState.err.println(keySpaceName + " does not exist.");
         }
         catch (NotFoundException e)
         {
-            css_.err.println(tableName + " does not exist.");
+            sessionState.err.println(keySpaceName + " does not exist.");
         } 
         catch (TException e) 
         {
-            if (css_.debug)
+            if (sessionState.debug)
                 e.printStackTrace();
             
-            css_.err.println("Login failure. Did you specify 'keyspace', 'username' and 'password'?");
+            sessionState.err.println("Login failure. Did you specify 'keyspace', 'username' and 'password'?");
         }
     }
 
-    private void describeTableInternal(String tableName, KsDef metadata) throws TException {
+    private void describeKeySpace(String keySpaceName, KsDef metadata) throws TException
+    {
         // Describe and display
-        css_.out.println("Keyspace: " + tableName + ":");
+        sessionState.out.println("Keyspace: " + keySpaceName + ":");
         try
         {
             KsDef ks_def;
-            ks_def = metadata == null ? thriftClient_.describe_keyspace(tableName) : metadata;
-            css_.out.println("  Replication Factor: " + ks_def.replication_factor);
-            css_.out.println("  Column Families:");
+            ks_def = metadata == null ? thriftClient.describe_keyspace(keySpaceName) : metadata;
+            sessionState.out.println("  Replication Factor: " + ks_def.replication_factor);
+            sessionState.out.println("  Column Families:");
 
             for (CfDef cf_def : ks_def.cf_defs)
             {
-                css_.out.printf("    ColumnFamily: %s%s\n", cf_def.name, cf_def.column_type.equals("Super") ? " (Super)" : "");
+                sessionState.out.printf("    ColumnFamily: %s%s\n", cf_def.name, cf_def.column_type.equals("Super") ? " (Super)" : "");
+
                 if (cf_def.comment != null && !cf_def.comment.isEmpty())
-                    css_.out.printf("    \"%s\"\n", cf_def.comment);
-                css_.out.printf("      Columns sorted by: %s%s\n", cf_def.comparator_type, cf_def.column_type.equals("Super") ? "/" + cf_def.subcomparator_type : "");
+                {
+                    sessionState.out.printf("    \"%s\"\n", cf_def.comment);
+                }
+                
+                sessionState.out.printf("      Columns sorted by: %s%s\n", cf_def.comparator_type, cf_def.column_type.equals("Super") ? "/" + cf_def.subcomparator_type : "");
+
                 if (cf_def.subcomparator_type != null)
-                    css_.out.println("      Subcolumns sorted by: " + cf_def.comparator_type);
-                css_.out.printf("      Row cache size / save period: %s/%s\n", cf_def.row_cache_size, cf_def.row_cache_save_period_in_seconds);
-                css_.out.printf("      Key cache size / save period: %s/%s\n", cf_def.key_cache_size, cf_def.key_cache_save_period_in_seconds);
-                css_.out.printf("      Memtable thresholds: %s/%s/%s\n",
+                {
+                    sessionState.out.println("      Subcolumns sorted by: " + cf_def.comparator_type);
+                }
+
+                sessionState.out.printf("      Row cache size / save period: %s/%s\n", cf_def.row_cache_size, cf_def.row_cache_save_period_in_seconds);
+                sessionState.out.printf("      Key cache size / save period: %s/%s\n", cf_def.key_cache_size, cf_def.key_cache_save_period_in_seconds);
+                sessionState.out.printf("      Memtable thresholds: %s/%s/%s\n",
                                 cf_def.memtable_operations_in_millions, cf_def.memtable_throughput_in_mb, cf_def.memtable_flush_after_mins);
-                css_.out.printf("      GC grace seconds: %s\n", cf_def.gc_grace_seconds);
-                css_.out.printf("      Compaction min/max thresholds: %s/%s\n", cf_def.min_compaction_threshold, cf_def.max_compaction_threshold);
+                sessionState.out.printf("      GC grace seconds: %s\n", cf_def.gc_grace_seconds);
+                sessionState.out.printf("      Compaction min/max thresholds: %s/%s\n", cf_def.min_compaction_threshold, cf_def.max_compaction_threshold);
 
                 if (cf_def.getColumn_metadataSize() != 0)
                 {
@@ -1467,22 +1114,22 @@ public class CliClient 
 
                     AbstractType columnNameValidator = getFormatTypeForColumn(cf_def.comparator_type);
 
-                    css_.out.println(leftSpace + "Column Metadata:");
+                    sessionState.out.println(leftSpace + "Column Metadata:");
                     for (ColumnDef columnDef : cf_def.getColumn_metadata())
                     {
                         String columnName = columnNameValidator.getString(columnDef.name);
 
-                        css_.out.println(leftSpace + "  Column Name: " + columnName);
-                        css_.out.println(columnLeftSpace + "Validation Class: " + columnDef.getValidation_class());
+                        sessionState.out.println(leftSpace + "  Column Name: " + columnName);
+                        sessionState.out.println(columnLeftSpace + "Validation Class: " + columnDef.getValidation_class());
 
                         if (columnDef.isSetIndex_name())
                         {
-                            css_.out.println(columnLeftSpace + "Index Name: " + columnDef.getIndex_name());
+                            sessionState.out.println(columnLeftSpace + "Index Name: " + columnDef.getIndex_name());
                         }
 
                         if (columnDef.isSetIndex_type())
                         {
-                            css_.out.println(columnLeftSpace + "Index Type: " + columnDef.getIndex_type().name());
+                            sessionState.out.println(columnLeftSpace + "Index Type: " + columnDef.getIndex_type().name());
                         }
                     }
                 }
@@ -1490,38 +1137,35 @@ public class CliClient 
         }
         catch (InvalidRequestException e)
         {
-            css_.out.println("Invalid request: " + e);
+            sessionState.out.println("Invalid request: " + e);
         }
         catch (NotFoundException e)
         {
-            css_.out.println("Keyspace " + tableName + " could not be found.");
+            sessionState.out.println("Keyspace " + keySpaceName + " could not be found.");
         }
     }
-    // process a statement of the form: describe table <tablename> 
-    private void executeDescribeTable(CommonTree ast) throws TException
+    // DESCRIBE KEYSPACE <keyspace_name> 
+    private void executeDescribeKeySpace(Tree statement) throws TException
     {
         if (!CliMain.isConnected())
             return;
 
-        // Get table name
-        int childCount = ast.getChildCount();
-        assert(childCount == 1);
-
-        String tableName = ast.getChild(0).getText();
+        // Get keySpace name
+        String keySpaceName = statement.getChild(0).getText();
 
-        if( tableName == null ) {
-            css_.out.println("Keyspace argument required");
+        if( keySpaceName == null ) {
+            sessionState.out.println("Keyspace argument required");
             return;
         }
         
-        describeTableInternal(tableName, null);
+        describeKeySpace(keySpaceName, null);
     }
 
     // process a statement of the form: connect hostname/port
-    private void executeConnect(CommonTree ast)
+    private void executeConnect(Tree statement)
     {
-        int portNumber = Integer.parseInt(ast.getChild(1).getText());
-        Tree idList = ast.getChild(0);
+        Tree idList = statement.getChild(0);
+        int portNumber = Integer.parseInt(statement.getChild(1).getText());
         
         StringBuilder hostName = new StringBuilder();
         int idCount = idList.getChildCount(); 
@@ -1535,9 +1179,9 @@ public class CliClient 
         CliMain.disconnect();
 
         // now, connect to the newly specified host name and port
-        css_.hostName = hostName.toString();
-        css_.thriftPort = portNumber;
-        CliMain.connect(css_.hostName, css_.thriftPort);
+        sessionState.hostName = hostName.toString();
+        sessionState.thriftPort = portNumber;
+        CliMain.connect(sessionState.hostName, sessionState.thriftPort);
     }
 
     /**
@@ -1720,7 +1364,7 @@ public class CliClient 
      * Converts column name into byte[] according to comparator type
      * @param column - column name from parser
      * @param columnFamily - column family name from parser
-     * @return byte[] - array of bytes in which column name was converted according to comparator type
+     * @return ByteBuffer - array of bytes in which column name was converted according to comparator type
      * @throws NoSuchFieldException - raised from getFormatTypeForColumn call
      * @throws InstantiationException - raised from getFormatTypeForColumn call
      * @throws IllegalAccessException - raised from getFormatTypeForColumn call
@@ -1780,7 +1424,7 @@ public class CliClient 
         {
             byte[] nameInBytes = columnDefinition.getName();
 
-            if (nameInBytes.equals(columnNameInBytes))
+            if (Arrays.equals(nameInBytes, columnNameInBytes))
             {
                 return getFormatTypeForColumn(columnDefinition.getValidation_class());
             }
@@ -1948,8 +1592,8 @@ public class CliClient 
 
         for (KeySlice ks : slices)
         {
-            css_.out.printf("-------------------\n");
-            css_.out.printf("RowKey: %s\n", ByteBufferUtil.string(ks.key, Charsets.UTF_8));
+            sessionState.out.printf("-------------------\n");
+            sessionState.out.printf("RowKey: %s\n", ByteBufferUtil.string(ks.key, Charsets.UTF_8));
 
             Iterator<ColumnOrSuperColumn> iterator = ks.getColumnsIterator();
 
@@ -1962,27 +1606,48 @@ public class CliClient 
                     Column col = columnOrSuperColumn.column;
                     validator = getValidatorForValue(columnFamilyDef, col.getName());
 
-                    css_.out.printf("=> (column=%s, value=%s, timestamp=%d)\n",
+                    sessionState.out.printf("=> (column=%s, value=%s, timestamp=%d)\n",
                                     formatColumnName(keySpace, columnFamilyName, col), validator.getString(col.value), col.timestamp);
                 }
                 else if (columnOrSuperColumn.super_column != null)
                 {
                     SuperColumn superCol = columnOrSuperColumn.super_column;
-                    css_.out.printf("=> (super_column=%s,", formatSuperColumnName(keySpace, columnFamilyName, superCol));
+                    sessionState.out.printf("=> (super_column=%s,", formatSuperColumnName(keySpace, columnFamilyName, superCol));
 
                     for (Column col : superCol.columns)
                     {
                         validator = getValidatorForValue(columnFamilyDef, col.getName());
 
-                        css_.out.printf("\n     (column=%s, value=%s, timestamp=%d)",
+                        sessionState.out.printf("\n     (column=%s, value=%s, timestamp=%d)",
                                         formatSubcolumnName(keySpace, columnFamilyName, col), validator.getString(col.value), col.timestamp);
                     }
 
-                    css_.out.println(")");
+                    sessionState.out.println(")");
                 }
             }
         }
 
-        css_.out.printf("\n%d Row%s Returned.\n", slices.size(), (slices.size() > 1 ? "s" : ""));
+        sessionState.out.printf("\n%d Row%s Returned.\n", slices.size(), (slices.size() > 1 ? "s" : ""));
+    }
+
+    // returns super column name in human-readable format
+    private String formatSuperColumnName(String keyspace, String columnFamily, SuperColumn column)
+            throws NotFoundException, TException, IllegalAccessException, InstantiationException, NoSuchFieldException
+    {
+        return getFormatTypeForColumn(getCfDef(keyspace,columnFamily).comparator_type).getString(column.name);
+    }
+
+    // retuns sub-column name in human-readable format
+    private String formatSubcolumnName(String keyspace, String columnFamily, Column subcolumn)
+            throws NotFoundException, TException, IllegalAccessException, InstantiationException, NoSuchFieldException
+    {
+        return getFormatTypeForColumn(getCfDef(keyspace,columnFamily).subcomparator_type).getString(subcolumn.name);
+    }
+
+    // retuns column name in human-readable format
+    private String formatColumnName(String keyspace, String columnFamily, Column column)
+            throws NotFoundException, TException, IllegalAccessException, InstantiationException, NoSuchFieldException
+    {
+        return getFormatTypeForColumn(getCfDef(keyspace, columnFamily).comparator_type).getString(ByteBuffer.wrap(column.getName()));
     }
 }

Modified: cassandra/branches/cassandra-0.7/src/java/org/apache/cassandra/cli/CliCompiler.java
URL: http://svn.apache.org/viewvc/cassandra/branches/cassandra-0.7/src/java/org/apache/cassandra/cli/CliCompiler.java?rev=1027181&r1=1027180&r2=1027181&view=diff
==============================================================================
--- cassandra/branches/cassandra-0.7/src/java/org/apache/cassandra/cli/CliCompiler.java (original)
+++ cassandra/branches/cassandra-0.7/src/java/org/apache/cassandra/cli/CliCompiler.java Mon Oct 25 16:10:31 2010
@@ -56,9 +56,9 @@ public class CliCompiler
         }
     }
 
-    public static CommonTree compileQuery(String query)
+    public static Tree compileQuery(String query)
     {
-        CommonTree queryTree;
+        Tree queryTree;
         
         try
         {
@@ -70,7 +70,7 @@ public class CliCompiler
             CliParser parser = new CliParser(tokens);
 
             // start parsing...
-            queryTree = (CommonTree)(parser.root().getTree());
+            queryTree = (Tree)(parser.root().getTree());
 
             // semantic analysis if any...
             //  [tbd]
@@ -88,24 +88,24 @@ public class CliCompiler
      * NODE_COLUMN_ACCESS related functions.
      */
 
-    public static String getColumnFamily(CommonTree astNode)
+    public static String getColumnFamily(Tree astNode)
     {
         return astNode.getChild(0).getText();
     }
 
-    public static String getKey(CommonTree astNode)
+    public static String getKey(Tree astNode)
     {
         return CliUtils.unescapeSQLString(astNode.getChild(1).getText());
     }
 
-    public static int numColumnSpecifiers(CommonTree astNode)
+    public static int numColumnSpecifiers(Tree astNode)
     {
         // Skip over table, column family and rowKey
         return astNode.getChildCount() - 2;
     }
 
     // Returns the pos'th (0-based index) column specifier in the astNode
-    public static String getColumn(CommonTree astNode, int pos)
+    public static String getColumn(Tree astNode, int pos)
     {
         // Skip over table, column family and rowKey
         return CliUtils.unescapeSQLString(astNode.getChild(pos + 2).getText()); 

Modified: cassandra/branches/cassandra-0.7/src/java/org/apache/cassandra/cli/CliMain.java
URL: http://svn.apache.org/viewvc/cassandra/branches/cassandra-0.7/src/java/org/apache/cassandra/cli/CliMain.java?rev=1027181&r1=1027180&r2=1027181&view=diff
==============================================================================
--- cassandra/branches/cassandra-0.7/src/java/org/apache/cassandra/cli/CliMain.java (original)
+++ cassandra/branches/cassandra-0.7/src/java/org/apache/cassandra/cli/CliMain.java Mon Oct 25 16:10:31 2010
@@ -95,15 +95,8 @@ public class CliMain
         {
             try {
                 thriftClient.set_keyspace(sessionState.keyspace);
-                cliClient.setKeyspace(sessionState.keyspace);
-
-                Set<String> cfnames = new HashSet<String>();
-                KsDef ksd = cliClient.getKSMetaData(sessionState.keyspace);
-                for (CfDef cfd : ksd.cf_defs) {
-                    cfnames.add(cfd.name);
-                }
-                updateCompletor(cfnames);
-                
+                cliClient.setKeySpace(sessionState.keyspace);
+                updateCompletor(CliUtils.getCfNamesByKeySpace(cliClient.getKSMetaData(sessionState.keyspace)));
             }
             catch (InvalidRequestException e)
             {
@@ -224,22 +217,15 @@ public class CliMain
 
         try
         {
-            cliClient.executeCLIStmt(query);
+            cliClient.executeCLIStatement(query);
         }
         catch (Exception e)
         {
             String errorTemplate = sessionState.inFileMode() ? "Line " + lineNumber + " => " : "";
-            
-            if (e instanceof InvalidRequestException)
-            {
-                sessionState.err.println(errorTemplate + ((InvalidRequestException) e).getWhy());
-            }
-            else
-            {
-                String message = (e.getCause() == null) ? e.getMessage() : e.getCause().getMessage();
-                sessionState.err.println(errorTemplate + message);
-            }
-            
+
+            String message = (e.getCause() == null) ? e.getMessage() : e.getCause().getMessage();
+            sessionState.err.println(errorTemplate + message);
+
             if (sessionState.debug)
             {
                 e.printStackTrace(sessionState.err);

Modified: cassandra/branches/cassandra-0.7/src/java/org/apache/cassandra/cli/CliUtils.java
URL: http://svn.apache.org/viewvc/cassandra/branches/cassandra-0.7/src/java/org/apache/cassandra/cli/CliUtils.java?rev=1027181&r1=1027180&r2=1027181&view=diff
==============================================================================
--- cassandra/branches/cassandra-0.7/src/java/org/apache/cassandra/cli/CliUtils.java (original)
+++ cassandra/branches/cassandra-0.7/src/java/org/apache/cassandra/cli/CliUtils.java Mon Oct 25 16:10:31 2010
@@ -1,6 +1,11 @@
 package org.apache.cassandra.cli;
 
+import org.apache.cassandra.thrift.CfDef;
 import org.apache.cassandra.thrift.IndexOperator;
+import org.apache.cassandra.thrift.KsDef;
+
+import java.util.LinkedHashSet;
+import java.util.Set;
 /*
  * 
  * Licensed to the Apache Software Foundation (ASF) under one
@@ -127,4 +132,21 @@ public class CliUtils
 
         return null;
     }
+
+    /**
+     * Returns set of column family names in specified keySpace.
+     * @param keySpace - keyspace definition to get column family names from.
+     * @return Set - column family names
+     */
+    public static Set<String> getCfNamesByKeySpace(KsDef keySpace)
+    {
+        Set<String> names = new LinkedHashSet<String>();
+
+        for (CfDef cfDef : keySpace.getCf_defs())
+        {
+            names.add(cfDef.getName());
+        }
+
+        return names;
+    }
 }