From 0d722c1d90d6159fbd50e7065920c0d3460ca53c Mon Sep 17 00:00:00 2001 From: Diego Torres Date: Tue, 29 Jun 2021 04:46:32 -0400 Subject: [PATCH] [uuid] diegotorres/dtorres.py@gmail.com Improvements for UUIDv5 generation (#10978) * [uuid] Added method to generate UUID identifiers for version 5 Signed-off-by: Diego Torres * [uuid] Small improvements for UUIDv5 generation Signed-off-by: Diego Torres --- .../java/com/baeldung/uuid/UUIDGenerator.java | 19 ++++++------------- .../baeldung/uuid/UUIDGeneratorUnitTest.java | 4 ++-- 2 files changed, 8 insertions(+), 15 deletions(-) diff --git a/core-java-modules/core-java/src/main/java/com/baeldung/uuid/UUIDGenerator.java b/core-java-modules/core-java/src/main/java/com/baeldung/uuid/UUIDGenerator.java index 49d43c38a2..54de1f95c6 100644 --- a/core-java-modules/core-java/src/main/java/com/baeldung/uuid/UUIDGenerator.java +++ b/core-java-modules/core-java/src/main/java/com/baeldung/uuid/UUIDGenerator.java @@ -176,8 +176,8 @@ public class UUIDGenerator { byte[] hash = md.digest(bytes); - long msb = peekLong(hash, 0, ByteOrder.BIG_ENDIAN); - long lsb = peekLong(hash, 8, ByteOrder.BIG_ENDIAN); + long msb = getLeastAndMostSignificantBitsVersion5(hash, 0); + long lsb = getLeastAndMostSignificantBitsVersion5(hash, 8); // Set the version field msb &= ~(0xfL << 12); msb |= ((long) 5) << 12; @@ -191,18 +191,11 @@ public class UUIDGenerator { } } - private static long peekLong(final byte[] src, final int offset, final ByteOrder order) { + private static long getLeastAndMostSignificantBitsVersion5(final byte[] src, final int offset) { long ans = 0; - if (order == ByteOrder.BIG_ENDIAN) { - for (int i = offset; i < offset + 8; i += 1) { - ans <<= 8; - ans |= src[i] & 0xffL; - } - } else { - for (int i = offset + 7; i >= offset; i -= 1) { - ans <<= 8; - ans |= src[i] & 0xffL; - } + for (int i = offset + 7; i >= offset; i -= 1) { + ans <<= 8; + ans |= src[i] & 0xffL; } return ans; } diff --git a/core-java-modules/core-java/src/test/java/com/baeldung/uuid/UUIDGeneratorUnitTest.java b/core-java-modules/core-java/src/test/java/com/baeldung/uuid/UUIDGeneratorUnitTest.java index b2ca979c83..cf0d7656ff 100644 --- a/core-java-modules/core-java/src/test/java/com/baeldung/uuid/UUIDGeneratorUnitTest.java +++ b/core-java-modules/core-java/src/test/java/com/baeldung/uuid/UUIDGeneratorUnitTest.java @@ -63,11 +63,11 @@ class UUIDGeneratorUnitTest { } @Test - public void version_5_UUID_is_correctly_generated_for_domain_baeldung_com_without_namespace() throws UnsupportedEncodingException { + public void version_5_UUID_is_correctly_generated_for_domain_baeldung_name() { UUID uuid = UUIDGenerator.generateType5UUID("baeldung.com"); - assertEquals("a3c27ab0-2b46-55ef-b50e-0e5c57bfea94", uuid.toString()); + assertEquals("efd5462b-b07a-52a3-94ea-bf575c0e0e75", uuid.toString()); assertEquals(5, uuid.version()); assertEquals(2, uuid.variant()); }