1 56 package org.objectstyle.cayenne.util; 57 58 import java.net.UnknownHostException ; 59 import java.security.MessageDigest ; 60 import java.security.NoSuchAlgorithmException ; 61 62 import org.objectstyle.cayenne.CayenneRuntimeException; 63 64 69 public class IDUtil { 70 71 private static volatile long currentId = Long.MIN_VALUE; 72 private static MessageDigest md; 73 private static byte[] ipAddress; 74 75 static { 76 try { 77 md = MessageDigest.getInstance("MD5"); 78 } catch (NoSuchAlgorithmException e) { 79 throw new CayenneRuntimeException("Can't initialize MessageDigest.", e); 80 } 81 82 try { 83 ipAddress = java.net.InetAddress.getLocalHost().getAddress(); 84 } catch (UnknownHostException e) { 85 ipAddress = new byte[] { 127, 0, 0, 1 }; 87 } 88 } 89 90 98 public synchronized static byte[] pseudoUniqueByteSequence(int length) { 99 if (length < 16) { 100 throw new IllegalArgumentException ( 101 "Can't generate unique byte sequence shorter than 16 bytes: " + length); 102 } 103 104 if (length == 16) { 105 return pseudoUniqueByteSequence16(); 106 } 107 108 byte[] bytes = new byte[length]; 109 for (int i = 0; i <= length - 16; i += 16) { 110 byte[] nextSequence = pseudoUniqueByteSequence16(); 111 System.arraycopy(nextSequence, 0, bytes, i, 16); 112 } 113 114 int leftoverLen = length % 16; 116 if (leftoverLen > 0) { 117 byte[] nextSequence = pseudoUniqueByteSequence16(); 118 System.arraycopy(nextSequence, 0, bytes, length - leftoverLen, leftoverLen); 119 } 120 121 return bytes; 122 } 123 124 127 public static byte[] pseudoUniqueByteSequence16() { 128 byte[] bytes = new byte[20]; 129 130 appendLongBytes(bytes, 0, System.currentTimeMillis()); 131 appendLongBytes(bytes, 8, currentId++); 132 System.arraycopy(ipAddress, 0, bytes, 16, ipAddress.length); 133 134 try { 136 Thread.sleep(2); 137 } catch (InterruptedException e) { 138 } 140 141 return md.digest(bytes); 142 } 143 144 145 private static void appendLongBytes(byte[] bytes, int offset, long value) { 146 for (int i = 0; i < 8; ++i) { 147 int off = (7 - i) * 8; 148 bytes[i + offset] = (byte) ((value & (0xff << off)) >>> off); 149 } 150 } 151 152 private IDUtil() { 153 } 154 155 } 156 | Popular Tags |