]> git.argeo.org Git - lgpl/argeo-commons.git/blob - org.argeo.api.uuid/src/org/argeo/api/uuid/ConcurrentUuidFactory.java
Experiment with package-based make
[lgpl/argeo-commons.git] / org.argeo.api.uuid / src / org / argeo / api / uuid / ConcurrentUuidFactory.java
1 package org.argeo.api.uuid;
2
3 import static java.lang.System.Logger.Level.DEBUG;
4 import static java.lang.System.Logger.Level.WARNING;
5
6 import java.lang.System.Logger;
7 import java.security.DrbgParameters;
8 import java.security.NoSuchAlgorithmException;
9 import java.security.SecureRandom;
10 import java.util.Objects;
11 import java.util.UUID;
12
13 /**
14 * A configurable implementation of an {@link AsyncUuidFactory}, which can be
15 * used as a base class for more optimised implementations.
16 *
17 * @see https://datatracker.ietf.org/doc/html/rfc4122
18 */
19 public class ConcurrentUuidFactory extends AbstractAsyncUuidFactory implements TypedUuidFactory {
20 private final static Logger logger = System.getLogger(ConcurrentUuidFactory.class.getName());
21
22 public ConcurrentUuidFactory(long initialClockRange, byte[] nodeId) {
23 this(initialClockRange, nodeId, 0);
24 }
25
26 public ConcurrentUuidFactory(long initialClockRange, byte[] nodeId, int offset) {
27 Objects.requireNonNull(nodeId);
28 if (offset + 6 > nodeId.length)
29 throw new IllegalArgumentException("Offset too big: " + offset);
30 byte[] defaultNodeId = toNodeIdBytes(nodeId, offset);
31 long nodeIdBase = NodeIdSupplier.toNodeIdBase(defaultNodeId);
32 setNodeIdSupplier(() -> nodeIdBase, initialClockRange);
33 }
34
35 /**
36 * Empty constructor for use with component life cycle. A {@link NodeIdSupplier}
37 * must be set externally, otherwise time based UUID won't work.
38 */
39 public ConcurrentUuidFactory() {
40 super();
41 }
42
43 // public ConcurrentUuidFactory() {
44 // byte[] defaultNodeId = getIpBytes();
45 // nodeIdBase = NodeIdSupplier.toNodeIdBase(defaultNodeId);
46 // setNodeIdSupplier(() -> nodeIdBase);
47 // assert newTimeUUID().node() == BitSet.valueOf(defaultNodeId).toLongArray()[0];
48 // }
49
50 /*
51 * DEFAULT
52 */
53 /**
54 * The default {@link UUID} to provide. This implementations returns
55 * {@link #timeUUID()} because it is fast and uses few resources.
56 */
57 @Override
58 public UUID get() {
59 return timeUUID();
60 }
61
62 @Override
63 protected SecureRandom createSecureRandom() {
64 SecureRandom secureRandom;
65 try {
66 secureRandom = SecureRandom.getInstance("DRBG",
67 DrbgParameters.instantiation(256, DrbgParameters.Capability.PR_AND_RESEED, "UUID".getBytes()));
68 } catch (NoSuchAlgorithmException e) {
69 try {
70 logger.log(DEBUG, "DRBG secure random not found, using strong");
71 secureRandom = SecureRandom.getInstanceStrong();
72 } catch (NoSuchAlgorithmException e1) {
73 logger.log(WARNING, "No strong secure random was found, using default");
74 secureRandom = new SecureRandom();
75 }
76 }
77 return secureRandom;
78 }
79
80 }