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
.UuidBinaryUtils
;
16 public class CmsUuidFactory
extends ConcurrentUuidFactory
{
17 private final static CmsLog log
= CmsLog
.getLog(CmsUuidFactory
.class);
19 public CmsUuidFactory(byte[] nodeId
) {
21 assert createTimeUUID().node() == BitSet
.valueOf(toNodeIdBytes(nodeId
, 0)).toLongArray()[0];
24 public CmsUuidFactory() {
28 /** Returns an SHA1 digest of one of the IP addresses. */
29 protected static byte[] getIpBytes() {
30 Enumeration
<NetworkInterface
> netInterfaces
= null;
32 netInterfaces
= NetworkInterface
.getNetworkInterfaces();
33 } catch (SocketException e
) {
34 throw new IllegalStateException(e
);
36 if (netInterfaces
== null)
37 throw new IllegalStateException("No interfaces");
39 InetAddress selectedIpv6
= null;
40 InetAddress selectedIpv4
= null;
41 netInterfaces
: while (netInterfaces
.hasMoreElements()) {
42 NetworkInterface netInterface
= netInterfaces
.nextElement();
43 byte[] hardwareAddress
= null;
45 hardwareAddress
= netInterface
.getHardwareAddress();
46 if (hardwareAddress
!= null) {
48 addr
: for (InterfaceAddress addr
: netInterface
.getInterfaceAddresses()) {
49 InetAddress ip
= addr
.getAddress();
50 if (ip
instanceof Inet6Address
) {
51 Inet6Address ipv6
= (Inet6Address
) ip
;
52 if (ipv6
.isAnyLocalAddress() || ipv6
.isLinkLocalAddress() || ipv6
.isLoopbackAddress())
60 addr
: for (InterfaceAddress addr
: netInterface
.getInterfaceAddresses()) {
61 InetAddress ip
= addr
.getAddress();
62 if (ip
instanceof Inet4Address
) {
63 Inet4Address ipv4
= (Inet4Address
) ip
;
64 if (ipv4
.isAnyLocalAddress() || ipv4
.isLinkLocalAddress() || ipv4
.isLoopbackAddress())
71 } catch (SocketException e
) {
72 throw new IllegalStateException(e
);
75 InetAddress selectedIp
= selectedIpv6
!= null ? selectedIpv6
: selectedIpv4
;
76 if (selectedIp
== null)
77 throw new IllegalStateException("No IP address found");
78 byte[] digest
= sha1(selectedIp
.getAddress());
79 log
.info("Use IP " + selectedIp
+ " hashed as " + UuidBinaryUtils
.toHexString(digest
) + " as node id");
80 byte[] nodeId
= toNodeIdBytes(digest
, 0);
81 // marks that this is not based on MAC address
82 forceToNoMacAddress(nodeId
, 0);