Document and clean up UUID factory API and implementation.
authorMathieu Baudier <mbaudier@argeo.org>
Tue, 25 Jan 2022 09:20:28 +0000 (10:20 +0100)
committerMathieu Baudier <mbaudier@argeo.org>
Tue, 25 Jan 2022 09:20:28 +0000 (10:20 +0100)
org.argeo.api.uuid/src/org/argeo/api/uuid/AbstractAsyncUuidFactory.java
org.argeo.api.uuid/src/org/argeo/api/uuid/AbstractUuidFactory.java
org.argeo.api.uuid/src/org/argeo/api/uuid/ConcurrentTimeUuidState.java
org.argeo.api.uuid/src/org/argeo/api/uuid/ConcurrentUuidFactory.java
org.argeo.api.uuid/src/org/argeo/api/uuid/MacAddressUuidFactory.java
org.argeo.api.uuid/src/org/argeo/api/uuid/NodeIdSupplier.java
org.argeo.api.uuid/src/org/argeo/api/uuid/TimeUuidState.java [deleted file]
org.argeo.api.uuid/src/org/argeo/api/uuid/UuidFactory.java
org.argeo.cms/src/org/argeo/cms/acr/CmsUuidFactory.java [new file with mode: 0644]

index 1948eafbd8e82de76afe00e21d4d7620b9259d83..685fe0a07bb3ff2515f3b9cdddd598bd839883a9 100644 (file)
@@ -52,6 +52,10 @@ public abstract class AbstractAsyncUuidFactory extends AbstractUuidFactory imple
                reset();
        }
 
+       protected NodeIdSupplier getNodeIdSupplier() {
+               return nodeIdSupplier;
+       }
+
        /*
         * SYNC OPERATIONS
         */
index d348504adff6784bc259953bf4ff58f462aef6fd..75a6339b01681f48a1890468b4a56f303bbee43b 100644 (file)
@@ -55,7 +55,7 @@ public abstract class AbstractUuidFactory implements UuidFactory {
 
        protected UUID timeUUID(Temporal time, long clockSequence, byte[] node, int offset) {
                // TODO add checks
-               Duration duration = Duration.between(TimeUuidState.GREGORIAN_START, time);
+               Duration duration = Duration.between(TimeUuid.TIMESTAMP_ZERO, time);
                // Number of 100 ns intervals in one second: 1000000000 / 100 = 10000000
                long timestamp = duration.getSeconds() * 10000000 + duration.getNano() / 100;
                return newTimeUUID(timestamp, clockSequence, node, offset);
@@ -69,12 +69,12 @@ public abstract class AbstractUuidFactory implements UuidFactory {
                Objects.requireNonNull(namespace, "Namespace cannot be null");
                Objects.requireNonNull(name, "Name cannot be null");
 
-               byte[] bytes = sha1(toBytes(namespace), name);
+               byte[] bytes = sha1(UuidBinaryUtils.toBytes(namespace), name);
                bytes[6] &= 0x0f;
                bytes[6] |= 0x50;// v5
                bytes[8] &= 0x3f;
                bytes[8] |= 0x80;// variant 1
-               UUID result = fromBytes(bytes, 0);
+               UUID result = UuidBinaryUtils.fromBytes(bytes, 0);
                return result;
        }
 
@@ -83,7 +83,7 @@ public abstract class AbstractUuidFactory implements UuidFactory {
                Objects.requireNonNull(name, "Name cannot be null");
 
                byte[] arr = new byte[name.length + 16];
-               copyBytes(namespace, arr, 0);
+               UuidBinaryUtils.copyBytes(namespace, arr, 0);
                System.arraycopy(name, 0, arr, 16, name.length);
                return UUID.nameUUIDFromBytes(arr);
        }
@@ -98,7 +98,31 @@ public abstract class AbstractUuidFactory implements UuidFactory {
                arr[6] |= 0x40;// v4
                arr[8] &= 0x3f;
                arr[8] |= 0x80;// variant 1
-               return fromBytes(arr);
+               return UuidBinaryUtils.fromBytes(arr);
+       }
+
+       /*
+        * SPI UTILITIES
+        */
+       /** Guarantees that a byte array of length 6 will be returned. */
+       protected static byte[] toNodeIdBytes(byte[] source, int offset) {
+               if (source == null)
+                       return null;
+               if (offset < 0 || offset + 6 > source.length)
+                       throw new ArrayIndexOutOfBoundsException(offset);
+               byte[] nodeId = new byte[6];
+               System.arraycopy(source, offset, nodeId, 0, 6);
+               return nodeId;
+       }
+
+       /**
+        * Force this node id to be identified as no MAC address.
+        * 
+        * @see https://datatracker.ietf.org/doc/html/rfc4122#section-4.5
+        */
+       protected static void forceToNoMacAddress(byte[] nodeId, int offset) {
+               assert nodeId != null && offset < nodeId.length;
+               nodeId[offset] = (byte) (nodeId[offset] | 1);
        }
 
        /*
@@ -108,7 +132,7 @@ public abstract class AbstractUuidFactory implements UuidFactory {
        private final static String MD5 = "MD5";
        private final static String SHA1 = "SHA1";
 
-       protected byte[] sha1(byte[]... bytes) {
+       protected static byte[] sha1(byte[]... bytes) {
                MessageDigest digest = getSha1Digest();
                for (byte[] arr : bytes)
                        digest.update(arr);
@@ -116,7 +140,7 @@ public abstract class AbstractUuidFactory implements UuidFactory {
                return checksum;
        }
 
-       protected byte[] md5(byte[]... bytes) {
+       protected static byte[] md5(byte[]... bytes) {
                MessageDigest digest = getMd5Digest();
                for (byte[] arr : bytes)
                        digest.update(arr);
@@ -124,15 +148,15 @@ public abstract class AbstractUuidFactory implements UuidFactory {
                return checksum;
        }
 
-       protected MessageDigest getSha1Digest() {
+       protected static MessageDigest getSha1Digest() {
                return getDigest(SHA1);
        }
 
-       protected MessageDigest getMd5Digest() {
+       protected static MessageDigest getMd5Digest() {
                return getDigest(MD5);
        }
 
-       private MessageDigest getDigest(String name) {
+       private static MessageDigest getDigest(String name) {
                try {
                        return MessageDigest.getInstance(name);
                } catch (NoSuchAlgorithmException e) {
@@ -140,177 +164,4 @@ public abstract class AbstractUuidFactory implements UuidFactory {
                }
        }
 
-       /*
-        * UTILITIES
-        */
-       /**
-        * Convert bytes to an UUID. Byte array must not be null and be exactly of
-        * length 16.
-        */
-       protected UUID fromBytes(byte[] data) {
-               Objects.requireNonNull(data, "Byte array must not be null");
-               if (data.length != 16)
-                       throw new IllegalArgumentException("Byte array as length " + data.length);
-               return fromBytes(data, 0);
-       }
-
-       /**
-        * Convert bytes to an UUID, starting to read the array at this offset.
-        */
-       protected UUID fromBytes(byte[] data, int offset) {
-               Objects.requireNonNull(data, "Byte array cannot be null");
-               long msb = 0;
-               long lsb = 0;
-               for (int i = offset; i < 8 + offset; i++)
-                       msb = (msb << 8) | (data[i] & 0xff);
-               for (int i = 8 + offset; i < 16 + offset; i++)
-                       lsb = (lsb << 8) | (data[i] & 0xff);
-               return new UUID(msb, lsb);
-       }
-
-       protected long longFromBytes(byte[] data) {
-               long msb = 0;
-               for (int i = 0; i < data.length; i++)
-                       msb = (msb << 8) | (data[i] & 0xff);
-               return msb;
-       }
-
-       protected byte[] toBytes(UUID uuid) {
-               Objects.requireNonNull(uuid, "UUID cannot be null");
-               long msb = uuid.getMostSignificantBits();
-               long lsb = uuid.getLeastSignificantBits();
-               return toBytes(msb, lsb);
-       }
-
-       protected void copyBytes(UUID uuid, byte[] arr, int offset) {
-               Objects.requireNonNull(uuid, "UUID cannot be null");
-               long msb = uuid.getMostSignificantBits();
-               long lsb = uuid.getLeastSignificantBits();
-               copyBytes(msb, lsb, arr, offset);
-       }
-
-       /**
-        * Converts an UUID hex representation without '-' to the standard form (with
-        * '-').
-        */
-       public String compactToStd(String compact) {
-               if (compact.length() != 32)
-                       throw new IllegalArgumentException(
-                                       "Compact UUID '" + compact + "' has length " + compact.length() + " and not 32.");
-               StringBuilder sb = new StringBuilder(36);
-               for (int i = 0; i < 32; i++) {
-                       if (i == 8 || i == 12 || i == 16 || i == 20)
-                               sb.append('-');
-                       sb.append(compact.charAt(i));
-               }
-               String std = sb.toString();
-               assert std.length() == 36;
-               assert UUID.fromString(std).toString().equals(std);
-               return std;
-       }
-
-       /**
-        * Converts an UUID hex representation without '-' to an {@link UUID}.
-        */
-       public UUID fromCompact(String compact) {
-               return UUID.fromString(compactToStd(compact));
-       }
-
-       /** To a 32 characters hex string without '-'. */
-       public String toCompact(UUID uuid) {
-               return toHexString(toBytes(uuid));
-       }
-
-       final protected static char[] hexArray = "0123456789abcdef".toCharArray();
-
-       /** Convert two longs to a byte array with length 16. */
-       protected byte[] toBytes(long long1, long long2) {
-               byte[] result = new byte[16];
-               for (int i = 0; i < 8; i++)
-                       result[i] = (byte) ((long1 >> ((7 - i) * 8)) & 0xff);
-               for (int i = 8; i < 16; i++)
-                       result[i] = (byte) ((long2 >> ((15 - i) * 8)) & 0xff);
-               return result;
-       }
-
-       protected void copyBytes(long long1, long long2, byte[] arr, int offset) {
-               assert arr.length >= 16 + offset;
-               for (int i = offset; i < 8 + offset; i++)
-                       arr[i] = (byte) ((long1 >> ((7 - i) * 8)) & 0xff);
-               for (int i = 8 + offset; i < 16 + offset; i++)
-                       arr[i] = (byte) ((long2 >> ((15 - i) * 8)) & 0xff);
-       }
-
-       /** Converts a byte array to an hex String. */
-       protected String toHexString(byte[] bytes) {
-               char[] hexChars = new char[bytes.length * 2];
-               for (int j = 0; j < bytes.length; j++) {
-                       int v = bytes[j] & 0xFF;
-                       hexChars[j * 2] = hexArray[v >>> 4];
-                       hexChars[j * 2 + 1] = hexArray[v & 0x0F];
-               }
-               return new String(hexChars);
-       }
-
-       protected byte[] toNodeIdBytes(byte[] source, int offset) {
-               if (source == null)
-                       return null;
-               if (offset < 0 || offset + 6 > source.length)
-                       throw new ArrayIndexOutOfBoundsException(offset);
-               byte[] nodeId = new byte[6];
-               System.arraycopy(source, offset, nodeId, 0, 6);
-               return nodeId;
-       }
-
-       /*
-        * STATIC UTILITIES
-        */
-       /**
-        * Converts an UUID to a binary string (list of 0 and 1), with a separator to
-        * make it more readable.
-        */
-       public static String toBinaryString(UUID uuid, int charsPerSegment, char separator) {
-               Objects.requireNonNull(uuid, "UUID cannot be null");
-               String binaryString = toBinaryString(uuid);
-               StringBuilder sb = new StringBuilder(128 + (128 / charsPerSegment));
-               for (int i = 0; i < binaryString.length(); i++) {
-                       if (i != 0 && i % charsPerSegment == 0)
-                               sb.append(separator);
-                       sb.append(binaryString.charAt(i));
-               }
-               return sb.toString();
-       }
-
-       /** Converts an UUID to a binary string (list of 0 and 1). */
-       public static String toBinaryString(UUID uuid) {
-               Objects.requireNonNull(uuid, "UUID cannot be null");
-               String most = zeroTo64Chars(Long.toBinaryString(uuid.getMostSignificantBits()));
-               String least = zeroTo64Chars(Long.toBinaryString(uuid.getLeastSignificantBits()));
-               String binaryString = most + least;
-               assert binaryString.length() == 128;
-               return binaryString;
-       }
-
-       /**
-        * Force this node id to be identified as no MAC address.
-        * 
-        * @see https://datatracker.ietf.org/doc/html/rfc4122#section-4.5
-        */
-       public static void forceToNoMacAddress(byte[] nodeId, int offset) {
-               assert nodeId != null && offset < nodeId.length;
-               nodeId[offset] = (byte) (nodeId[offset] | 1);
-       }
-
-       private static String zeroTo64Chars(String str) {
-               assert str.length() <= 64;
-               if (str.length() < 64) {
-                       StringBuilder sb = new StringBuilder(64);
-                       for (int i = 0; i < 64 - str.length(); i++)
-                               sb.append('0');
-                       sb.append(str);
-                       return sb.toString();
-               } else
-                       return str;
-       }
-
 }
index 61f5b8304d3710713a500fa2fc7347ec81ae07c6..25ba62b03ba4d7224bcc8ec3326838a68b95b9ce 100644 (file)
@@ -19,7 +19,7 @@ import java.util.concurrent.atomic.AtomicLong;
  * A simple base implementation of {@link TimeUuidState}, which maintains
  * different clock sequences for each thread.
  */
-public class ConcurrentTimeUuidState implements TimeUuidState {
+public class ConcurrentTimeUuidState implements UuidFactory.TimeUuidState {
        private final static Logger logger = System.getLogger(ConcurrentTimeUuidState.class.getName());
 
        /** The maximum possible value of the clocksequence. */
@@ -46,8 +46,8 @@ public class ConcurrentTimeUuidState implements TimeUuidState {
                // compute the start reference
                startInstant = Instant.now(this.clock);
                long nowVm = nowVm();
-               Duration duration = Duration.between(TimeUuidState.GREGORIAN_START, startInstant);
-               startTimeStamp = durationToUuidTimestamp(duration) - nowVm;
+               Duration duration = Duration.between(TimeUuid.TIMESTAMP_ZERO, startInstant);
+               startTimeStamp = TimeUuid.durationToTimestamp(duration) - nowVm;
 
                clockSequenceProvider = new ClockSequenceProvider(secureRandom);
 
@@ -100,8 +100,8 @@ public class ConcurrentTimeUuidState implements TimeUuidState {
 
        private long computeNow() {
                if (useClockForMeasurement) {
-                       Duration duration = Duration.between(TimeUuidState.GREGORIAN_START, Instant.now(clock));
-                       return durationToUuidTimestamp(duration);
+                       Duration duration = Duration.between(TimeUuid.TIMESTAMP_ZERO, Instant.now(clock));
+                       return TimeUuid.durationToTimestamp(duration);
                } else {
                        return startTimeStamp + nowVm();
                }
@@ -111,10 +111,6 @@ public class ConcurrentTimeUuidState implements TimeUuidState {
                return System.nanoTime() / 100;
        }
 
-       private long durationToUuidTimestamp(Duration duration) {
-               return (duration.getSeconds() * 10000000 + duration.getNano() / 100);
-       }
-
        @Override
        public long getClockSequence() {
                return currentHolder.get().clockSequence;
@@ -141,8 +137,7 @@ public class ConcurrentTimeUuidState implements TimeUuidState {
        @Override
        public long getMostSignificantBits() {
                long timestamp = useTimestamp();
-               long mostSig = MOST_SIG_VERSION1 // base for version 1 UUID
-                               | ((timestamp & 0xFFFFFFFFL) << 32) // time_low
+               long mostSig = UuidFactory.MOST_SIG_VERSION1 | ((timestamp & 0xFFFFFFFFL) << 32) // time_low
                                | (((timestamp >> 32) & 0xFFFFL) << 16) // time_mid
                                | ((timestamp >> 48) & 0x0FFFL);// time_hi_and_version
                return mostSig;
index 14f6d54adb0d25467ad58c732fdc4654704a367c..6debd83b803426453c9e56b1594b6793bcaf6dcb 100644 (file)
@@ -1,21 +1,12 @@
 package org.argeo.api.uuid;
 
 import static java.lang.System.Logger.Level.DEBUG;
-import static java.lang.System.Logger.Level.INFO;
 import static java.lang.System.Logger.Level.WARNING;
 
 import java.lang.System.Logger;
-import java.net.Inet4Address;
-import java.net.Inet6Address;
-import java.net.InetAddress;
-import java.net.InterfaceAddress;
-import java.net.NetworkInterface;
-import java.net.SocketException;
 import java.security.DrbgParameters;
 import java.security.NoSuchAlgorithmException;
 import java.security.SecureRandom;
-import java.util.BitSet;
-import java.util.Enumeration;
 import java.util.Objects;
 import java.util.UUID;
 
@@ -28,25 +19,34 @@ import java.util.UUID;
 public class ConcurrentUuidFactory extends AbstractAsyncUuidFactory {
        private final static Logger logger = System.getLogger(ConcurrentUuidFactory.class.getName());
 
-       private Long nodeIdBase;
+       public ConcurrentUuidFactory(byte[] nodeId) {
+               this(nodeId, 0);
+       }
 
        public ConcurrentUuidFactory(byte[] nodeId, int offset) {
                Objects.requireNonNull(nodeId);
                if (offset + 6 > nodeId.length)
                        throw new IllegalArgumentException("Offset too big: " + offset);
                byte[] defaultNodeId = toNodeIdBytes(nodeId, offset);
-               nodeIdBase = NodeIdSupplier.toNodeIdBase(defaultNodeId);
+               long nodeIdBase = NodeIdSupplier.toNodeIdBase(defaultNodeId);
                setNodeIdSupplier(() -> nodeIdBase);
-               assert newTimeUUID().node() == BitSet.valueOf(defaultNodeId).toLongArray()[0];
        }
 
+       /**
+        * Empty constructor for use with component life cycle. A {@link NodeIdSupplier}
+        * must be set externally, otherwise time based UUID won't work.
+        */
        public ConcurrentUuidFactory() {
-               byte[] defaultNodeId = getIpBytes();
-               nodeIdBase = NodeIdSupplier.toNodeIdBase(defaultNodeId);
-               setNodeIdSupplier(() -> nodeIdBase);
-               assert newTimeUUID().node() == BitSet.valueOf(defaultNodeId).toLongArray()[0];
+               super();
        }
 
+//     public ConcurrentUuidFactory() {
+//             byte[] defaultNodeId = getIpBytes();
+//             nodeIdBase = NodeIdSupplier.toNodeIdBase(defaultNodeId);
+//             setNodeIdSupplier(() -> nodeIdBase);
+//             assert newTimeUUID().node() == BitSet.valueOf(defaultNodeId).toLongArray()[0];
+//     }
+
        /*
         * DEFAULT
         */
@@ -77,61 +77,4 @@ public class ConcurrentUuidFactory extends AbstractAsyncUuidFactory {
                return secureRandom;
        }
 
-       /** Returns an SHA1 digest of one of the IP addresses. */
-       protected byte[] getIpBytes() {
-               Enumeration<NetworkInterface> netInterfaces = null;
-               try {
-                       netInterfaces = NetworkInterface.getNetworkInterfaces();
-               } catch (SocketException e) {
-                       throw new IllegalStateException(e);
-               }
-               if (netInterfaces == null)
-                       throw new IllegalStateException("No interfaces");
-
-               InetAddress selectedIpv6 = null;
-               InetAddress selectedIpv4 = null;
-               netInterfaces: while (netInterfaces.hasMoreElements()) {
-                       NetworkInterface netInterface = netInterfaces.nextElement();
-                       byte[] hardwareAddress = null;
-                       try {
-                               hardwareAddress = netInterface.getHardwareAddress();
-                               if (hardwareAddress != null) {
-                                       // first IPv6
-                                       addr: for (InterfaceAddress addr : netInterface.getInterfaceAddresses()) {
-                                               InetAddress ip = addr.getAddress();
-                                               if (ip instanceof Inet6Address) {
-                                                       Inet6Address ipv6 = (Inet6Address) ip;
-                                                       if (ipv6.isAnyLocalAddress() || ipv6.isLinkLocalAddress() || ipv6.isLoopbackAddress())
-                                                               continue addr;
-                                                       selectedIpv6 = ipv6;
-                                                       break netInterfaces;
-                                               }
-
-                                       }
-                                       // then IPv4
-                                       addr: for (InterfaceAddress addr : netInterface.getInterfaceAddresses()) {
-                                               InetAddress ip = addr.getAddress();
-                                               if (ip instanceof Inet4Address) {
-                                                       Inet4Address ipv4 = (Inet4Address) ip;
-                                                       if (ipv4.isAnyLocalAddress() || ipv4.isLinkLocalAddress() || ipv4.isLoopbackAddress())
-                                                               continue addr;
-                                                       selectedIpv4 = ipv4;
-                                               }
-
-                                       }
-                               }
-                       } catch (SocketException e) {
-                               throw new IllegalStateException(e);
-                       }
-               }
-               InetAddress selectedIp = selectedIpv6 != null ? selectedIpv6 : selectedIpv4;
-               if (selectedIp == null)
-                       throw new IllegalStateException("No IP address found");
-               byte[] digest = sha1(selectedIp.getAddress());
-               logger.log(INFO, "Use IP " + selectedIp + " hashed as " + toHexString(digest) + " as node id");
-               byte[] nodeId = toNodeIdBytes(digest, 0);
-               // marks that this is not based on MAC address
-               forceToNoMacAddress(nodeId, 0);
-               return nodeId;
-       }
 }
\ No newline at end of file
index 39c919fa6d36976bed0439a0b2a2c22138ecf41b..9f27fad842bde97e615a2acef99425ee9ec4856b 100644 (file)
@@ -16,7 +16,7 @@ public class MacAddressUuidFactory extends ConcurrentUuidFactory {
        public final static UuidFactory DEFAULT = new MacAddressUuidFactory();
 
        public MacAddressUuidFactory() {
-               super(localHardwareAddressAsNodeId(), 0);
+               super(localHardwareAddressAsNodeId());
        }
 
        public static byte[] localHardwareAddressAsNodeId() {
index ae9686c7042781348643295ef29f58a302b510b6..94ec50da4b9ff76d3eb86fe94425d6e1ec9dddce 100644 (file)
@@ -4,11 +4,9 @@ import java.util.function.Supplier;
 
 /** A factory for node id base */
 public interface NodeIdSupplier extends Supplier<Long> {
-       long LEAST_SIG_RFC4122_VARIANT = (1l << 63);
-
        static long toNodeIdBase(byte[] node) {
                assert node.length == 6;
-               return LEAST_SIG_RFC4122_VARIANT // base for Leach–Salz UUID
+               return UuidFactory.LEAST_SIG_RFC4122_VARIANT
                                | (node[0] & 0xFFL) //
                                | ((node[1] & 0xFFL) << 8) //
                                | ((node[2] & 0xFFL) << 16) //
@@ -17,4 +15,8 @@ public interface NodeIdSupplier extends Supplier<Long> {
                                | ((node[5] & 0xFFL) << 40); //
        }
 
+       static boolean isNoMacAddressNodeId(byte[] nodeId) {
+               return (nodeId[0] & 1) != 0;
+       }
+
 }
diff --git a/org.argeo.api.uuid/src/org/argeo/api/uuid/TimeUuidState.java b/org.argeo.api.uuid/src/org/argeo/api/uuid/TimeUuidState.java
deleted file mode 100644 (file)
index 9c8b6dd..0000000
+++ /dev/null
@@ -1,42 +0,0 @@
-package org.argeo.api.uuid;
-
-import java.time.Instant;
-import java.time.ZoneOffset;
-import java.time.ZonedDateTime;
-import java.util.UUID;
-
-/**
- * The state of a time based UUID generator, as described and discussed in
- * section 4.2.1 of RFC4122.
- * 
- * @see https://datatracker.ietf.org/doc/html/rfc4122#section-4.2.1
- */
-public interface TimeUuidState {
-       long MOST_SIG_VERSION1 = (1l << 12);
-       long LEAST_SIG_RFC4122_VARIANT = (1l << 63);
-
-       /** Start of the Gregorian time, used by time-based UUID (v1). */
-       final static Instant GREGORIAN_START = ZonedDateTime.of(1582, 10, 15, 0, 0, 0, 0, ZoneOffset.UTC).toInstant();
-
-       /** Current node id and clock sequence for this thread. */
-       long getLeastSignificantBits();
-
-       /** A new current timestamp for this thread. */
-       long getMostSignificantBits();
-
-       /**
-        * The last timestamp which was produced by this thread, as returned by
-        * {@link UUID#timestamp()}.
-        */
-       long getLastTimestamp();
-
-       /**
-        * The current clock sequence for this thread, as returned by
-        * {@link UUID#clockSequence()}.
-        */
-       long getClockSequence();
-
-       static boolean isNoMacAddressNodeId(byte[] nodeId) {
-               return (nodeId[0] & 1) != 0;
-       }
-}
index dc83f48ec10ea62fbb5ea4c08578a27ae6276d43..4ab6c2e4b754d7818be29a24fece361373b5f6e9 100644 (file)
@@ -17,6 +17,7 @@ import java.util.function.Supplier;
  * @see https://datatracker.ietf.org/doc/html/rfc4122
  */
 public interface UuidFactory extends Supplier<UUID> {
+
        /*
         * DEFAULT
         */
@@ -158,6 +159,14 @@ public interface UuidFactory extends Supplier<UUID> {
         */
        final static UUID NAMESPACE_UUID_X500 = UUID.fromString("6ba7b814-9dad-11d1-80b4-00c04fd430c8");
 
+       /*
+        * BIT LEVEL CONSTANTS
+        */
+       /** Base for the most significant bit of version 1 (time based) UUIDs. */
+       long MOST_SIG_VERSION1 = (1l << 12);
+       /** Base for the least significant part of RFC4122 (variant 2) UUIDs. */
+       long LEAST_SIG_RFC4122_VARIANT = (1l << 63);
+
        /*
         * UTILITIES
         */
@@ -188,4 +197,30 @@ public interface UuidFactory extends Supplier<UUID> {
        static boolean isNameBased(UUID uuid) {
                return uuid.version() == 3 || uuid.version() == 5;
        }
+
+       /**
+        * The state of a time based UUID generator, as described and discussed in
+        * section 4.2.1 of RFC4122.
+        * 
+        * @see https://datatracker.ietf.org/doc/html/rfc4122#section-4.2.1
+        */
+       interface TimeUuidState {
+               /** Current node id and clock sequence for this thread. */
+               long getLeastSignificantBits();
+
+               /** A new current timestamp for this thread. */
+               long getMostSignificantBits();
+
+               /**
+                * The last timestamp which was produced by this thread, as returned by
+                * {@link UUID#timestamp()}.
+                */
+               long getLastTimestamp();
+
+               /**
+                * The current clock sequence for this thread, as returned by
+                * {@link UUID#clockSequence()}.
+                */
+               long getClockSequence();
+       }
 }
diff --git a/org.argeo.cms/src/org/argeo/cms/acr/CmsUuidFactory.java b/org.argeo.cms/src/org/argeo/cms/acr/CmsUuidFactory.java
new file mode 100644 (file)
index 0000000..de0be36
--- /dev/null
@@ -0,0 +1,86 @@
+package org.argeo.cms.acr;
+
+import java.net.Inet4Address;
+import java.net.Inet6Address;
+import java.net.InetAddress;
+import java.net.InterfaceAddress;
+import java.net.NetworkInterface;
+import java.net.SocketException;
+import java.util.BitSet;
+import java.util.Enumeration;
+
+import org.argeo.api.cms.CmsLog;
+import org.argeo.api.uuid.ConcurrentUuidFactory;
+import org.argeo.api.uuid.UuidBinaryUtils;
+
+public class CmsUuidFactory extends ConcurrentUuidFactory {
+       private final static CmsLog log = CmsLog.getLog(CmsUuidFactory.class);
+
+       public CmsUuidFactory(byte[] nodeId) {
+               super(nodeId);
+               assert newTimeUUID().node() == BitSet.valueOf(toNodeIdBytes(nodeId, 0)).toLongArray()[0];
+       }
+
+       public CmsUuidFactory() {
+               this(getIpBytes());
+       }
+
+       /** Returns an SHA1 digest of one of the IP addresses. */
+       protected static byte[] getIpBytes() {
+               Enumeration<NetworkInterface> netInterfaces = null;
+               try {
+                       netInterfaces = NetworkInterface.getNetworkInterfaces();
+               } catch (SocketException e) {
+                       throw new IllegalStateException(e);
+               }
+               if (netInterfaces == null)
+                       throw new IllegalStateException("No interfaces");
+
+               InetAddress selectedIpv6 = null;
+               InetAddress selectedIpv4 = null;
+               netInterfaces: while (netInterfaces.hasMoreElements()) {
+                       NetworkInterface netInterface = netInterfaces.nextElement();
+                       byte[] hardwareAddress = null;
+                       try {
+                               hardwareAddress = netInterface.getHardwareAddress();
+                               if (hardwareAddress != null) {
+                                       // first IPv6
+                                       addr: for (InterfaceAddress addr : netInterface.getInterfaceAddresses()) {
+                                               InetAddress ip = addr.getAddress();
+                                               if (ip instanceof Inet6Address) {
+                                                       Inet6Address ipv6 = (Inet6Address) ip;
+                                                       if (ipv6.isAnyLocalAddress() || ipv6.isLinkLocalAddress() || ipv6.isLoopbackAddress())
+                                                               continue addr;
+                                                       selectedIpv6 = ipv6;
+                                                       break netInterfaces;
+                                               }
+
+                                       }
+                                       // then IPv4
+                                       addr: for (InterfaceAddress addr : netInterface.getInterfaceAddresses()) {
+                                               InetAddress ip = addr.getAddress();
+                                               if (ip instanceof Inet4Address) {
+                                                       Inet4Address ipv4 = (Inet4Address) ip;
+                                                       if (ipv4.isAnyLocalAddress() || ipv4.isLinkLocalAddress() || ipv4.isLoopbackAddress())
+                                                               continue addr;
+                                                       selectedIpv4 = ipv4;
+                                               }
+
+                                       }
+                               }
+                       } catch (SocketException e) {
+                               throw new IllegalStateException(e);
+                       }
+               }
+               InetAddress selectedIp = selectedIpv6 != null ? selectedIpv6 : selectedIpv4;
+               if (selectedIp == null)
+                       throw new IllegalStateException("No IP address found");
+               byte[] digest = sha1(selectedIp.getAddress());
+               log.info("Use IP " + selectedIp + " hashed as " + UuidBinaryUtils.toHexString(digest) + " as node id");
+               byte[] nodeId = toNodeIdBytes(digest, 0);
+               // marks that this is not based on MAC address
+               forceToNoMacAddress(nodeId, 0);
+               return nodeId;
+       }
+
+}