admin
3 天以前 768498719683f85e5ed19c73eb3d14cdbf420df4
提交 | 用户 | 时间
e57a89 1 package com.jcdm.common.utils.uuid;
2
3 import java.security.MessageDigest;
4 import java.security.NoSuchAlgorithmException;
5 import java.security.SecureRandom;
6 import java.util.Random;
7 import java.util.concurrent.ThreadLocalRandom;
8 import com.jcdm.common.exception.UtilException;
9
10 /**
11  * 提供通用唯一识别码(universally unique identifier)(UUID)实现
12  *
13  * @author jc
14  */
15 public final class UUID implements java.io.Serializable, Comparable<UUID>
16 {
17     private static final long serialVersionUID = -1185015143654744140L;
18
19     /**
20      * SecureRandom 的单例
21      *
22      */
23     private static class Holder
24     {
25         static final SecureRandom numberGenerator = getSecureRandom();
26     }
27
28     /** 此UUID的最高64有效位 */
29     private final long mostSigBits;
30
31     /** 此UUID的最低64有效位 */
32     private final long leastSigBits;
33
34     /**
35      * 私有构造
36      * 
37      * @param data 数据
38      */
39     private UUID(byte[] data)
40     {
41         long msb = 0;
42         long lsb = 0;
43         assert data.length == 16 : "data must be 16 bytes in length";
44         for (int i = 0; i < 8; i++)
45         {
46             msb = (msb << 8) | (data[i] & 0xff);
47         }
48         for (int i = 8; i < 16; i++)
49         {
50             lsb = (lsb << 8) | (data[i] & 0xff);
51         }
52         this.mostSigBits = msb;
53         this.leastSigBits = lsb;
54     }
55
56     /**
57      * 使用指定的数据构造新的 UUID。
58      *
59      * @param mostSigBits 用于 {@code UUID} 的最高有效 64 位
60      * @param leastSigBits 用于 {@code UUID} 的最低有效 64 位
61      */
62     public UUID(long mostSigBits, long leastSigBits)
63     {
64         this.mostSigBits = mostSigBits;
65         this.leastSigBits = leastSigBits;
66     }
67
68     /**
69      * 获取类型 4(伪随机生成的)UUID 的静态工厂。
70      * 
71      * @return 随机生成的 {@code UUID}
72      */
73     public static UUID fastUUID()
74     {
75         return randomUUID(false);
76     }
77
78     /**
79      * 获取类型 4(伪随机生成的)UUID 的静态工厂。 使用加密的强伪随机数生成器生成该 UUID。
80      * 
81      * @return 随机生成的 {@code UUID}
82      */
83     public static UUID randomUUID()
84     {
85         return randomUUID(true);
86     }
87
88     /**
89      * 获取类型 4(伪随机生成的)UUID 的静态工厂。 使用加密的强伪随机数生成器生成该 UUID。
90      * 
91      * @param isSecure 是否使用{@link SecureRandom}如果是可以获得更安全的随机码,否则可以得到更好的性能
92      * @return 随机生成的 {@code UUID}
93      */
94     public static UUID randomUUID(boolean isSecure)
95     {
96         final Random ng = isSecure ? Holder.numberGenerator : getRandom();
97
98         byte[] randomBytes = new byte[16];
99         ng.nextBytes(randomBytes);
100         randomBytes[6] &= 0x0f; /* clear version */
101         randomBytes[6] |= 0x40; /* set to version 4 */
102         randomBytes[8] &= 0x3f; /* clear variant */
103         randomBytes[8] |= 0x80; /* set to IETF variant */
104         return new UUID(randomBytes);
105     }
106
107     /**
108      * 根据指定的字节数组获取类型 3(基于名称的)UUID 的静态工厂。
109      *
110      * @param name 用于构造 UUID 的字节数组。
111      *
112      * @return 根据指定数组生成的 {@code UUID}
113      */
114     public static UUID nameUUIDFromBytes(byte[] name)
115     {
116         MessageDigest md;
117         try
118         {
119             md = MessageDigest.getInstance("MD5");
120         }
121         catch (NoSuchAlgorithmException nsae)
122         {
123             throw new InternalError("MD5 not supported");
124         }
125         byte[] md5Bytes = md.digest(name);
126         md5Bytes[6] &= 0x0f; /* clear version */
127         md5Bytes[6] |= 0x30; /* set to version 3 */
128         md5Bytes[8] &= 0x3f; /* clear variant */
129         md5Bytes[8] |= 0x80; /* set to IETF variant */
130         return new UUID(md5Bytes);
131     }
132
133     /**
134      * 根据 {@link #toString()} 方法中描述的字符串标准表示形式创建{@code UUID}。
135      *
136      * @param name 指定 {@code UUID} 字符串
137      * @return 具有指定值的 {@code UUID}
138      * @throws IllegalArgumentException 如果 name 与 {@link #toString} 中描述的字符串表示形式不符抛出此异常
139      *
140      */
141     public static UUID fromString(String name)
142     {
143         String[] components = name.split("-");
144         if (components.length != 5)
145         {
146             throw new IllegalArgumentException("Invalid UUID string: " + name);
147         }
148         for (int i = 0; i < 5; i++)
149         {
150             components[i] = "0x" + components[i];
151         }
152
153         long mostSigBits = Long.decode(components[0]).longValue();
154         mostSigBits <<= 16;
155         mostSigBits |= Long.decode(components[1]).longValue();
156         mostSigBits <<= 16;
157         mostSigBits |= Long.decode(components[2]).longValue();
158
159         long leastSigBits = Long.decode(components[3]).longValue();
160         leastSigBits <<= 48;
161         leastSigBits |= Long.decode(components[4]).longValue();
162
163         return new UUID(mostSigBits, leastSigBits);
164     }
165
166     /**
167      * 返回此 UUID 的 128 位值中的最低有效 64 位。
168      *
169      * @return 此 UUID 的 128 位值中的最低有效 64 位。
170      */
171     public long getLeastSignificantBits()
172     {
173         return leastSigBits;
174     }
175
176     /**
177      * 返回此 UUID 的 128 位值中的最高有效 64 位。
178      *
179      * @return 此 UUID 的 128 位值中最高有效 64 位。
180      */
181     public long getMostSignificantBits()
182     {
183         return mostSigBits;
184     }
185
186     /**
187      * 与此 {@code UUID} 相关联的版本号. 版本号描述此 {@code UUID} 是如何生成的。
188      * <p>
189      * 版本号具有以下含意:
190      * <ul>
191      * <li>1 基于时间的 UUID
192      * <li>2 DCE 安全 UUID
193      * <li>3 基于名称的 UUID
194      * <li>4 随机生成的 UUID
195      * </ul>
196      *
197      * @return 此 {@code UUID} 的版本号
198      */
199     public int version()
200     {
201         // Version is bits masked by 0x000000000000F000 in MS long
202         return (int) ((mostSigBits >> 12) & 0x0f);
203     }
204
205     /**
206      * 与此 {@code UUID} 相关联的变体号。变体号描述 {@code UUID} 的布局。
207      * <p>
208      * 变体号具有以下含意:
209      * <ul>
210      * <li>0 为 NCS 向后兼容保留
211      * <li>2 <a href="http://www.ietf.org/rfc/rfc4122.txt">IETF&nbsp;RFC&nbsp;4122</a>(Leach-Salz), 用于此类
212      * <li>6 保留,微软向后兼容
213      * <li>7 保留供以后定义使用
214      * </ul>
215      *
216      * @return 此 {@code UUID} 相关联的变体号
217      */
218     public int variant()
219     {
220         // This field is composed of a varying number of bits.
221         // 0 - - Reserved for NCS backward compatibility
222         // 1 0 - The IETF aka Leach-Salz variant (used by this class)
223         // 1 1 0 Reserved, Microsoft backward compatibility
224         // 1 1 1 Reserved for future definition.
225         return (int) ((leastSigBits >>> (64 - (leastSigBits >>> 62))) & (leastSigBits >> 63));
226     }
227
228     /**
229      * 与此 UUID 相关联的时间戳值。
230      *
231      * <p>
232      * 60 位的时间戳值根据此 {@code UUID} 的 time_low、time_mid 和 time_hi 字段构造。<br>
233      * 所得到的时间戳以 100 毫微秒为单位,从 UTC(通用协调时间) 1582 年 10 月 15 日零时开始。
234      *
235      * <p>
236      * 时间戳值仅在在基于时间的 UUID(其 version 类型为 1)中才有意义。<br>
237      * 如果此 {@code UUID} 不是基于时间的 UUID,则此方法抛出 UnsupportedOperationException。
238      *
239      * @throws UnsupportedOperationException 如果此 {@code UUID} 不是 version 为 1 的 UUID。
240      */
241     public long timestamp() throws UnsupportedOperationException
242     {
243         checkTimeBase();
244         return (mostSigBits & 0x0FFFL) << 48//
245                 | ((mostSigBits >> 16) & 0x0FFFFL) << 32//
246                 | mostSigBits >>> 32;
247     }
248
249     /**
250      * 与此 UUID 相关联的时钟序列值。
251      *
252      * <p>
253      * 14 位的时钟序列值根据此 UUID 的 clock_seq 字段构造。clock_seq 字段用于保证在基于时间的 UUID 中的时间唯一性。
254      * <p>
255      * {@code clockSequence} 值仅在基于时间的 UUID(其 version 类型为 1)中才有意义。 如果此 UUID 不是基于时间的 UUID,则此方法抛出
256      * UnsupportedOperationException。
257      *
258      * @return 此 {@code UUID} 的时钟序列
259      *
260      * @throws UnsupportedOperationException 如果此 UUID 的 version 不为 1
261      */
262     public int clockSequence() throws UnsupportedOperationException
263     {
264         checkTimeBase();
265         return (int) ((leastSigBits & 0x3FFF000000000000L) >>> 48);
266     }
267
268     /**
269      * 与此 UUID 相关的节点值。
270      *
271      * <p>
272      * 48 位的节点值根据此 UUID 的 node 字段构造。此字段旨在用于保存机器的 IEEE 802 地址,该地址用于生成此 UUID 以保证空间唯一性。
273      * <p>
274      * 节点值仅在基于时间的 UUID(其 version 类型为 1)中才有意义。<br>
275      * 如果此 UUID 不是基于时间的 UUID,则此方法抛出 UnsupportedOperationException。
276      *
277      * @return 此 {@code UUID} 的节点值
278      *
279      * @throws UnsupportedOperationException 如果此 UUID 的 version 不为 1
280      */
281     public long node() throws UnsupportedOperationException
282     {
283         checkTimeBase();
284         return leastSigBits & 0x0000FFFFFFFFFFFFL;
285     }
286
287     /**
288      * 返回此{@code UUID} 的字符串表现形式。
289      *
290      * <p>
291      * UUID 的字符串表示形式由此 BNF 描述:
292      * 
293      * <pre>
294      * {@code
295      * UUID                   = <time_low>-<time_mid>-<time_high_and_version>-<variant_and_sequence>-<node>
296      * time_low               = 4*<hexOctet>
297      * time_mid               = 2*<hexOctet>
298      * time_high_and_version  = 2*<hexOctet>
299      * variant_and_sequence   = 2*<hexOctet>
300      * node                   = 6*<hexOctet>
301      * hexOctet               = <hexDigit><hexDigit>
302      * hexDigit               = [0-9a-fA-F]
303      * }
304      * </pre>
305      * 
306      * </blockquote>
307      *
308      * @return 此{@code UUID} 的字符串表现形式
309      * @see #toString(boolean)
310      */
311     @Override
312     public String toString()
313     {
314         return toString(false);
315     }
316
317     /**
318      * 返回此{@code UUID} 的字符串表现形式。
319      *
320      * <p>
321      * UUID 的字符串表示形式由此 BNF 描述:
322      * 
323      * <pre>
324      * {@code
325      * UUID                   = <time_low>-<time_mid>-<time_high_and_version>-<variant_and_sequence>-<node>
326      * time_low               = 4*<hexOctet>
327      * time_mid               = 2*<hexOctet>
328      * time_high_and_version  = 2*<hexOctet>
329      * variant_and_sequence   = 2*<hexOctet>
330      * node                   = 6*<hexOctet>
331      * hexOctet               = <hexDigit><hexDigit>
332      * hexDigit               = [0-9a-fA-F]
333      * }
334      * </pre>
335      * 
336      * </blockquote>
337      *
338      * @param isSimple 是否简单模式,简单模式为不带'-'的UUID字符串
339      * @return 此{@code UUID} 的字符串表现形式
340      */
341     public String toString(boolean isSimple)
342     {
343         final StringBuilder builder = new StringBuilder(isSimple ? 32 : 36);
344         // time_low
345         builder.append(digits(mostSigBits >> 32, 8));
346         if (!isSimple)
347         {
348             builder.append('-');
349         }
350         // time_mid
351         builder.append(digits(mostSigBits >> 16, 4));
352         if (!isSimple)
353         {
354             builder.append('-');
355         }
356         // time_high_and_version
357         builder.append(digits(mostSigBits, 4));
358         if (!isSimple)
359         {
360             builder.append('-');
361         }
362         // variant_and_sequence
363         builder.append(digits(leastSigBits >> 48, 4));
364         if (!isSimple)
365         {
366             builder.append('-');
367         }
368         // node
369         builder.append(digits(leastSigBits, 12));
370
371         return builder.toString();
372     }
373
374     /**
375      * 返回此 UUID 的哈希码。
376      *
377      * @return UUID 的哈希码值。
378      */
379     @Override
380     public int hashCode()
381     {
382         long hilo = mostSigBits ^ leastSigBits;
383         return ((int) (hilo >> 32)) ^ (int) hilo;
384     }
385
386     /**
387      * 将此对象与指定对象比较。
388      * <p>
389      * 当且仅当参数不为 {@code null}、而是一个 UUID 对象、具有与此 UUID 相同的 varriant、包含相同的值(每一位均相同)时,结果才为 {@code true}。
390      *
391      * @param obj 要与之比较的对象
392      *
393      * @return 如果对象相同,则返回 {@code true};否则返回 {@code false}
394      */
395     @Override
396     public boolean equals(Object obj)
397     {
398         if ((null == obj) || (obj.getClass() != UUID.class))
399         {
400             return false;
401         }
402         UUID id = (UUID) obj;
403         return (mostSigBits == id.mostSigBits && leastSigBits == id.leastSigBits);
404     }
405
406     // Comparison Operations
407
408     /**
409      * 将此 UUID 与指定的 UUID 比较。
410      *
411      * <p>
412      * 如果两个 UUID 不同,且第一个 UUID 的最高有效字段大于第二个 UUID 的对应字段,则第一个 UUID 大于第二个 UUID。
413      *
414      * @param val 与此 UUID 比较的 UUID
415      *
416      * @return 在此 UUID 小于、等于或大于 val 时,分别返回 -1、0 或 1。
417      *
418      */
419     @Override
420     public int compareTo(UUID val)
421     {
422         // The ordering is intentionally set up so that the UUIDs
423         // can simply be numerically compared as two numbers
424         return (this.mostSigBits < val.mostSigBits ? -1 : //
425                 (this.mostSigBits > val.mostSigBits ? 1 : //
426                         (this.leastSigBits < val.leastSigBits ? -1 : //
427                                 (this.leastSigBits > val.leastSigBits ? 1 : //
428                                         0))));
429     }
430
431     // -------------------------------------------------------------------------------------------------------------------
432     // Private method start
433     /**
434      * 返回指定数字对应的hex值
435      * 
436      * @param val 值
437      * @param digits 位
438      * @return 值
439      */
440     private static String digits(long val, int digits)
441     {
442         long hi = 1L << (digits * 4);
443         return Long.toHexString(hi | (val & (hi - 1))).substring(1);
444     }
445
446     /**
447      * 检查是否为time-based版本UUID
448      */
449     private void checkTimeBase()
450     {
451         if (version() != 1)
452         {
453             throw new UnsupportedOperationException("Not a time-based UUID");
454         }
455     }
456
457     /**
458      * 获取{@link SecureRandom},类提供加密的强随机数生成器 (RNG)
459      * 
460      * @return {@link SecureRandom}
461      */
462     public static SecureRandom getSecureRandom()
463     {
464         try
465         {
466             return SecureRandom.getInstance("SHA1PRNG");
467         }
468         catch (NoSuchAlgorithmException e)
469         {
470             throw new UtilException(e);
471         }
472     }
473
474     /**
475      * 获取随机数生成器对象<br>
476      * ThreadLocalRandom是JDK 7之后提供并发产生随机数,能够解决多个线程发生的竞争争夺。
477      * 
478      * @return {@link ThreadLocalRandom}
479      */
480     public static ThreadLocalRandom getRandom()
481     {
482         return ThreadLocalRandom.current();
483     }
484 }