1 13 14 package org.ejbca.util; 15 16 import org.apache.log4j.Logger; 17 18 23 public class GUIDGenerator { 24 private static final Logger log = Logger.getLogger(GUIDGenerator.class); 25 26 27 private static String hexServerIP = null; 28 29 private static final java.security.SecureRandom seeder = new java.security.SecureRandom (); 31 32 38 public static final String generateGUID(Object o) { 39 StringBuffer tmpBuffer = new StringBuffer (16); 40 if (hexServerIP == null) { 41 java.net.InetAddress localInetAddress = null; 42 try { 43 localInetAddress = java.net.InetAddress.getLocalHost(); 45 } 46 catch (java.net.UnknownHostException uhe) { 47 log.error("Could not get the local IP address using InetAddress.getLocalHost(): ", uhe); 48 return null; 50 } 51 byte serverIP[] = localInetAddress.getAddress(); 52 hexServerIP = hexFormat(getInt(serverIP), 8); 53 } 54 55 String hashcode = hexFormat(System.identityHashCode(o), 8); 56 tmpBuffer.append(hexServerIP); 57 tmpBuffer.append(hashcode); 58 59 long timeNow = System.currentTimeMillis(); 60 int timeLow = (int)timeNow & 0xFFFFFFFF; 61 int node = seeder.nextInt(); 62 63 StringBuffer guid = new StringBuffer (32); 64 guid.append(hexFormat(timeLow, 8)); 65 guid.append(tmpBuffer.toString()); 66 guid.append(hexFormat(node, 8)); 67 return guid.toString(); 68 } 69 70 private static int getInt(byte bytes[]) { 71 int i = 0; 72 int j = 24; 73 for (int k = 0; j >= 0; k++) { 74 int l = bytes[k] & 0xff; 75 i += l << j; 76 j -= 8; 77 } 78 return i; 79 } 80 81 private static String hexFormat(int i, int j) { 82 String s = Integer.toHexString(i); 83 return padHex(s, j) + s; 84 } 85 86 private static String padHex(String s, int i) { 87 StringBuffer tmpBuffer = new StringBuffer (); 88 if (s.length() < i) { 89 for (int j = 0; j < i - s.length(); j++) { 90 tmpBuffer.append('0'); 91 } 92 } 93 return tmpBuffer.toString(); 94 } 95 } 96 | Popular Tags |