1 15 16 package org.snipsnap.jdbc; 17 18 19 20 import java.math.BigInteger ; 21 import java.net.InetAddress ; 22 import java.net.UnknownHostException ; 23 import java.util.Random ; 24 25 35 36 public final class UIDGenerator { 37 38 39 40 public final static int MAX_LENGTH = 55; 41 42 43 44 private final static String ZEROS = "0000000000000"; 45 private final static int ZEROSLENGTH = ZEROS.length(); 46 47 private static long detail = normalize((new Random ()).nextLong()); 48 49 57 58 public final static String generate(long aCode) { 59 60 61 long code = normalize(aCode); 62 long ip = getIP(); 63 long timestamp = System.currentTimeMillis(); 64 65 66 67 StringBuffer buffer = new StringBuffer (); 68 69 buffer.append(createString(code)); 70 buffer.append("-"); 71 buffer.append(createString(ip)); 72 buffer.append("-"); 73 buffer.append(createString(timestamp)); 74 buffer.append("-"); 75 buffer.append(createString(detail)); 76 77 return buffer.toString().toUpperCase(); 78 } 79 80 88 89 public final static String generate(Class aClass) { 90 return UIDGenerator.generate(aClass.hashCode()); 91 } 92 93 100 101 private final static long getIP() { 102 try { 103 InetAddress localHost = InetAddress.getLocalHost(); 104 BigInteger bigIP = new BigInteger (localHost.getAddress()); 105 106 return normalize(bigIP.longValue()); 107 } 108 catch (UnknownHostException uhex) { 109 return 0; 110 } 111 } 112 113 121 122 private final static long normalize(long value) { 123 if (value > 0) return value; 124 125 if (value == Long.MIN_VALUE) 126 return Long.MAX_VALUE; 127 else 128 return value * -1; 129 } 130 131 139 140 private final static String createString(long value) { 141 String baseString = Long.toString(value, 36); 142 String result = ZEROS.substring(0, ZEROSLENGTH - baseString.length()) + baseString; 143 144 return result; 145 } 146 } 147 148 149 | Popular Tags |