1 4 package com.tc.aspectwerkz.util; 5 6 import java.net.InetAddress ; 7 import java.security.SecureRandom ; 8 9 15 public class UuidGenerator { 16 19 private static SecureRandom s_seeder = null; 20 21 24 private static String s_midValue = null; 25 26 29 private static boolean s_initialized = false; 30 31 34 private UuidGenerator() { 35 } 36 37 43 public static String generate(Object obj) { 44 if (!s_initialized) { 45 initialize(obj); 46 } 47 long timeNow = System.currentTimeMillis(); 48 49 int timeLow = (int) timeNow & 0xFFFFFFFF; 51 int node = s_seeder.nextInt(); 52 return (hexFormat(timeLow, 8) + s_midValue + hexFormat(node, 8)); 53 } 54 55 60 private synchronized static void initialize(final Object obj) { 61 try { 62 InetAddress inet = InetAddress.getLocalHost(); 63 byte[] bytes = inet.getAddress(); 64 String hexInetAddress = hexFormat(getInt(bytes), 8); 65 String thisHashCode = hexFormat(System.identityHashCode(obj), 8); 66 s_midValue = hexInetAddress + thisHashCode; 67 s_seeder = new SecureRandom (); 68 s_seeder.nextInt(); 69 } catch (java.net.UnknownHostException e) { 70 throw new Error ("can not initialize the UuidGenerator generator"); 71 } 72 s_initialized = true; 73 } 74 75 81 private static int getInt(final byte[] abyte) { 82 int i = 0; 83 int j = 24; 84 for (int k = 0; j >= 0; k++) { 85 int l = abyte[k] & 0xff; 86 i += (l << j); 87 j -= 8; 88 } 89 return i; 90 } 91 92 99 private static String hexFormat(final int i, final int j) { 100 String s = Integer.toHexString(i); 101 return padHex(s, j) + s; 102 } 103 104 111 private static String padHex(final String str, final int i) { 112 StringBuffer buf = new StringBuffer (); 113 if (str.length() < i) { 114 for (int j = 0; j < (i - str.length()); j++) { 115 buf.append('0'); 116 } 117 } 118 return buf.toString(); 119 } 120 } | Popular Tags |