1 8 package org.codehaus.aspectwerkz.util; 9 10 import java.net.InetAddress ; 11 import java.security.SecureRandom ; 12 13 19 public class UuidGenerator { 20 23 private static SecureRandom s_seeder = null; 24 25 28 private static String s_midValue = null; 29 30 33 private static boolean s_initialized = false; 34 35 38 private UuidGenerator() { 39 } 40 41 47 public static String generate(Object obj) { 48 if (!s_initialized) { 49 initialize(obj); 50 } 51 long timeNow = System.currentTimeMillis(); 52 53 int timeLow = (int) timeNow & 0xFFFFFFFF; 55 int node = s_seeder.nextInt(); 56 return (hexFormat(timeLow, 8) + s_midValue + hexFormat(node, 8)); 57 } 58 59 64 private synchronized static void initialize(final Object obj) { 65 try { 66 InetAddress inet = InetAddress.getLocalHost(); 67 byte[] bytes = inet.getAddress(); 68 String hexInetAddress = hexFormat(getInt(bytes), 8); 69 String thisHashCode = hexFormat(System.identityHashCode(obj), 8); 70 s_midValue = hexInetAddress + thisHashCode; 71 s_seeder = new SecureRandom (); 72 s_seeder.nextInt(); 73 } catch (java.net.UnknownHostException e) { 74 throw new Error ("can not initialize the UuidGenerator generator"); 75 } 76 s_initialized = true; 77 } 78 79 85 private static int getInt(final byte[] abyte) { 86 int i = 0; 87 int j = 24; 88 for (int k = 0; j >= 0; k++) { 89 int l = abyte[k] & 0xff; 90 i += (l << j); 91 j -= 8; 92 } 93 return i; 94 } 95 96 103 private static String hexFormat(final int i, final int j) { 104 String s = Integer.toHexString(i); 105 return padHex(s, j) + s; 106 } 107 108 115 private static String padHex(final String str, final int i) { 116 StringBuffer buf = new StringBuffer (); 117 if (str.length() < i) { 118 for (int j = 0; j < (i - str.length()); j++) { 119 buf.append('0'); 120 } 121 } 122 return buf.toString(); 123 } 124 } | Popular Tags |