Skip to content

Instantly share code, notes, and snippets.

@ofirski
Created December 6, 2019 15:41
Show Gist options
  • Save ofirski/3eb3c7b6d3c277579d19fe19a68784e8 to your computer and use it in GitHub Desktop.
Save ofirski/3eb3c7b6d3c277579d19fe19a68784e8 to your computer and use it in GitHub Desktop.
TypeCodec for mapping java.lang.Long values to Cassandra's TimeUUID using DataStax Java Connector
package ofirski;
import com.datastax.oss.driver.api.core.ProtocolVersion;
import com.datastax.oss.driver.api.core.type.DataType;
import com.datastax.oss.driver.api.core.type.DataTypes;
import com.datastax.oss.driver.api.core.type.codec.TypeCodec;
import com.datastax.oss.driver.api.core.type.reflect.GenericType;
import edu.umd.cs.findbugs.annotations.NonNull;
import edu.umd.cs.findbugs.annotations.Nullable;
import com.datastax.oss.driver.api.core.uuid.Uuids;
import java.nio.ByteBuffer;
import java.util.UUID;
public class LongAsTimeUUIDTypeCodec implements TypeCodec<Long> {
@NonNull
@Override
public GenericType<Long> getJavaType() {
return GenericType.LONG;
}
@NonNull
@Override
public DataType getCqlType() {
return DataTypes.TIMEUUID;
}
@Nullable
@Override
public ByteBuffer encode(@Nullable Long value, @NonNull ProtocolVersion protocolVersion) {
if (value == null) {
return null;
}
UUID uuid = Uuids.startOf(value);
ByteBuffer bytes = ByteBuffer.allocate(16);
bytes.putLong(0, uuid.getMostSignificantBits());
bytes.putLong(8, uuid.getLeastSignificantBits());
return bytes;
}
@Nullable
@Override
public Long decode(@Nullable ByteBuffer bytes, @NonNull ProtocolVersion protocolVersion) {
if (bytes == null || bytes.remaining() == 0) {
return null;
} else if (bytes.remaining() != 16) {
throw new IllegalArgumentException(
"Unexpected number of bytes for a UUID, expected 16, got " + bytes.remaining());
} else {
UUID uuid = new UUID(bytes.getLong(bytes.position()), bytes.getLong(bytes.position() + 8));
return Uuids.unixTimestamp(uuid);
}
}
@NonNull
@Override
public String format(@Nullable Long value) {
if (value == null) {
return "NULL";
}
return Uuids.startOf(value).toString();
}
@Nullable
@Override
public Long parse(@Nullable String value) {
try {
return (value == null || value.isEmpty() || value.equalsIgnoreCase("NULL"))
? null
: UUID.fromString(value).timestamp();
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException(
String.format("Cannot parse UUID value from \"%s\"", value), e);
}
}
@Override
public boolean accepts(@NonNull Object value) {
return value instanceof Long;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment