01: /*
02: * Copyright 2001-2007 Geert Bevin <gbevin[remove] at uwyn dot com>
03: * Distributed under the terms of either:
04: * - the common development and distribution license (CDDL), v1.0; or
05: * - the GNU Lesser General Public License, v2.1 or later
06: * $Id: UniqueIDGenerator.java 3634 2007-01-08 21:42:24Z gbevin $
07: */
08: package com.uwyn.rife.tools;
09:
10: import java.net.InetAddress;
11: import java.net.UnknownHostException;
12: import java.security.MessageDigest;
13: import java.security.NoSuchAlgorithmException;
14: import java.util.Date;
15: import java.util.Random;
16:
17: public abstract class UniqueIDGenerator {
18: private static final String ALGORITHM = "MD5";
19:
20: private static Random sRandom = new Random(System
21: .currentTimeMillis());
22: private static String sLocalHostSeed = null;
23:
24: public static UniqueID generate() {
25: if (null == sLocalHostSeed) {
26: String seed = null;
27: try {
28: seed = InetAddress.getLocalHost().toString();
29: } catch (UnknownHostException e) {
30: seed = "localhost/127.0.0.1";
31: }
32:
33: sLocalHostSeed = seed;
34: }
35:
36: return generate(sLocalHostSeed);
37: }
38:
39: public static UniqueID generate(String seed) {
40: seed = seed + (new Date()).toString();
41: seed = seed + Long.toString(sRandom.nextLong());
42: MessageDigest md = null;
43: try {
44: md = MessageDigest.getInstance(ALGORITHM);
45: } catch (NoSuchAlgorithmException e) {
46: return null;
47: }
48: md.update(seed.getBytes());
49:
50: return new UniqueID(md.digest());
51: }
52: }
|