package me.prettyprint.cassandra.examples;

import static me.prettyprint.cassandra.utils.StringUtils.bytes;
import static me.prettyprint.cassandra.utils.StringUtils.string;
import me.prettyprint.cassandra.model.HectorException;
import me.prettyprint.cassandra.service.CassandraClient;
import me.prettyprint.cassandra.service.CassandraClientPool;
import me.prettyprint.cassandra.service.CassandraClientPoolFactory;
import me.prettyprint.cassandra.service.Keyspace;

import org.apache.cassandra.thrift.Column;
import org.apache.cassandra.thrift.ColumnPath;

/**
 * Example client that uses the cassandra hector client.
 *
 * @author Ran Tavory (rantav@gmail.com)
 *
 */
public class ExampleClient {

  public static void main(String[] args) throws HectorException {
    CassandraClientPool pool = CassandraClientPoolFactory.INSTANCE.get();
    CassandraClient client = pool.borrowClient("tush", 9160);
    // A load balanced version would look like this:
    // CassandraClient client = pool.borrowClient(new String[] {"cas1:9160", "cas2:9160", "cas3:9160"});

    try {
      Keyspace keyspace = client.getKeyspace("Keyspace1");
      ColumnPath columnPath = new ColumnPath("Standard1");
      columnPath.setColumn(bytes("column-name"));

      // insert
      keyspace.insert("key", columnPath, bytes("value"));

      // read
      Column col = keyspace.getColumn("key", columnPath);

      System.out.println("Read from cassandra: " + string(col.getValue()));

      // This line makes sure that even if the client had failures and recovered, a correct
      // releaseClient is called, on the up to date client.
      client = keyspace.getClient();
    } finally {
      // return client to pool. do it in a finally block to make sure it's executed
      pool.releaseClient(client);
    }
  }
}

@@ -1048,24 +1048,54 @@
 3:9160%22%7D);%0A%0A
+    Keyspace keyspace = null;%0A
     try %7B%0A  
@@ -1094,33 +1094,24 @@
 try %7B%0A      
-Keyspace 
 keyspace = c
@@ -1473,24 +1473,40 @@
 Value()));%0A%0A
+    %7D finally %7B%0A
       // Thi
@@ -1645,16 +1645,48 @@
 client.%0A
+      if (keyspace != null) %7B%0A  
       cl
@@ -1716,30 +1716,16 @@
 nt();%0A  
-  %7D finally %7B%0A
       //
@@ -1806,16 +1806,18 @@
 d%0A      
+  
 pool.rel
@@ -1836,16 +1836,24 @@
 lient);%0A
+      %7D%0A
     %7D%0A  

Fix a bug when releasing a client in the ExampleClient