1 package nl.hippo.uidgenerator; 2 3 import java.net.InetAddress ; 4 import java.net.UnknownHostException ; 5 import java.security.SecureRandom ; 6 7 13 public class UIDGenerator 14 { 15 private SecureRandom m_randomNumberGenerator; 16 17 private String m_middle16Characters; 18 19 private static UIDGenerator s_instance; 20 21 public static String generateUID() throws UIDGeneratorException 22 { 23 return getInstance().generateNext(); 24 } 25 26 public UIDGenerator() throws UIDGeneratorException 27 { 28 super(); 29 m_randomNumberGenerator = new SecureRandom (); 30 StringBuffer middle16Characters = new StringBuffer (); 31 middle16Characters.append(toHexString(getLeastSignificantIpAddressData())); 32 middle16Characters.append(toHexString(System.identityHashCode(this))); 33 m_middle16Characters = middle16Characters.toString(); 34 } 35 36 public String generateNext() 37 { 38 int first32Bits = (int) (System.currentTimeMillis() & 0xFFFFFFFFl); 39 int fourth32Bits = getNextRandomNumber(); 40 StringBuffer result = new StringBuffer (toHexString(first32Bits)); 41 result.append(m_middle16Characters); 42 result.append(toHexString(fourth32Bits)); 43 return result.toString(); 44 } 45 46 private static synchronized UIDGenerator getInstance() throws UIDGeneratorException 47 { 48 if (s_instance == null) 49 { 50 s_instance = new UIDGenerator(); 51 } 52 return s_instance; 53 } 54 55 private static int getLeastSignificantIpAddressData() throws UIDGeneratorException 56 { 57 int result = 0; 58 try 59 { 60 byte[] ipAddress = InetAddress.getLocalHost().getAddress(); 61 if (ipAddress.length >= 4) 62 { 63 for (int i = 0; i < 4; i++) 64 { 65 result <<= 8; 66 result += ipAddress[ipAddress.length - 4 + i] & 0xFF; 67 } 68 } 69 else 70 { 71 throw new UIDGeneratorException("Not enough information in IP address"); 72 } 73 } 74 catch (UnknownHostException e) 75 { 76 throw new UIDGeneratorException(e); 77 } 78 79 return result; 80 } 81 82 private static String toHexString(int value) 83 { 84 String hexStringWithLeadingZeros = "0000000" + Integer.toHexString(value); 85 return hexStringWithLeadingZeros.substring(hexStringWithLeadingZeros.length() - 8); 86 } 87 88 private int getNextRandomNumber() 89 { 90 return m_randomNumberGenerator.nextInt(); 91 } 92 93 } 94 | Popular Tags |