1 23 24 package org.mdarad.framework.util; 25 26 import org.mdarad.framework.util.GUIDGenerationException; 27 28 import java.net.UnknownHostException ; 29 import java.net.InetAddress ; 30 31 38 public class GUIDGenerator { 39 40 43 private static String hexServerIP = null; 44 45 private static final java.security.SecureRandom seeder = new java.security.SecureRandom (); 47 48 53 public static final String generateGUID(Object o) throws GUIDGenerationException { 54 StringBuffer tmpBuffer = new StringBuffer (16); 55 if (hexServerIP == null) { 56 InetAddress localInetAddress = null; 57 58 try { 59 localInetAddress = InetAddress.getLocalHost(); 61 byte serverIP[] = localInetAddress.getAddress(); 62 hexServerIP = hexFormat(getInt(serverIP), 8); 63 } catch (UnknownHostException e) { 64 throw new GUIDGenerationException("Could not generate GUID, for unable to reach localhost", e); 65 } 66 } 67 String hashcode = hexFormat(System.identityHashCode(o), 8); 68 tmpBuffer.append(hexServerIP); 69 tmpBuffer.append(hashcode); 70 71 long timeNow = System.currentTimeMillis(); 72 int timeLow = (int) timeNow & 0xFFFFFFFF; 73 int node = seeder.nextInt(); 74 75 StringBuffer guid = new StringBuffer (32); 76 guid.append(hexFormat(timeLow, 8)); 77 guid.append(tmpBuffer.toString()); 78 guid.append(hexFormat(node, 8)); 79 return guid.toString(); 80 } 81 82 83 private static int getInt(byte bytes[]) { 84 int i = 0; 85 int j = 24; 86 for (int k = 0; j >= 0; k++) { 87 int l = bytes[k] & 0xff; 88 i += l << j; 89 j -= 8; 90 } 91 return i; 92 } 93 94 private static String hexFormat(int i, int j) { 95 String s = Integer.toHexString(i); 96 return padHex(s, j) + s; 97 } 98 99 private static String padHex(String s, int i) { 100 StringBuffer tmpBuffer = new StringBuffer (); 101 if (s.length() < i) { 102 for (int j = 0; j < i - s.length(); j++) { 103 tmpBuffer.append('0'); 104 } 105 } 106 return tmpBuffer.toString(); 107 } 108 109 } 110 | Popular Tags |