The drawback is that the address becomes part of the UUID which could be a security concern. The other possibility is to generate a fake address for each machine which could also guarantee uniqueness while getting around the possible security issue.
Here's the code to do it. Yes, this is using CDI to inject the UUID. You can replicate this using any DI framework or by simply using the class directly.
@Named
@ApplicationScoped
public class UuidService implements Serializable {
private UUIDGenerator uuidGen = null;
private EthernetAddress ethernet = null;
/**
* Set up the uuid generator
*/
@PostConstruct
private void init() {
uuidGen = UUIDGenerator.getInstance();
try {
Enumeration<NetworkInterface> ns = NetworkInterface.getNetworkInterfaces();
while (ns.hasMoreElements()) {
NetworkInterface n = ns.nextElement();
if (n.isUp() && !n.isLoopback()) {
// Grab the first external network interface and get the hardware address for UUID
byte[] byteAddress = n.getHardwareAddress();
ethernet = new EthernetAddress(byteAddress);
}
}
} catch (SocketException ex) {
Logger.getLogger(UuidService.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* UUID
* @return
*/
public String nextId() {
return uuidGen.generateTimeBasedUUID(ethernet).toString();
}
}
Here is the injection part.
@Inject UuidService service;
User u = new User(service.nextId());