1 package org
.argeo
.cms
.internal
.runtime
;
3 import java
.net
.Inet4Address
;
4 import java
.net
.Inet6Address
;
5 import java
.net
.InetAddress
;
6 import java
.net
.InterfaceAddress
;
7 import java
.net
.NetworkInterface
;
8 import java
.net
.SocketException
;
9 import java
.util
.BitSet
;
10 import java
.util
.Enumeration
;
12 import org
.argeo
.api
.cms
.CmsLog
;
13 import org
.argeo
.api
.uuid
.ConcurrentUuidFactory
;
14 import org
.argeo
.api
.uuid
.NodeIdSupplier
;
15 import org
.argeo
.api
.uuid
.UuidBinaryUtils
;
18 class CmsUuidFactory
extends ConcurrentUuidFactory
{
19 private final static CmsLog log
= CmsLog
.getLog(CmsUuidFactory
.class);
21 public CmsUuidFactory(byte[] nodeId
) {
23 assert createTimeUUID().node() == BitSet
.valueOf(NodeIdSupplier
.toNodeIdBytes(nodeId
, 0)).toLongArray()[0];
26 public CmsUuidFactory() {
30 /** Returns an SHA1 digest of one of the IP addresses. */
31 protected static byte[] getIpBytes() {
32 Enumeration
<NetworkInterface
> netInterfaces
= null;
34 netInterfaces
= NetworkInterface
.getNetworkInterfaces();
35 } catch (SocketException e
) {
36 throw new IllegalStateException(e
);
39 InetAddress selectedIpv6
= null;
40 InetAddress selectedIpv4
= null;
41 if (netInterfaces
!= null) {
42 netInterfaces
: while (netInterfaces
.hasMoreElements()) {
43 NetworkInterface netInterface
= netInterfaces
.nextElement();
44 byte[] hardwareAddress
= null;
46 hardwareAddress
= netInterface
.getHardwareAddress();
47 if (hardwareAddress
!= null) {
49 addr
: for (InterfaceAddress addr
: netInterface
.getInterfaceAddresses()) {
50 InetAddress ip
= addr
.getAddress();
51 if (ip
instanceof Inet6Address
) {
52 Inet6Address ipv6
= (Inet6Address
) ip
;
53 if (ipv6
.isAnyLocalAddress() || ipv6
.isLinkLocalAddress() || ipv6
.isLoopbackAddress())
61 addr
: for (InterfaceAddress addr
: netInterface
.getInterfaceAddresses()) {
62 InetAddress ip
= addr
.getAddress();
63 if (ip
instanceof Inet4Address
) {
64 Inet4Address ipv4
= (Inet4Address
) ip
;
65 if (ipv4
.isAnyLocalAddress() || ipv4
.isLinkLocalAddress() || ipv4
.isLoopbackAddress())
68 // we keep searching for IPv6
73 } catch (SocketException e
) {
74 throw new IllegalStateException(e
);
78 InetAddress selectedIp
= selectedIpv6
!= null ? selectedIpv6
: selectedIpv4
;
79 if (selectedIp
== null) {
80 log
.warn("No IP address found, using a random node id for UUID generation");
81 return NodeIdSupplier
.randomNodeId();
83 byte[] digest
= sha1(selectedIp
.getAddress());
84 log
.debug("Use IP " + selectedIp
+ " hashed as " + UuidBinaryUtils
.toHexString(digest
) + " as node id");
85 byte[] nodeId
= NodeIdSupplier
.toNodeIdBytes(digest
, 0);
86 // marks that this is not based on MAC address
87 NodeIdSupplier
.forceToNoMacAddress(nodeId
, 0);