1 package org
.argeo
.cms
.acr
;
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
;
17 public class CmsUuidFactory
extends ConcurrentUuidFactory
{
18 private final static CmsLog log
= CmsLog
.getLog(CmsUuidFactory
.class);
20 public CmsUuidFactory(byte[] nodeId
) {
22 assert createTimeUUID().node() == BitSet
.valueOf(toNodeIdBytes(nodeId
, 0)).toLongArray()[0];
25 public CmsUuidFactory() {
29 /** Returns an SHA1 digest of one of the IP addresses. */
30 protected static byte[] getIpBytes() {
31 Enumeration
<NetworkInterface
> netInterfaces
= null;
33 netInterfaces
= NetworkInterface
.getNetworkInterfaces();
34 } catch (SocketException e
) {
35 throw new IllegalStateException(e
);
37 if (netInterfaces
== null)
38 throw new IllegalStateException("No interfaces");
40 InetAddress selectedIpv6
= null;
41 InetAddress selectedIpv4
= 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())
72 } catch (SocketException e
) {
73 throw new IllegalStateException(e
);
76 InetAddress selectedIp
= selectedIpv6
!= null ? selectedIpv6
: selectedIpv4
;
77 if (selectedIp
== null) {
78 log
.warn("No IP address found, using a random node id for UUID generation");
79 return NodeIdSupplier
.randomNodeId();
81 byte[] digest
= sha1(selectedIp
.getAddress());
82 log
.info("Use IP " + selectedIp
+ " hashed as " + UuidBinaryUtils
.toHexString(digest
) + " as node id");
83 byte[] nodeId
= toNodeIdBytes(digest
, 0);
84 // marks that this is not based on MAC address
85 forceToNoMacAddress(nodeId
, 0);