Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Its a restart... initial get and set and delete done

  • Loading branch information...
commit 71f51ae55f5ca5464021613f64dd6195ec77e524 1 parent cb58011
@wolpert authored
View
5 .classpath
@@ -11,5 +11,10 @@
<classpathentry kind="src" path="test/unit"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
<classpathentry kind="con" path="com.springsource.sts.grails.core.CLASSPATH_CONTAINER"/>
+ <classpathentry kind="src" path="tomcat-1.2.2-src-groovy">
+ <attributes>
+ <attribute name="com.springsource.sts.grails.core.SOURCE_FOLDER" value="true"/>
+ </attributes>
+ </classpathentry>
<classpathentry kind="output" path="web-app/WEB-INF/classes"/>
</classpath>
View
7 .project
@@ -22,4 +22,11 @@
<nature>org.eclipse.jdt.core.javanature</nature>
<nature>org.eclipse.wst.common.project.facet.core.nature</nature>
</natures>
+ <linkedResources>
+ <link>
+ <name>tomcat-1.2.2-src-groovy</name>
+ <type>2</type>
+ <location>/home/wolpert/.grails/1.2.2/projects/cassandra/plugins/tomcat-1.2.2/src/groovy</location>
+ </link>
+ </linkedResources>
</projectDescription>
View
2  CassandraGrailsPlugin.groovy
@@ -1,6 +1,6 @@
class CassandraGrailsPlugin {
// the plugin version
- def version = "0.5.4"
+ def version = "0.7.0-20101025"
// the version or versions of Grails the plugin is designed for
def grailsVersion = "1.2.2 > *"
// the other plugins this plugin depends on
View
101 README
@@ -1,28 +1,15 @@
http://www.opensource.org/licenses/apache2.0.php
-Cassandra Version: 0.6.0
-Hector Version: 0.6.0-14
-Grails: 1.2.2
-
-NOTE ABOUT CASSANDRA 0.7:
-
- The upcoming change to cassandra 0.7.0 will impact the grails plugin big
- time. Specifically, the plugin wraps hector which will have lots of changes
- too. I'm going to try to make it as backwards compatiable as possible,
- but I'd rather use the features of cassandra and hector have added or changed
- when possible. We will be compatiable to grails 1.2.2 at least. I will also
- be checking for compatibility against grails 1.3.5.
-
- Stay tune!
-
-RECENT CHANGES:
- 0.5.0:
- Please note that now, values stored in cassandra are NOT converted to
- string then byte[] if they are already a byte[]. This is a significant
- change that WILL impact data already stored. (In reality, the way I was
- doing it before was wrong.) Expect another change soon on deciding what
- to do on values coming back. (Right now I convert them to strings. I will
- make that optional.)
+Cassandra Version: 0.7.0
+Hector Version: 0.7.0-19_10212010
+Grails: 1.2.2 or higher
+
+
+NOTE:
+This is INCOMPATABLE with cassandra 0.6 or earlier. It will also be incompatiable
+with earlier versions of this own plugin. You'll have to re-do the api calls
+when upgrading to this version of grails-cassandra.
+
ABOUT
@@ -31,7 +18,8 @@ from within grails. It is not intended to be a GORM mapping layer.
It specifically wraps the Hector (http://github.com/rantav/hector) API which
makes it easy to connect to Cassandra without dealing with the thrift layer.
-Hector also provides for connection pooling, etc.
+Hector also provides for connection pooling, etc. Hector has gone through
+a new API version, so this plugin has to as well.
Goals:
@@ -41,63 +29,20 @@ and optionally hiding 'NotFound' exceptions. (The ruby Cassandra plugin
returns an empty hash if a searched for value does not exist. Java plugin
throws an exception.)
-INSTALLATION
-
-You can either install via the standard grails technique:
-
- grails install-plugin cassandra
-
-or download the latest zip from github download section.
-
-USAGE
-
-Once the plugin is installed, grails will inject the Cassandra service
-into any controller or service that defines 'cassandraService' variable.
-
-By default, this plugin will connect to Cassandra running at localhost:9160
-using the keyspace 'Keyspace1' for all queries. To change this, setup in
-your grails-app/conf/spring/resources.groovy file:
-
-beans = {
- cassandraService(codehead.CassandraService){
- servers=["localhost:9160","192.168.2.1:9160"] as String[]
- //servers=["localhost:9160"] // for just one server
- defaultKeyspace="GeneralKeyspace"
- }
-}
-
-The above configuration will allow for server fail-over to multiple Cassandra
-servers running, and default requests to the 'GeneralKeyspace' named Keyspace.
-
-
-EXAMPLES
-
-import java.util.Date
-class CassandraLookupController {
- def cassandraService
- def index = {
- def now = new Date().toString()
- def old_value = cassandraService.setColumnValue("Users","2","login_date",now) //column family, key, col_name, value
- def new_value = cassandraService.getColumnValue("Users","2","login_date")
- // Example that uses a superColumnFamily
- def old_scf_value = cassandraService.setColumnValue("Classes","chemistry","textbook","title","Quantum for Dummies") // column family, key, supercolumn, col_nam, value
- def new_scf_value = cassandraService.getColumnValue("Classes","chemistry","textbook","title")
-
- def str = "Login date was $old_value and now is $new_value"
- render(str)
- }
-}
-Note that you also have access to the Hector objects for connecting to
-Cassandra. More test cases will be generated to show examples on how to do
-this. Until then, you can lookup how the service uses Hector in the code.
+UNDER DEVELOPMENT:
+The development for this plugin has re-started from scratch due to the
+extensive (and valuable) changes to Hector. New versions will be
+labeled 0.7 going forward. No new plugin will be provided to the grails
+repository until its usable in production. Please review the unit test
+CassandraServiceTest to see the direction of the plugin going forward. If you
+are testing this yourself, you'll need Cassandra 0.7b2 running, and make sure
+you loaded the schema from the YAML file as shown in this post:
+http://wiki.apache.org/cassandra/FAQ#no_keyspaces
-TODO
-Some tasks in progress
- - Add in ability to set timestamps
- - Create CassandraHashMap
- - Test cases, better instructions.
+Finally, note that you will have full access to Hector directly if you do not
+want the helper methods provided in the CassandraService layer.
View
5 grails-app/conf/spring/resources.groovy
@@ -1,8 +1,9 @@
beans = {
cassandraService(codehead.CassandraService){
- servers=["localhost:9160"] // add more servers as needed
- defaultKeyspace="Keyspace1"
+ servers="localhost:9160"
+ keyspaceName="Keyspace1"
+ clusterName="Main"
hideNotFoundExceptions=true
}
}
View
366 grails-app/services/codehead/CassandraService.groovy
@@ -7,108 +7,106 @@ import java.util.LinkedHashMap;
import java.util.TimeZone;
import java.util.UUID;
-import me.prettyprint.cassandra.service.CassandraClientPool
-import me.prettyprint.cassandra.service.CassandraClientPoolFactory
-import me.prettyprint.cassandra.service.CassandraClient
-import me.prettyprint.cassandra.service.Keyspace
-
-import static me.prettyprint.cassandra.utils.StringUtils.bytes;
-import static me.prettyprint.cassandra.utils.StringUtils.string;
-
-import org.apache.cassandra.db.marshal.TimeUUIDType;
-import org.apache.cassandra.thrift.Column;
-import org.apache.cassandra.thrift.ColumnOrSuperColumn;
+import org.apache.cassandra.thrift.ColumnParent;
import org.apache.cassandra.thrift.KeyRange;
-import org.apache.cassandra.thrift.SuperColumn;
-import org.apache.cassandra.thrift.ColumnPath;
import org.apache.cassandra.thrift.NotFoundException;
-import org.apache.cassandra.thrift.ColumnParent
-import org.apache.cassandra.thrift.SliceRange
-import org.apache.cassandra.thrift.SlicePredicate
-import org.apache.cassandra.thrift.ConsistencyLevel
+import org.apache.cassandra.thrift.SlicePredicate;
+import org.apache.cassandra.thrift.SliceRange;
+
+import me.prettyprint.cassandra.serializers.SerializerTypeInferer;
+import me.prettyprint.hector.api.Cluster;
+import me.prettyprint.hector.api.Keyspace;
+import me.prettyprint.hector.api.beans.HColumn;
+import me.prettyprint.hector.api.factory.HFactory;
+import me.prettyprint.hector.api.mutation.MutationResult;
+import me.prettyprint.hector.api.mutation.Mutator;
+import me.prettyprint.hector.api.query.ColumnQuery;
+import me.prettyprint.hector.api.query.QueryResult;
class CassandraService {
boolean transactional = true
- def servers=["localhost:9160"]
- def defaultKeyspace="Keyspace1"
+ String servers="localhost:9160"
+ String clusterName="Test Cluster"
+ String keyspaceName="Keyspace1"
def hideNotFoundExceptions=true
def convertOnGetDefault = true
def keyspaceDetails = [:]
-
+
+
/**
- * Executes the block passing in the available client
+ * The service itself is a singleton, but if we throw it away and create a new one, then we want to do the
+ * same thing for the keyspace holder. Note the the keyspace hold is not an
+ * inner class because groovy 1.6 doesn't support inner classes
*/
- def acquireClient(block){
- //if(null!=log) log.debug("[acquireClient]")
- CassandraClientPool pool = CassandraClientPoolFactory.INSTANCE.get();
- CassandraClient client = pool.borrowClient(servers);
- try {
- return block(client)
- } finally {
- pool.releaseClient(client)
- }
+ private final KeyspaceHolder keyspaceHolder= new KeyspaceHolder();
+
+ // need to override the setters so the keyspaceHolder is set right
+
+ public void setServers(String s){
+ log.debug("[setServers(${s})]")
+ servers = s;
+ keyspaceHolder.setServers(s);
+ }
+ public void setClusterName(String s){
+ log.debug("[setClusterName(${s})]")
+ clusterName = s;
+ keyspaceHolder.setClusterName(s);
+ }
+ public void setKeyspaceName(String s){
+ log.debug("[setKeyspaceName(${s})]")
+ keyspaceName = s;
+ keyspaceHolder.setKeyspaceName(s);
}
/**
- * A way get the details of the column families in this keyspace. Note that the data is also stored in
- * the keyspaceDetails properties, so if you need to flush the cache, set that to null
+ * Returns the hector cluster object
* @return
*/
- def columnFamilyDetails(keyspaceName=defaultKeyspace){
- if (null==keyspaceDetails[keyspaceName]) {
- keyspaceDetails[keyspaceName] = acquireClient{it.getCassandra().describe_keyspace(keyspaceName)}
- }
- return keyspaceDetails[keyspaceName]
+ public Cluster getCluster(){
+ log.debug("[getCluster()]")
+ return keyspaceHolder.getCluster();
+ }
+
+ public Keyspace keyspace() {
+ log.debug("[keyspace()]")
+ return keyspaceHolder.get();
+ }
+
+ def resetKeyspace(){
+ log.debug("[resetKeyspace()]")
+ keyspaceHolder.remove()
}
/**
- * Returns a list of keys for the column family. They will not be ordered
- * if you are not using an OPP sort. You can page through the list by
- * starting with emptystrings for startKey and endKey, and using the last
- * key found as the 'startKey' in the next list.
- * @param columnFamily
+ * A way get the details of the column families in this keyspace. Note that the data is also stored in
+ * the keyspaceDetails properties, so if you need to flush the cache, set that to null
* @return
*/
- def keySearch(columnFamily,count=100,startKey="",endKey=""){
- execute { keyspace ->
- ColumnParent cp = new ColumnParent(columnFamily)
- SliceRange sr = new SliceRange(new byte[0], new byte[0], true, 0) //we don't want any columns, just keys
- SlicePredicate sp = new SlicePredicate()
- sp.setSlice_range(sr)
- KeyRange kr = new KeyRange()
- kr.setCount(count)
- kr.setStart_key(startKey)
- kr.setEnd_key(endKey)
- def map = keyspace.getRangeSlices(cp,sp,kr)
- return map.keySet()
+ def columnFamilyDetails(keyspaceName=keyspace){
+ if (null==keyspaceDetails[keyspaceName]) {
+ keyspaceDetails[keyspaceName] = getCluster().describeKeyspace(keyspaceName)
}
+ return keyspaceDetails[keyspaceName]
}
/**
* Executes the closure giving it the keyspace as an argument
*/
- def execute(keyspaceName=defaultKeyspace,block){
- //if(null!=log) log.debug("[execute] $keyspaceName")
- acquireClient { client ->
- Keyspace keyspace = client.getKeyspace(keyspaceName);
- return block(keyspace)
- }
+ def execute(block){
+ log.debug("[execute]")
+ return block(getKeyspace())
}
/**
- * If the object is not already a byte[], it will convert it to one.
- * @param obj
+ * Returns the serializer for the object given...
+ *
+ * @param object
* @return
*/
- def bytesConvert(obj){
- if (obj instanceof Long){
- obj = ByteBuffer.allocate(8).putLong(obj).array()
- } else if(!(obj instanceof byte[])){
- obj = bytes(obj.toString())
- }
- obj
+ def serializer(object){
+ return SerializerTypeInferer.getSerializer(object)
}
/**
@@ -127,201 +125,53 @@ class CassandraService {
}
/**
- * Returns the number of columns defined for this key in this column family. If the key is not defined, will return a zero and
- * not throw an exception.
- *
- * @param columnFamilyName
- * @param key
- * @param superColumnName (optional)
- * @return number of columns available.
- */
- def getColumnCount(columnFamilyName,key,superColumnName=null){
- def columnParent = new ColumnParent(columnFamilyName, (superColumnName==null ? null : bytesConvert(superColumnName)))
- execute { keyspace ->
- def result = exceptionCatcher{keyspace.getCount(key,columnParent)}
- if(result==null){
- result=0
- }
- return result
- }
- }
-
-
- /**
- * This will return a single value for a specific column family.
- * superColumnName==null
- * columnFamilyName:{key:{columnName = columnValue}}
- * superColumnName!=null
- * columnFamilyName:{key:{superColumnName:{columnName = columnValue}}}
- *
- * @param columnFamilyName
- * @param key
- * @param superColumnName (optional)
- * @param columnName
- * @return
- */
- def getColumnValue(columnFamilyName,key,superColumnName=null,columnName,convert=convertOnGetDefault){
- //if(null!=log) log.debug("[getColumnValue] $columnFamilyName $key $superColumnName $columnName")
- def columnPath = getColumnPath(columnFamilyName,superColumnName,columnName)
- execute { keyspace ->
- return exceptionCatcher{
- def value = keyspace.getColumn(key,columnPath).getValue()
- if (value!=null){
- def rowDetails = columnFamilyDetails()[columnFamilyName]
- value = (convert ?
- convertValue(value,(superColumnName == null ? rowDetails["CompareWith"] : rowDetails["CompareWith"])) :
- value)
- }
- value
- }
- }
- }
-
- /**
- * Removes an entry from the system.
- * @param columnFamilyName Required to specify the columnFamily to remove from
- * @param key Require to specify the key to remove.
- * @param superColumnName optional if there is a superColumn
- * @param columnName optional. Use this if you only want to remove one value
- */
- def removeValue(columnFamilyName, key, superColumnName=null, columnName=null){
- def columnPath = getColumnPath(columnFamilyName,superColumnName,columnName)
- execute {keyspace ->
- keyspace.remove(key,columnPath)
- }
- }
-
- /**
- * Returns a map where the key is the super-column, and the value is the sub-column name/value pairs
- * @param columnFamilyName
- * @param key
- * @param covert Set this to false if you want 'bytes' back.
- * @return
- */
- def getRow(columnFamilyName,key,convert=convertOnGetDefault){
- def rowDetails = columnFamilyDetails()[columnFamilyName]
-
- SliceRange sr = new SliceRange(new byte[0], new byte[0], false, 1000000); //TODO, fix this to get a real count, somehow
- SlicePredicate predicate = new SlicePredicate();
- predicate.setSlice_range(sr)
-
- acquireClient { client ->
- List<ColumnOrSuperColumn> columns = client.getCassandra().get_slice(defaultKeyspace, key,
- new ColumnParent(columnFamilyName),
- predicate,
- ConsistencyLevel.ONE);
- int size = columns.size();
- def result = new LinkedHashMap()
- for (ColumnOrSuperColumn cosc : columns) {
- if (cosc.isSetSuper_column()) {
- SuperColumn superColumn = cosc.super_column;
- def superColumnName = (convert ? convertValue(superColumn.name,rowDetails["CompareWith"]) : superColumn.name)
- result[superColumnName] = new LinkedHashMap()
- for (Column col : superColumn.getColumns()){
- result[superColumnName][( convert ? convertValue(col.name,rowDetails["CompareSubcolumnsWith"]) : col.name)] = (convert ? convertValue(col.value) : col.value)}
- } else {
- Column col = cosc.column;
- result[(convert ? convertValue(col.name,rowDetails["CompareWith"]) : col.name) ] = ( convert ? convertValue(col.value) : col.value)
- }
- } // for
- return result
- }
- }
-
- def convertValue(value,type=null){
- def result
- if(type=="org.apache.cassandra.db.marshal.TimeUUIDType"){
- long msb = 0;
- long lsb = 0;
- for (int i=0; i<8; i++)
- msb = (msb << 8) | (value[i] & 0xff);
- for (int i=8; i<16; i++)
- lsb = (lsb << 8) | (value[i] & 0xff);
- long mostSigBits = msb;
- long leastSigBits = lsb;
- def uuid = new UUID(msb, lsb)
- result = uuid.toString()
- } else if (type == "org.apache.cassandra.db.marshal.LongType"){
- result = ByteBuffer.wrap(bytes).getLong()
- } else {
- result = new String(value,"UTF-8")
- }
- return result
- }
-
- /**
- * This will set the value for a specific column family.
- * superColumnName==null
- * columnFamilyName:{key:{columnName = columnValue}}
- * superColumnName!=null
- * columnFamilyName:{key:{superColumnName:{columnName = columnValue}}}
+ * Sets a single value for a key. Note that it uses the potential serializer derived from the data type.
*
- * @param columnFamilyName
* @param key
- * @param superColumnName (optional)
- * @param columnName
+ * @param cf
+ * @param scName Optional super column name... needs to be set if and only if its a super column family
+ * @param name
* @param value
* @return
*/
- def setColumnValue(columnFamilyName,key,superColumnName=null,columnName,value){
- //if(null!=log) log.debug("[setColumnValue] $columnFamilyName $key $superColumnName $columnName $value")
- def columnPath = getColumnPath(columnFamilyName,superColumnName,columnName)
- execute { keyspace ->
- def old_value = null
- try {old_value = string(keyspace.getColumn(key,columnPath).getValue())
- } catch (NotFoundException nfe){;
- }
- keyspace.insert(key, columnPath, bytesConvert(value))
- return old_value
- }
+ def setValue(key,cf,scName=null,name,value){
+ Mutator m = HFactory.createMutator(keyspace(),serializer(key));
+ MutationResult mr = m.insert(key, cf, HFactory.createColumn(name, value, serializer(name), serializer(value)));
}
-
+
/**
- * Sets all the column name/value pairs in the values map
- *
- * @param columnFamilyName
- * @param key
- * @param superColumnName (optional)
- * @param values map of columnNames to columnValues.
- * @return
- */
- def setColumnValues(columnFamilyName,key, superColumnName=null,values){
- //if(null!=log) log.debug("[setColumnValues] $columnFamilyName $key $superColumnName $values")
- ArrayList<Column> list = new ArrayList<Column>(values.size()); // columnName,value in values
- values.each{
- list.add(new Column(bytesConvert(it.key),bytesConvert(it.value),System.currentTimeMillis()));
- }
- // if no superColumnName
- if (null==superColumnName){
- LinkedHashMap<String, List<Column>> cfmap = new LinkedHashMap<String, List<Column>>(values.size());
- cfmap.put(columnFamilyName,list)
- execute {keyspace -> keyspace.batchInsert(key,cfmap,null)}
+ * Gets a single value for a key. Note that it uses the potential serializer derived from the data type.
+ *
+ * @param key
+ * @param cf
+ * @param scName Optional super column name... needs to be set if and only if its a super column family
+ * @param name
+ * @param valueClass, expected type coming back.
+ * @return
+ */
+ def getValue(key,cf,scName=null,name,valueClass){
+ ColumnQuery q = HFactory.createColumnQuery(keyspace(), serializer(key), serializer(name), serializer(valueClass))
+ q.setName(name).setColumnFamily(cf)
+ QueryResult r = q.setKey(key).execute()
+ HColumn c = r.get()
+ if(c==null){
+ return null
} else {
- SuperColumn sc = new SuperColumn(bytesConvert(superColumnName),list)
- LinkedHashMap<String, List<SuperColumn>> cfmap = new LinkedHashMap<String, List<SuperColumn>>(1);
- List<SuperColumn> scList = new ArrayList<SuperColumn>(1)
- scList.add(sc)
- cfmap.put(columnFamilyName,scList)
- execute {keyspace -> keyspace.batchInsert(key,null,cfmap)}
- }
- }
-
-
- /**
- * //supercolumnname/columnfamilyname/key?colname=colval&colname=colval
- */
- def getColumnPath(columnFamilyName,superColumnName=null,name){
- //if(null!=log) log.debug("[getColumnPath]: $columnFamilyName $superColumnName $name")
- ColumnPath cp = new ColumnPath(columnFamilyName)
- if(name!=null){
- cp.setColumn(bytesConvert(name))
- }
- if(superColumnName!=null){
- cp.setSuper_column(bytesConvert(superColumnName))
- }
- return cp
- }
-
-
-
+ return c.getValue()
+ }
+ }
+
+ /**
+ * Removes the column for the key's name from the (super) column family
+ * @param key
+ * @param cf
+ * @param scName Optional super column name... needs to be set if and only if its a super column family
+ * @param name
+ * @return
+ */
+ def deleteValue(key,cf,scName=null,name){
+ Mutator m = HFactory.createMutator(keyspace(), serializer(key));
+ MutationResult mr2 = m.delete(key, cf, name, serializer(name));
+ }
+
}
View
60 src/groovy/codehead/CassandraMap.groovy
@@ -1,60 +0,0 @@
-package codehead
-
-import java.util.Map
-
-/**
- *
- * @author wolpert
- */
-class CassandraMap implements Map{
-
- public int size() {
- throw new UnsupportedOperationException("Not supported yet.");
- }
-
- public boolean isEmpty() {
- throw new UnsupportedOperationException("Not supported yet.");
- }
-
- public boolean containsKey(Object o) {
- throw new UnsupportedOperationException("Not supported yet.");
- }
-
- public boolean containsValue(Object o) {
- throw new UnsupportedOperationException("Not supported yet.");
- }
-
- public Object get(Object o) {
- throw new UnsupportedOperationException("Not supported yet.");
- }
-
- public Object put(Object k, Object v) {
- throw new UnsupportedOperationException("Not supported yet.");
- }
-
- public Object remove(Object o) {
- throw new UnsupportedOperationException("Not supported yet.");
- }
-
- public void putAll(Map map) {
- throw new UnsupportedOperationException("Not supported yet.");
- }
-
- public void clear() {
- throw new UnsupportedOperationException("Not supported yet.");
- }
-
- public Set keySet() {
- throw new UnsupportedOperationException("Not supported yet.");
- }
-
- public Collection values() {
- throw new UnsupportedOperationException("Not supported yet.");
- }
-
- public Set entrySet() {
- throw new UnsupportedOperationException("Not supported yet.");
- }
-
-}
-
View
154 test/unit/codehead/CassandraServiceTests.groovy
@@ -2,14 +2,14 @@ package codehead;
import java.nio.ByteBuffer;
import grails.test.*
-import org.apache.cassandra.thrift.NotFoundException;
+import me.prettyprint.hector.api.beans.HColumn;
+import me.prettyprint.hector.api.factory.HFactory;
+import me.prettyprint.hector.api.mutation.MutationResult;
+import me.prettyprint.hector.api.mutation.Mutator;
+import me.prettyprint.hector.api.query.ColumnQuery;
+import me.prettyprint.hector.api.query.QueryResult;
-/**
- * mockFor requires a groovy object, where the keyspace I'm mocking is
- * a java one. So this class is just a holder.
- */
-class MockKeyspace {
-}
+import org.apache.cassandra.thrift.NotFoundException;
class CassandraServiceTests extends GrailsUnitTestCase {
@@ -17,87 +17,77 @@ class CassandraServiceTests extends GrailsUnitTestCase {
protected void setUp() {
super.setUp()
+ mockLogging(CassandraService,true)
+ cassandraService = new CassandraService()
}
protected void tearDown() {
super.tearDown()
}
+
+ void testExceptionBlocker(){
+ def result = cassandraService.exceptionCatcher {
+ throw new NotFoundException()
+ }
+ assertNull(result) // and if you got not error, its all good.
+ }
+
+ /**
+ * The standard hector test, before the service refactoring...
+ */
+ void testSetGetDeleteOldStyle(){
+
+ String cf = "Standard1"
+ String method = "testSetGetDeleteOldStyle"
+ String key = "${method}_Key"
+ String name = "${method}_Name"
+ String value = "${method}_Value"
+
+ Mutator<String> m = HFactory.createMutator(cassandraService.keyspace(),cassandraService.serializer(String.class));
+ MutationResult mr = m.insert(key, cf, HFactory.createColumn(name, value, cassandraService.serializer(String.class), cassandraService.serializer(String.class)));
+
+ ColumnQuery<String, String, String> q = HFactory.createColumnQuery(cassandraService.keyspace(), cassandraService.serializer(String.class), cassandraService.serializer(String.class), cassandraService.serializer(String.class))
+ q.setName(name).setColumnFamily(cf)
+ QueryResult<HColumn<String, String>> r = q.setKey(key).execute();
+ assertNotNull(r);
- void testMock() {
- def mockKeyspaceImpl = mockFor(MockKeyspace)
- mockKeyspaceImpl.demand.getName(1..1){ -> return "mock keyspace"}
- def cassandraService = getCassandraService(mockKeyspaceImpl.createMock())
-
- // run test
- def str = cassandraService.execute{keyspace ->keyspace.getName()}
- assertEquals("mock keyspace", str)
- }
-
- void testByteConvertWithLong(){
- long value = 87667382432456
- cassandraService = new CassandraService()
- byte[] ba = cassandraService.bytesConvert(value)
- long result = ByteBuffer.wrap(ba).getLong();
- assertEquals(value,result)
- }
-
- void testByteConvertWithLongObject(){
- Long value = new Long(87667382432456)
- cassandraService = new CassandraService()
- byte[] ba = cassandraService.bytesConvert(value)
- long result = ByteBuffer.wrap(ba).getLong();
- assertEquals(value,result)
- }
-
- void testBytesArrayConvertOnBytesArray(){
- cassandraService = new CassandraService()
- def obj = new byte[2];
- obj[0]=5
- obj[1]=6
- def result = cassandraService.bytesConvert(obj)
- assertEquals obj, result
- assertEquals obj[0], result[0]
- assertEquals obj[1], result[1]
- }
-
- void testBytesArrayConvertOnString(){
- cassandraService = new CassandraService()
- def obj = "this is a string"
- def result = cassandraService.bytesConvert(obj)
- assertEquals(byte[].class,result.class)
- assertEquals(obj,new String(result))
- }
-
- void testExceptionCatcherWithNotFoundException(){
- def mockKeyspaceImpl = mockFor(MockKeyspace)
- mockKeyspaceImpl.demand.getColumn(1..1){arg1, arg2 -> throw new NotFoundException()}
- def cassandraService = getCassandraService(mockKeyspaceImpl.createMock())
- cassandraService.hideNotFoundExceptions=true
- assertNull cassandraService.getColumnValue('colFamName','key','columnName')
- }
+ HColumn<String, String> c = r.get();
+ assertNotNull(c);
+ String foundvalue = c.getValue();
+ assertEquals(value, foundvalue);
+ String foundname = c.getName();
+ assertEquals(name, foundname);
+ assertEquals(q, r.getQuery());
+
+ m = HFactory.createMutator(cassandraService.keyspace(), cassandraService.serializer(String.class));
+ MutationResult mr2 = m.delete(key, cf, name, cassandraService.serializer(String.class));
+
+ // get already removed value
+ ColumnQuery<String, String, String> q2 = HFactory.createColumnQuery(cassandraService.keyspace(), cassandraService.serializer(String.class), cassandraService.serializer(String.class), cassandraService.serializer(String.class));
+ q2.setName(name).setColumnFamily(cf);
+ QueryResult<HColumn<String, String>> r2 = q2.setKey(key).execute();
+ assertNotNull(r2);
+ assertNull("Value should have been deleted", r2.get())
+ }
+ /**
+ * The standard hector test, before the service refactoring...
+ */
+ void testSetGetDeleteGroovyStyle(){
+
+ String cf = "Standard1"
+ String method = "testSetGetDeleteGroovyStyle"
+ String key = "${method}_Key"
+ String name = "${method}_Name"
+ String value = "${method}_Value"
+
+ cassandraService.setValue(key,cf,name,value)
+
+ def result = cassandraService.getValue(key,cf,name,String.class)
+ assertNotNull(result);
+ assertEquals(value,result)
- void testExceptionCatcherWithRealException(){
- def mockKeyspaceImpl = mockFor(MockKeyspace)
- mockKeyspaceImpl.demand.getColumn(1..1){arg1, arg2 -> throw new Exception()}
- def cassandraService = getCassandraService(mockKeyspaceImpl.createMock())
- cassandraService.hideNotFoundExceptions=true
- shouldFail{
- cassandraService.getColumnValue('colFamName','key','columnName')
- }
- }
-
- /**
- * Returns a cassandra service that uess the keyspace for its execute
- */
- def getCassandraService(keyspace){
- cassandraService = new CassandraService()
- mockLogging(CassandraService)
- def emc = new ExpandoMetaClass(CassandraService.class, false)
- emc.execute = { it(keyspace) }
-
- emc.initialize()
- cassandraService.metaClass = emc
- return cassandraService
- }
+ cassandraService.deleteValue(key,cf,name)
+ assertNull("Value should have been deleted", cassandraService.getValue(key,cf,name,String.class))
+ }
}
Please sign in to comment.
Something went wrong with that request. Please try again.