| UUID.java |
1 /*
2 * %W% %E%
3 *
4 * Copyright (c) 2006, Oracle and/or its affiliates. All rights reserved.
5 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
6 */
7
8 package java.util;
9
10 import java.security.*;
11 import java.io.IOException;
12 import java.io.UnsupportedEncodingException;
13
14 /**
15 *
16 * A class that represents an immutable universally unique identifier (UUID).
17 * A UUID represents a 128-bit value.
18 *
19 * <p>There exist different variants of these global identifiers. The methods
20 * of this class are for manipulating the Leach-Salz variant, although the
21 * constructors allow the creation of any variant of UUID (described below).
22 *
23 * <p>The layout of a variant 2 (Leach-Salz) UUID is as follows:
24 *
25 * The most significant long consists of the following unsigned fields:
26 * <pre>
27 * 0xFFFFFFFF00000000 time_low
28 * 0x00000000FFFF0000 time_mid
29 * 0x000000000000F000 version
30 * 0x0000000000000FFF time_hi
31 * </pre>
32 * The least significant long consists of the following unsigned fields:
33 * <pre>
34 * 0xC000000000000000 variant
35 * 0x3FFF000000000000 clock_seq
36 * 0x0000FFFFFFFFFFFF node
37 * </pre>
38 *
39 * <p>The variant field contains a value which identifies the layout of
40 * the <tt>UUID</tt>. The bit layout described above is valid only for
41 * a <tt>UUID</tt> with a variant value of 2, which indicates the
42 * Leach-Salz variant.
43 *
44 * <p>The version field holds a value that describes the type of this
45 * <tt>UUID</tt>. There are four different basic types of UUIDs: time-based,
46 * DCE security, name-based, and randomly generated UUIDs. These types
47 * have a version value of 1, 2, 3 and 4, respectively.
48 *
49 * <p>For more information including algorithms used to create <tt>UUID</tt>s,
50 * see <a href="http://www.ietf.org/rfc/rfc4122.txt">
51 * <i>RFC 4122: A Universally Unique IDentifier (UUID) URN
52 * Namespace</i></a>, section 4.2 "Algorithms for Creating a Time-Based
53 * UUID".
54 *
55 * @version %I%, %G%
56 * @since 1.5
57 */
58 public final class UUID
59 implements java.io.Serializable, Comparable<UUID> {
60
61 /**
62 * Explicit serialVersionUID for interoperability.
63 */
64 private static final long serialVersionUID = -4856846361193249489L;
65
66 /*
67 * The most significant 64 bits of this UUID.
68 *
69 * @serial
70 */
71 private final long mostSigBits;
72
73 /*
74 * The least significant 64 bits of this UUID.
75 *
76 * @serial
77 */
78 private final long leastSigBits;
79
80 /*
81 * The version number associated with this UUID. Computed on demand.
82 */
83 private transient int version = -1;
84
85 /*
86 * The variant number associated with this UUID. Computed on demand.
87 */
88 private transient int variant = -1;
89
90 /*
91 * The timestamp associated with this UUID. Computed on demand.
92 */
93 private transient volatile long timestamp = -1;
94
95 /*
96 * The clock sequence associated with this UUID. Computed on demand.
97 */
98 private transient int sequence = -1;
99
100 /*
101 * The node number associated with this UUID. Computed on demand.
102 */
103 private transient long node = -1;
104
105 /*
106 * The hashcode of this UUID. Computed on demand.
107 */
108 private transient int hashCode = -1;
109
110 /*
111 * The random number generator used by this class to create random
112 * based UUIDs.
113 */
114 private static volatile SecureRandom numberGenerator = null;
115
116 // Constructors and Factories
117
118 /*
119 * Private constructor which uses a byte array to construct the new UUID.
120 */
121 private UUID(byte[] data) {
122 long msb = 0;
123 long lsb = 0;
124 assert data.length == 16;
125 for (int i=0; i<8; i++)
126 msb = (msb << 8) | (data[i] & 0xff);
127 for (int i=8; i<16; i++)
128 lsb = (lsb << 8) | (data[i] & 0xff);
129 this.mostSigBits = msb;
130 this.leastSigBits = lsb;
131 }
132
133 /**
134 * Constructs a new <tt>UUID</tt> using the specified data.
135 * <tt>mostSigBits</tt> is used for the most significant 64 bits
136 * of the <tt>UUID</tt> and <tt>leastSigBits</tt> becomes the
137 * least significant 64 bits of the <tt>UUID</tt>.
138 *
139 * @param mostSigBits
140 * @param leastSigBits
141 */
142 public UUID(long mostSigBits, long leastSigBits) {
143 this.mostSigBits = mostSigBits;
144 this.leastSigBits = leastSigBits;
145 }
146
147 /**
148 * Static factory to retrieve a type 4 (pseudo randomly generated) UUID.
149 *
150 * The <code>UUID</code> is generated using a cryptographically strong
151 * pseudo random number generator.
152 *
153 * @return a randomly generated <tt>UUID</tt>.
154 */
155 public static UUID randomUUID() {
156 SecureRandom ng = numberGenerator;
157 if (ng == null) {
158 numberGenerator = ng = new SecureRandom();
159 }
160
161 byte[] randomBytes = new byte[16];
162 ng.nextBytes(randomBytes);
163 randomBytes[6] &= 0x0f; /* clear version */
164 randomBytes[6] |= 0x40; /* set to version 4 */
165 randomBytes[8] &= 0x3f; /* clear variant */
166 randomBytes[8] |= 0x80; /* set to IETF variant */
167 return new UUID(randomBytes);
168 }
169
170 /**
171 * Static factory to retrieve a type 3 (name based) <tt>UUID</tt> based on
172 * the specified byte array.
173 *
174 * @param name a byte array to be used to construct a <tt>UUID</tt>.
175 * @return a <tt>UUID</tt> generated from the specified array.
176 */
177 public static UUID nameUUIDFromBytes(byte[] name) {
178 MessageDigest md;
179 try {
180 md = MessageDigest.getInstance("MD5");
181 } catch (NoSuchAlgorithmException nsae) {
182 throw new InternalError("MD5 not supported");
183 }
184 byte[] md5Bytes = md.digest(name);
185 md5Bytes[6] &= 0x0f; /* clear version */
186 md5Bytes[6] |= 0x30; /* set to version 3 */
187 md5Bytes[8] &= 0x3f; /* clear variant */
188 md5Bytes[8] |= 0x80; /* set to IETF variant */
189 return new UUID(md5Bytes);
190 }
191
192 /**
193 * Creates a <tt>UUID</tt> from the string standard representation as
194 * described in the {@link #toString} method.
195 *
196 * @param name a string that specifies a <tt>UUID</tt>.
197 * @return a <tt>UUID</tt> with the specified value.
198 * @throws IllegalArgumentException if name does not conform to the
199 * string representation as described in {@link #toString}.
200 */
201 public static UUID fromString(String name) {
202 String[] components = name.split("-");
203 if (components.length != 5)
204 throw new IllegalArgumentException("Invalid UUID string: "+name);
205 for (int i=0; i<5; i++)
206 components[i] = "0x"+components[i];
207
208 long mostSigBits = Long.decode(components[0]).longValue();
209 mostSigBits <<= 16;
210 mostSigBits |= Long.decode(components[1]).longValue();
211 mostSigBits <<= 16;
212 mostSigBits |= Long.decode(components[2]).longValue();
213
214 long leastSigBits = Long.decode(components[3]).longValue();
215 leastSigBits <<= 48;
216 leastSigBits |= Long.decode(components[4]).longValue();
217
218 return new UUID(mostSigBits, leastSigBits);
219 }
220
221 // Field Accessor Methods
222
223 /**
224 * Returns the least significant 64 bits of this UUID's 128 bit value.
225 *
226 * @return the least significant 64 bits of this UUID's 128 bit value.
227 */
228 public long getLeastSignificantBits() {
229 return leastSigBits;
230 }
231
232 /**
233 * Returns the most significant 64 bits of this UUID's 128 bit value.
234 *
235 * @return the most significant 64 bits of this UUID's 128 bit value.
236 */
237 public long getMostSignificantBits() {
238 return mostSigBits;
239 }
240
241 /**
242 * The version number associated with this <tt>UUID</tt>. The version
243 * number describes how this <tt>UUID</tt> was generated.
244 *
245 * The version number has the following meaning:<p>
246 * <ul>
247 * <li>1 Time-based UUID
248 * <li>2 DCE security UUID
249 * <li>3 Name-based UUID
250 * <li>4 Randomly generated UUID
251 * </ul>
252 *
253 * @return the version number of this <tt>UUID</tt>.
254 */
255 public int version() {
256 if (version < 0) {
257 // Version is bits masked by 0x000000000000F000 in MS long
258 version = (int)((mostSigBits >> 12) & 0x0f);
259 }
260 return version;
261 }
262
263 /**
264 * The variant number associated with this <tt>UUID</tt>. The variant
265 * number describes the layout of the <tt>UUID</tt>.
266 *
267 * The variant number has the following meaning:<p>
268 * <ul>
269 * <li>0 Reserved for NCS backward compatibility
270 * <li>2 The Leach-Salz variant (used by this class)
271 * <li>6 Reserved, Microsoft Corporation backward compatibility
272 * <li>7 Reserved for future definition
273 * </ul>
274 *
275 * @return the variant number of this <tt>UUID</tt>.
276 */
277 public int variant() {
278 if (variant < 0) {
279 // This field is composed of a varying number of bits
280 if ((leastSigBits >>> 63) == 0) {
281 variant = 0;
282 } else if ((leastSigBits >>> 62) == 2) {
283 variant = 2;
284 } else {
285 variant = (int)(leastSigBits >>> 61);
286 }
287 }
288 return variant;
289 }
290
291 /**
292 * The timestamp value associated with this UUID.
293 *
294 * <p>The 60 bit timestamp value is constructed from the time_low,
295 * time_mid, and time_hi fields of this <tt>UUID</tt>. The resulting
296 * timestamp is measured in 100-nanosecond units since midnight,
297 * October 15, 1582 UTC.<p>
298 *
299 * The timestamp value is only meaningful in a time-based UUID, which
300 * has version type 1. If this <tt>UUID</tt> is not a time-based UUID then
301 * this method throws UnsupportedOperationException.
302 *
303 * @throws UnsupportedOperationException if this UUID is not a
304 * version 1 UUID.
305 */
306 public long timestamp() {
307 if (version() != 1) {
308 throw new UnsupportedOperationException("Not a time-based UUID");
309 }
310 long result = timestamp;
311 if (result < 0) {
312 result = (mostSigBits & 0x0000000000000FFFL) << 48;
313 result |= ((mostSigBits >> 16) & 0xFFFFL) << 32;
314 result |= mostSigBits >>> 32;
315 timestamp = result;
316 }
317 return result;
318 }
319
320 /**
321 * The clock sequence value associated with this UUID.
322 *
323 * <p>The 14 bit clock sequence value is constructed from the clock
324 * sequence field of this UUID. The clock sequence field is used to
325 * guarantee temporal uniqueness in a time-based UUID.<p>
326 *
327 * The clockSequence value is only meaningful in a time-based UUID, which
328 * has version type 1. If this UUID is not a time-based UUID then
329 * this method throws UnsupportedOperationException.
330 *
331 * @return the clock sequence of this <tt>UUID</tt>.
332 * @throws UnsupportedOperationException if this UUID is not a
333 * version 1 UUID.
334 */
335 public int clockSequence() {
336 if (version() != 1) {
337 throw new UnsupportedOperationException("Not a time-based UUID");
338 }
339 if (sequence < 0) {
340 sequence = (int)((leastSigBits & 0x3FFF000000000000L) >>> 48);
341 }
342 return sequence;
343 }
344
345 /**
346 * The node value associated with this UUID.
347 *
348 * <p>The 48 bit node value is constructed from the node field of
349 * this UUID. This field is intended to hold the IEEE 802 address
350 * of the machine that generated this UUID to guarantee spatial
351 * uniqueness.<p>
352 *
353 * The node value is only meaningful in a time-based UUID, which
354 * has version type 1. If this UUID is not a time-based UUID then
355 * this method throws UnsupportedOperationException.
356 *
357 * @return the node value of this <tt>UUID</tt>.
358 * @throws UnsupportedOperationException if this UUID is not a
359 * version 1 UUID.
360 */
361 public long node() {
362 if (version() != 1) {
363 throw new UnsupportedOperationException("Not a time-based UUID");
364 }
365 if (node < 0) {
366 node = leastSigBits & 0x0000FFFFFFFFFFFFL;
367 }
368 return node;
369 }
370
371 // Object Inherited Methods
372
373 /**
374 * Returns a <code>String</code> object representing this
375 * <code>UUID</code>.
376 *
377 * <p>The UUID string representation is as described by this BNF :
378 * <blockquote><pre>
379 * {@code
380 * UUID = <time_low> "-" <time_mid> "-"
381 * <time_high_and_version> "-"
382 * <variant_and_sequence> "-"
383 * <node>
384 * time_low = 4*<hexOctet>
385 * time_mid = 2*<hexOctet>
386 * time_high_and_version = 2*<hexOctet>
387 * variant_and_sequence = 2*<hexOctet>
388 * node = 6*<hexOctet>
389 * hexOctet = <hexDigit><hexDigit>
390 * hexDigit =
391 * "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9"
392 * | "a" | "b" | "c" | "d" | "e" | "f"
393 * | "A" | "B" | "C" | "D" | "E" | "F"
394 * }</pre></blockquote>
395 *
396 * @return a string representation of this <tt>UUID</tt>.
397 */
398 public String toString() {
399 return (digits(mostSigBits >> 32, 8) + "-" +
400 digits(mostSigBits >> 16, 4) + "-" +
401 digits(mostSigBits, 4) + "-" +
402 digits(leastSigBits >> 48, 4) + "-" +
403 digits(leastSigBits, 12));
404 }
405
406 /** Returns val represented by the specified number of hex digits. */
407 private static String digits(long val, int digits) {
408 long hi = 1L << (digits * 4);
409 return Long.toHexString(hi | (val & (hi - 1))).substring(1);
410 }
411
412 /**
413 * Returns a hash code for this <code>UUID</code>.
414 *
415 * @return a hash code value for this <tt>UUID</tt>.
416 */
417 public int hashCode() {
418 if (hashCode == -1) {
419 hashCode = (int)((mostSigBits >> 32) ^
420 mostSigBits ^
421 (leastSigBits >> 32) ^
422 leastSigBits);
423 }
424 return hashCode;
425 }
426
427 /**
428 * Compares this object to the specified object. The result is
429 * <tt>true</tt> if and only if the argument is not
430 * <tt>null</tt>, is a <tt>UUID</tt> object, has the same variant,
431 * and contains the same value, bit for bit, as this <tt>UUID</tt>.
432 *
433 * @param obj the object to compare with.
434 * @return <code>true</code> if the objects are the same;
435 * <code>false</code> otherwise.
436 */
437 public boolean equals(Object obj) {
438 if (!(obj instanceof UUID))
439 return false;
440 if (((UUID)obj).variant() != this.variant())
441 return false;
442 UUID id = (UUID)obj;
443 return (mostSigBits == id.mostSigBits &&
444 leastSigBits == id.leastSigBits);
445 }
446
447 // Comparison Operations
448
449 /**
450 * Compares this UUID with the specified UUID.
451 *
452 * <p>The first of two UUIDs follows the second if the most significant
453 * field in which the UUIDs differ is greater for the first UUID.
454 *
455 * @param val <tt>UUID</tt> to which this <tt>UUID</tt> is to be compared.
456 * @return -1, 0 or 1 as this <tt>UUID</tt> is less than, equal
457 * to, or greater than <tt>val</tt>.
458 */
459 public int compareTo(UUID val) {
460 // The ordering is intentionally set up so that the UUIDs
461 // can simply be numerically compared as two numbers
462 return (this.mostSigBits < val.mostSigBits ? -1 :
463 (this.mostSigBits > val.mostSigBits ? 1 :
464 (this.leastSigBits < val.leastSigBits ? -1 :
465 (this.leastSigBits > val.leastSigBits ? 1 :
466 0))));
467 }
468
469 /**
470 * Reconstitute the <tt>UUID</tt> instance from a stream (that is,
471 * deserialize it). This is necessary to set the transient fields
472 * to their correct uninitialized value so they will be recomputed
473 * on demand.
474 */
475 private void readObject(java.io.ObjectInputStream in)
476 throws java.io.IOException, ClassNotFoundException {
477
478 in.defaultReadObject();
479
480 // Set "cached computation" fields to their initial values
481 version = -1;
482 variant = -1;
483 timestamp = -1;
484 sequence = -1;
485 node = -1;
486 hashCode = -1;
487 }
488 }
489