reset();
}
+ protected NodeIdSupplier getNodeIdSupplier() {
+ return nodeIdSupplier;
+ }
+
/*
* SYNC OPERATIONS
*/
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);
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;
}
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);
}
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);
}
/*
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);
return checksum;
}
- protected byte[] md5(byte[]... bytes) {
+ protected static byte[] md5(byte[]... bytes) {
MessageDigest digest = getMd5Digest();
for (byte[] arr : bytes)
digest.update(arr);
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) {
}
}
- /*
- * 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;
- }
-
}
* 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. */
// 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);
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();
}
return System.nanoTime() / 100;
}
- private long durationToUuidTimestamp(Duration duration) {
- return (duration.getSeconds() * 10000000 + duration.getNano() / 100);
- }
-
@Override
public long getClockSequence() {
return currentHolder.get().clockSequence;
@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;
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;
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
*/
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
public final static UuidFactory DEFAULT = new MacAddressUuidFactory();
public MacAddressUuidFactory() {
- super(localHardwareAddressAsNodeId(), 0);
+ super(localHardwareAddressAsNodeId());
}
public static byte[] localHardwareAddressAsNodeId() {
/** 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) //
| ((node[5] & 0xFFL) << 40); //
}
+ static boolean isNoMacAddressNodeId(byte[] nodeId) {
+ return (nodeId[0] & 1) != 0;
+ }
+
}
+++ /dev/null
-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;
- }
-}
* @see https://datatracker.ietf.org/doc/html/rfc4122
*/
public interface UuidFactory extends Supplier<UUID> {
+
/*
* DEFAULT
*/
*/
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
*/
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();
+ }
}
--- /dev/null
+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;
+ }
+
+}