1 21 24 package org.lobobrowser.util; 25 26 import java.util.*; 27 import java.util.logging.*; 28 import java.security.*; 29 import java.math.*; 30 import java.net.InetAddress ; 31 32 35 public class ID { 36 private static final Random RANDOM1; 37 private static final Random RANDOM2; 38 private static final Random RANDOM3; 39 private static final long globalProcessID; 40 private static final Logger logger = Logger.getLogger(ID.class.getName()); 41 42 static { 43 long time = System.currentTimeMillis(); 44 long nanoTime = System.nanoTime(); 45 long freeMemory = Runtime.getRuntime().freeMemory(); 46 long addressHashCode; 47 try { 48 InetAddress inetAddress; 49 inetAddress = InetAddress.getLocalHost(); 50 addressHashCode = inetAddress.getHostName().hashCode() ^ inetAddress.getHostAddress().hashCode(); 51 } catch(Exception err) { 52 logger.log(Level.WARNING, "Unable to get local host information.", err); 53 addressHashCode = ID.class.hashCode(); 54 } 55 globalProcessID = time ^ nanoTime ^ freeMemory ^ addressHashCode; 56 RANDOM1 = new Random(time); 57 RANDOM2 = new Random(nanoTime); 58 RANDOM3 = new Random(addressHashCode ^ freeMemory); 59 } 60 61 private ID() { 62 } 63 64 public static long generateLong() { 65 return Math.abs(RANDOM1.nextLong() ^ RANDOM2.nextLong() ^ RANDOM3.nextLong()); 66 } 67 68 public static int generateInt() { 69 return (int) generateLong(); 70 } 71 72 public static byte[] getMD5Bytes(String content) { 73 try { 74 MessageDigest digest = MessageDigest.getInstance("MD5"); 75 return digest.digest(content.getBytes("UTF-8")); 76 } catch (NoSuchAlgorithmException e) { 77 throw new IllegalStateException (e); 78 } catch(java.io.UnsupportedEncodingException uee) { 79 throw new IllegalStateException (uee); 80 } 81 } 82 83 public static String getHexString(byte[] bytes) { 84 BigInteger bigInteger = BigInteger.ZERO; 86 int shift = 0; 87 for(int i = bytes.length; --i >= 0;) { 88 BigInteger contrib = BigInteger.valueOf(bytes[i] & 0xFF); 89 contrib = contrib.shiftLeft(shift); 90 bigInteger = bigInteger.add(contrib); 91 shift += 8; 92 } 93 return bigInteger.toString(16).toUpperCase(); 94 } 95 96 99 public static long getGlobalProcessID() { 100 return globalProcessID; 101 } 102 103 public static int random(int min, int max) { 104 if(max <= min) { 105 return min; 106 } 107 return Math.abs(RANDOM1.nextInt()) % (max - min) + min; 108 } 109 } 110 | Popular Tags |