I have a couple of fields which I am trying to put together into a single ByteBuffer
before storing it in a Cassandra database.
That byte array which I will be writing into Cassandra is made up of three byte arrays as described below:
short employeeId = 32767;
long lastModifiedDate = "1379811105109L";
byte[] attributeValue = os.toByteArray();
Now, I will write employeeId
, lastModifiedDate
and attributeValue
together into a single byte array and that resulting byte array will be written into Cassandra. I will then have my C++ program retrieve that byte array data from Cassandra and then deserialize it to extract employeeId
, lastModifiedDate
and attributeValue
from it.
To do this, I am using ByyteBuffer
with BigEndian byte order format.
I have put up this code together:
public static void main(String[] args) throws Exception {
String text = "Byte Buffer Test";
byte[] attributeValue = text.getBytes();
long lastModifiedDate = 1289811105109L;
short employeeId = 32767;
int size = 2 + 8 + 4 + attributeValue.length; // short is 2 bytes, long 8 and int 4
ByteBuffer bbuf = ByteBuffer.allocate(size);
bbuf.order(ByteOrder.BIG_ENDIAN);
bbuf.putShort(employeeId);
bbuf.putLong(lastModifiedDate);
bbuf.putInt(attributeValue.length);
bbuf.put(attributeValue);
bbuf.rewind();
// best approach is copy the internal buffer
byte[] bytesToStore = new byte[size];
bbuf.get(bytesToStore);
// write bytesToStore in Cassandra...
// Now retrieve the Byte Array data from Cassandra and deserialize it...
byte[] allWrittenBytesTest = bytesToStore;//magicFunctionToRetrieveDataFromCassandra();
ByteBuffer bb = ByteBuffer.wrap(allWrittenBytesTest);
bb.order(ByteOrder.BIG_ENDIAN);
bb.rewind();
short extractEmployeeId = bb.getShort();
long extractLastModifiedDate = bb.getLong();
int extractAttributeValueLength = bb.getInt();
byte[] extractAttributeValue = new byte[extractAttributeValueLength];
bb.get(extractAttributeValue); // read attributeValue from the remaining buffer
System.out.println(extractEmployeeId);
System.out.println(extractLastModifiedDate);
System.out.println(new String(extractAttributeValue));
}
- Is there any better way of doing this?
- Are there some minor improvements that can be made here?
- Can anyone take a look and let me know whether this is the right way to use
ByteBuffer
? This is my first time using it, so I'm having a bit of a problem.