1 5 package org.exoplatform.services.idgenerator.impl; 6 7 import java.io.Serializable ; 8 import java.net.InetAddress ; 9 import java.security.SecureRandom ; 10 import org.exoplatform.services.idgenerator.IDGeneratorService; 11 16 public class IDGeneratorServiceImpl implements IDGeneratorService { 17 private static String hexServerIP_ = null; 18 private static final SecureRandom seeder_ = new SecureRandom (); 19 20 21 public Serializable generateID(Object o) { 22 return generateStringID(o) ; 23 } 24 25 public long generateLongID(Object o) { 26 throw new RuntimeException ("This operation is not supported") ; 27 } 28 29 public String generateStringID(Object o) { 30 StringBuffer tmpBuffer = new StringBuffer (16); 31 if (hexServerIP_ == null) { 32 InetAddress localInetAddress = null; 33 try { 34 localInetAddress = InetAddress.getLocalHost(); 36 } 37 catch (java.net.UnknownHostException uhe) { 38 System.err.println("ContentSetUtil: Could not get the local IP address using InetAddress.getLocalHost()!"); 39 uhe.printStackTrace(); 41 return null; 42 } 43 byte serverIP[] = localInetAddress.getAddress(); 44 hexServerIP_ = hexFormat(getInt(serverIP), 8); 45 } 46 String hashcode = hexFormat(System.identityHashCode(o), 8); 47 tmpBuffer.append(hexServerIP_); 48 tmpBuffer.append(hashcode); 49 50 long timeNow = System.currentTimeMillis(); 51 int timeLow = (int)timeNow & 0xFFFFFFFF; 52 int node = seeder_.nextInt(); 53 54 StringBuffer guid = new StringBuffer (32); 55 guid.append(hexFormat(timeLow, 8)); 56 guid.append(tmpBuffer.toString()); 57 guid.append(hexFormat(node, 8)); 58 return guid.toString(); 59 } 60 61 private static int getInt(byte bytes[]) { 62 int i = 0; 63 int j = 24; 64 for (int k = 0; j >= 0; k++) { 65 int l = bytes[k] & 0xff; 66 i += l << j; 67 j -= 8; 68 } 69 return i; 70 } 71 72 private static String hexFormat(int i, int j) { 73 String s = Integer.toHexString(i); 74 return padHex(s, j) + s; 75 } 76 77 private static String padHex(String s, int i) { 78 StringBuffer tmpBuffer = new StringBuffer (); 79 if (s.length() < i) { 80 for (int j = 0; j < i - s.length(); j++) { 81 tmpBuffer.append('0'); 82 } 83 } 84 return tmpBuffer.toString(); 85 } 86 } | Popular Tags |