Cassandra DB Connetor in Java, using Thrift API

This simple connector class for making a connection to a Cassandra cluster. It’s genesis was the result of working towards a Thrift API loader for a Cassandra evaluation implementation. You can read bout that, here: Cassandra – A Use case examined (IP data)

/*
------------------------------------------------------------------------
 $Id: CassDB.java,v 1.1 2012/03/13 23:20:02 ddemartini Exp $
 $Revision: 1.1 $
 $Date: 2012/03/13 23:20:02 $
 $Name:  $
------------------------------------------------------------------------
 Sample connector program.  Requires two environment variables be setup
 to executed
    host:    hostname of Cassandra cluster node member
    port:    connector port - default is 9160, this should be default
------------------------------------------------------------------------
*/

package base;
import org.apache.cassandra.thrift.Cassandra;
import org.apache.thrift.protocol.*;
import org.apache.thrift.transport.*;

public class CassDB {
      
  /* Delcare private properties used for client server communications */
  private TTransport transport;
  private TProtocol  protocol; 
  private TSocket    socket;

  /* Constructor takes supplied host and port */
  public CassDB(String host, int port) throws Exception {
    try {
      socket    = new TSocket(host,port);
      transport = new TFramedTransport(socket);
      protocol  = new TBinaryProtocol(transport);
    } catch(Exception e){
      System.out.println("Exception "+e);
    }
  }

  /* Opener */
  public void open() throws Exception {
    try {
      transport.open();
    } catch(Exception e) {
      System.out.println("Exception "+e);
    }
  }

  /* Closer */
  public void close() throws Exception {
    try {
      transport.close();
    } catch(Exception e) {
      System.out.println("Exception "+e);
    }
  }

  /* getClient method */
  public Cassandra.Client getClient() {
    Cassandra.Client client = new Cassandra.Client(protocol);
    return client;
  }

 /* end */
}

Calling and using this class is pretty simple. Here are some excerpts from a program I’ll post later:

[...]
package c01;
import base.*;
[...]
    String host = Util.envOrProp("host");
    int port    = Integer.parseInt(Util.envOrProp("port"));
[...]
    /* instance db connector and open connection */
    CassDB db   = new CassDB(host,port); 
    db.open();
[...]

1 comment for “Cassandra DB Connetor in Java, using Thrift API

Comments are closed.