KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > tc > util > UUID


1 /*
2  * All content copyright (c) 2003-2006 Terracotta, Inc., except as may otherwise be noted in a separate copyright notice. All rights reserved.
3  */

4 package com.tc.util;
5
6 import com.tc.logging.TCLogger;
7 import com.tc.logging.TCLogging;
8
9 import java.lang.reflect.Method JavaDoc;
10 import java.security.SecureRandom JavaDoc;
11 import java.util.Random JavaDoc;
12
13 public class UUID {
14
15   private static final TCLogger logger = TCLogging.getLogger(UUID.class);
16   private static final Method JavaDoc jdk15createMethod;
17
18   private final String JavaDoc uuid;
19
20   public static UUID getUUID() {
21     if (jdk15createMethod != null) { return new UUID(getJDK15()); }
22     return new UUID(getDefault());
23   }
24
25   private static String JavaDoc getDefault() {
26     Random JavaDoc r = new SecureRandom JavaDoc();
27     long l1 = r.nextLong();
28     long l2 = r.nextLong();
29     return Long.toHexString(l1) + Long.toHexString(l2);
30   }
31
32   private static String JavaDoc getJDK15() {
33     try {
34       Object JavaDoc object = jdk15createMethod.invoke(null, new Object JavaDoc[] {});
35       String JavaDoc s = object.toString();
36       return s.replaceAll("[^A-Fa-f0-9]", "");
37     } catch (Exception JavaDoc e) {
38       throw new AssertionError JavaDoc(e);
39     }
40   }
41
42   public String JavaDoc toString() {
43     return uuid;
44   }
45
46   private UUID(String JavaDoc uuid) {
47     this.uuid = makeSize32(uuid);
48     if(32 != this.uuid.length()) {
49       throw new AssertionError JavaDoc("UUID : length is not 32 but " + this.uuid.length() + " : UUID is : " + this.uuid);
50     }
51   }
52
53   // TODO:: TIM FIXME
54
private String JavaDoc makeSize32(String JavaDoc uuid2) {
55     int len = uuid2.length() ;
56     if(len < 32 ) {
57       StringBuffer JavaDoc sb = new StringBuffer JavaDoc(32);
58       while(len ++ < 32) {
59         sb.append('0');
60       }
61       sb.append(uuid2);
62       return sb.toString();
63     } else if ( len > 32) {
64       return uuid2.substring(0, 32);
65     } else {
66       return uuid2;
67     }
68   }
69
70   public static boolean usesJDKImpl() {
71     return jdk15createMethod != null;
72   }
73
74   static {
75     Method JavaDoc jdk15UUID = null;
76     try {
77       Class JavaDoc c = Class.forName("java.util.UUID");
78       jdk15UUID = c.getDeclaredMethod("randomUUID", new Class JavaDoc[] {});
79     } catch (Throwable JavaDoc t) {
80       logger.warn("JDK1.5+ UUID class not available, falling back to default implementation. " + t.getMessage());
81     }
82
83     jdk15createMethod = jdk15UUID;
84   }
85
86   public static void main(String JavaDoc args[]) {
87     for (int i = 0; i < 10; i++) {
88       System.out.println(UUID.getUUID());
89     }
90   }
91
92 }
93
Popular Tags