KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > columba > core > base > UUIDGenerator


1 /**
2  *
3  * Copyright 2001 Sun Microsystems(TM), Inc. All Rights Reserved.
4  *
5  * The contents of this file are made available under and subject to the
6  * Research Use Rights of the Sun(TM) Community Source License v 3.0 (the
7  * "License"). Software distributed under the License is distributed on an "AS
8  * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
9  * License for the specific language governing rights and limitations under
10  * the License.
11  *
12  * Contributor(s): Sun Microsystems, Inc.
13  *
14  */

15 package org.columba.core.base;
16
17 import java.security.SecureRandom JavaDoc;
18
19 /**
20  * A universally unique identifier (UUID). A UUID is a 128-bit value.
21  * <p>
22  * Standard RFC 4122:
23  * ftp://ftp.isi.edu/in-notes/rfc4122.txt
24  * <p>
25  */

26 public class UUIDGenerator {
27
28     /**
29      * random number generator for UUID generation
30      */

31     private final SecureRandom JavaDoc secRand = new SecureRandom JavaDoc();
32
33     /**
34      * 128-bit buffer for use with secRand
35      */

36     private final byte[] secRandBuf16 = new byte[16];
37
38     public UUIDGenerator() {
39         super();
40     }
41
42     /**
43      * @return uuid as String
44      */

45     public String JavaDoc newUUID() {
46         secRand.nextBytes(secRandBuf16);
47         secRandBuf16[6] &= 0x0f;
48         secRandBuf16[6] |= 0x40; /* version 4 */
49         secRandBuf16[8] &= 0x3f;
50         secRandBuf16[8] |= 0x80; /* IETF variant */
51         secRandBuf16[10] |= 0x80; /* multicast bit */
52         long mostSig = 0;
53         for (int i = 0; i < 8; i++) {
54             mostSig = (mostSig << 8) | (secRandBuf16[i] & 0xff);
55         }
56         long leastSig = 0;
57         for (int i = 8; i < 16; i++) {
58             leastSig = (leastSig << 8) | (secRandBuf16[i] & 0xff);
59         }
60         return (digits(mostSig >> 32, 8) + "-" + digits(mostSig >> 16, 4) + "-" //$NON-NLS-1$//$NON-NLS-2$
61
+ digits(mostSig, 4) + "-" + digits(leastSig >> 48, 4) + "-" + digits( //$NON-NLS-1$//$NON-NLS-2$
62
leastSig, 12));
63     }
64
65     /** Returns val represented by the specified number of hex digits. */
66     private static String JavaDoc digits(long val, int digits) {
67         long hi = 1L << (digits * 4);
68         return Long.toHexString(hi | (val & (hi - 1))).substring(1);
69     }
70
71 }
72
Popular Tags