\ \

The Matygo Blog

Matygo is a startup intent on being a catalyst in the education revolution.

  1. Posted: 1 year ago by: joegaudet

    { Time UUIDs with Java + Cassandra }

    Here at Matygo we’ve decided to jump on the NoSQL bandwagon and as such have been building up a small Java + Cassandra client. One of the many features of Cassandra is the Column / SuperColumn naming by time based UUIDs. I won’t bother explaining it, as many other people have done a much better job than I could (WTF is a super column). 

    That said one of the sticky bits when using Java is that the UUID class included in the java.util package doesn’t support making time based UUIDs. This is covered on the official Cassandra wiki here. However I find their code a bit cluttered, so I thought I’d post an alternative using the Java NIO package which is quite helpful for type conversions between byte arrays and primitive data types. The class in question is the ByteBuffer. 

    I tested both implementations for speed and they both performed the same, very very quickly :P

    Here is the code, you’ll also need the UUID library found here.

    public class UUIDUtil {

    public static java.util.UUID getTimeUUID() {

    return java.util.UUID.fromString(new com.eaio.uuid.UUID().toString());

     }

    public static java.util.UUID getRandomUUID(){

    return java.util.UUID.randomUUID();

    }

    public static java.util.UUID toUUID( byte[] uuid ) {

    ByteBuffer buffer = ByteBuffer.allocate(16);

    buffer.put(uuid);

    buffer.rewind();

    com.eaio.uuid.UUID u = new com.eaio.uuid.UUID(buffer.getLong(),buffer.getLong());

    return java.util.UUID.fromString(u.toString());

    }

    public static byte[] asByteArray(java.util.UUID uuid) {

    ByteBuffer buffer = ByteBuffer.allocate(16);

    buffer.putLong(uuid.getMostSignificantBits());

    buffer.putLong(uuid.getLeastSignificantBits());

    return buffer.array();

    }

    }

    Cheers,

    .joe