1 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 ; 10 import java.security.SecureRandom ; 11 import java.util.Random ; 12 13 public class UUID { 14 15 private static final TCLogger logger = TCLogging.getLogger(UUID.class); 16 private static final Method jdk15createMethod; 17 18 private final String 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 getDefault() { 26 Random r = new SecureRandom (); 27 long l1 = r.nextLong(); 28 long l2 = r.nextLong(); 29 return Long.toHexString(l1) + Long.toHexString(l2); 30 } 31 32 private static String getJDK15() { 33 try { 34 Object object = jdk15createMethod.invoke(null, new Object [] {}); 35 String s = object.toString(); 36 return s.replaceAll("[^A-Fa-f0-9]", ""); 37 } catch (Exception e) { 38 throw new AssertionError (e); 39 } 40 } 41 42 public String toString() { 43 return uuid; 44 } 45 46 private UUID(String uuid) { 47 this.uuid = makeSize32(uuid); 48 if(32 != this.uuid.length()) { 49 throw new AssertionError ("UUID : length is not 32 but " + this.uuid.length() + " : UUID is : " + this.uuid); 50 } 51 } 52 53 private String makeSize32(String uuid2) { 55 int len = uuid2.length() ; 56 if(len < 32 ) { 57 StringBuffer sb = new StringBuffer (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 jdk15UUID = null; 76 try { 77 Class c = Class.forName("java.util.UUID"); 78 jdk15UUID = c.getDeclaredMethod("randomUUID", new Class [] {}); 79 } catch (Throwable 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 args[]) { 87 for (int i = 0; i < 10; i++) { 88 System.out.println(UUID.getUUID()); 89 } 90 } 91 92 } 93 | Popular Tags |