KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > jodd > util > idgen > UuidGenerator


1 // Copyright (c) 2003-2007, Jodd Team (jodd.sf.net). All Rights Reserved.
2

3 package jodd.util.idgen;
4
5 /**
6  * Two UUID generators.Generated UUIDs are not sequencial.
7  */

8 public class UuidGenerator {
9
10     /**
11      * Returns unique String of 16 chars. This string is based on following template:
12      * <ul>
13      * <li>32bits from current time,
14      * <li>32bits from identityHashCode
15      * <li>32bits from random
16      * </ul>
17      * Total 96 bits, that are coded with base 6 so resulting string will
18      * have just 16 chars.
19      */

20     public static String JavaDoc generate(Object JavaDoc o) {
21         long id1 = System.currentTimeMillis() & 0xFFFFFFFFL;
22         long id2 = System.identityHashCode(o);
23         long id3 = jodd.util.MathUtil.randomLong(-0x80000000L, 0x80000000L) & 0xFFFFFFFFL;
24
25         id1 <<= 16;
26         id1 += (id2 & 0xFFFF0000L) >> 16;
27         id3 += (id2 & 0x0000FFFFL) << 32;
28
29         return unisgnedValueOf(id1) + unisgnedValueOf(id3);
30     }
31
32     /**
33      * Returns 10 random chars just based on current time and a random string.
34      * @see #generate(Object o)
35      */

36     public static String JavaDoc generate() {
37         long id1 = System.currentTimeMillis() & 0x3FFFFFFFL;
38         long id3 = jodd.util.MathUtil.randomLong(-0x80000000L, 0x80000000L) & 0x3FFFFFFFL;
39         return unisgnedValueOf(id1) + unisgnedValueOf(id3);
40     }
41
42     private final static char[] chars64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".toCharArray();
43     
44     private static String JavaDoc unisgnedValueOf(long l) {
45         char[] buf = new char[64];
46         int charNdx = 64;
47         int radix = 1 << 6;
48         long mask = radix - 1;
49         do {
50             buf[--charNdx] = chars64[(int)(l & mask)];
51             l >>>= 6;
52         } while (l != 0);
53         return new String JavaDoc(buf, charNdx, (64 - charNdx));
54     }
55
56 }
57
Popular Tags