Skip to content

Instantly share code, notes, and snippets.

@zsoltk
Forked from jeffjohnson9046/UuidHelper.java
Created April 8, 2019 11:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zsoltk/0228508a8f74b3e65e9762843f067fb6 to your computer and use it in GitHub Desktop.
Save zsoltk/0228508a8f74b3e65e9762843f067fb6 to your computer and use it in GitHub Desktop.
Convert UUID to byte array and vice versa. Useful for when UUIDs are stored in MySQL tables as VARBINARY(16)
import java.nio.ByteBuffer;
import java.util.UUID;
public class UuidAdapter {
public static byte[] getBytesFromUUID(UUID uuid) {
ByteBuffer bb = ByteBuffer.wrap(new byte[16]);
bb.putLong(uuid.getMostSignificantBits());
bb.putLong(uuid.getLeastSignificantBits());
return bb.array();
}
public static UUID getUUIDFromBytes(byte[] bytes) {
ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);
Long high = byteBuffer.getLong();
Long low = byteBuffer.getLong();
return new UUID(high, low);
}
}
import junit.framework.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.transaction.TransactionConfiguration;
import tds.student.performance.dao.utils.UuidAdapter;
import java.util.UUID;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("/your-test-context.xml")
@TransactionConfiguration
public class UuidAdapterTest {
@Test
public void should_Get_16_Bytes_From_a_UUID() {
UUID uuid = UUID.randomUUID();
byte[] result = UuidAdapter.getBytesFromUUID(uuid);
Assert.assertEquals("Expected result to be a byte array w/16 elements.", 16, result.length);
}
@Test
public void should_Reconstruct_Same_UUID_From_Byte_Array() {
UUID uuid = UUID.randomUUID();
byte[] bytes = UuidAdapter.getBytesFromUUID(uuid);
UUID reconstructedUuid = UuidAdapter.getUUIDFromBytes(bytes);
Assert.assertEquals(uuid, reconstructedUuid);
}
@Test
public void should_Not_Generate_the_Same_UUID_From_Bytes() {
UUID uuid = UUID.fromString("9f881758-0b4a-4eaa-b59f-b6dea0934223");
byte[] result = UuidAdapter.getBytesFromUUID(uuid);
UUID newUuid = UUID.nameUUIDFromBytes(result);
Assert.assertFalse(uuid.equals(newUuid));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment