01: /***
02: * jwma Java WebMail
03: * Copyright (c) 2000-2003 jwma team
04: *
05: * jwma is free software; you can distribute and use this source
06: * under the terms of the BSD-style license received along with
07: * the distribution.
08: ***/package dtw.webmail.util;
09:
10: import java.rmi.server.UID;
11: import java.net.URL;
12: import java.io.DataInputStream;
13: import java.util.Random;
14:
15: /**
16: * Utility class exposing a method that will return
17: * a unique identifier.
18: *
19: * @author Dieter Wimberger
20: * @version 0.9.7 07/02/2003
21: */
22: public class UIDGenerator {
23:
24: //class attributes
25: private static Random m_Random;
26: private static int m_ReseedCounter = 0;
27:
28: //create seeded random
29: static {
30: m_Random = new Random();
31: seedRandom();
32: }
33:
34: /**
35: * Returns a UID (unique identifier) as <tt>String</tt>.
36: * The identifier represents the MD5 hashed combination
37: * of a <tt>java.rmi.server.UID</tt> instance, a random padding of
38: * <tt>RANDOM_PADDING</tt> length, it's identity hashcode and
39: * <tt>System.currentTimeMillis()</tt>.
40: *
41: * @return the UID as <tt>String</tt>.
42: */
43: public static final synchronized String getUID() {
44: byte[] buffer = new byte[RANDOM_PADDING];
45: String u = new UID().toString();
46: int i = System.identityHashCode(u);
47: long d = System.currentTimeMillis();
48: //create random padding
49: m_Random.nextBytes(buffer);
50: u = u + new String(buffer);
51:
52: if (m_ReseedCounter == RANDOM_RESEED) {
53: seedRandom();
54: m_ReseedCounter = 0;
55: } else {
56: m_ReseedCounter++;
57: }
58: return MD5.hash(u + i + d);
59: }//getUID
60:
61: /**
62: * If the <tt>HotBits</tt> Server is available, <tt>Random</tt>
63: * will be seeded with a real random long.
64: * <p>
65: * <a href="http://www.fourmilab.ch/hotbits/">HotBits</a> is located
66: * at Fermilab, Switzerland.
67: *
68: */
69: public static final void seedRandom() {
70: try {
71: URL url = new URL(HOTBITS_URL);
72: DataInputStream din = new DataInputStream(url.openStream());
73: m_Random.setSeed(din.readLong());
74: din.close();
75: } catch (Exception ex) {
76: //use what is available
77: m_Random.setSeed(System.currentTimeMillis());
78: }
79: }//seedRandom
80:
81: public static final void main(String[] args) {
82: int i = 0;
83: long start = System.currentTimeMillis();
84: while (i < 1000) {
85: System.out.println(getUID());
86: i++;
87: }
88: long stop = System.currentTimeMillis();
89: System.out.println("Time =" + (stop - start) + "[ms]");
90: }//main
91:
92: public static final int RANDOM_PADDING = 256;
93: public static final int RANDOM_SEED_LENGTH = 6;
94: public static final int RANDOM_RESEED = 1000;
95:
96: public static final String HOTBITS_URL = "http://www.fourmilab.ch/cgi-bin/uncgi/Hotbits?nbytes="
97: + RANDOM_SEED_LENGTH + "&fmt=bin";
98:
99: }//UIDGenerator
|