KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > mr > core > util > UUID


1 /*
2  * Copyright 2002 by
3  * <a HREF="http://www.coridan.com">Coridan</a>
4  * <a HREF="mailto: support@coridan.com ">support@coridan.com</a>
5  *
6  * The contents of this file are subject to the Mozilla Public License Version
7  * 1.1 (the "License"); you may not use this file except in compliance with the
8  * License. You may obtain a copy of the License at
9  * http://www.mozilla.org/MPL/
10  *
11  * Software distributed under the License is distributed on an "AS IS" basis,
12  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
13  * for the specific language governing rights and limitations under the
14  * License.
15  *
16  * The Original Code is "MantaRay" (TM).
17  *
18  * The Initial Developer of the Original Code is Coridan.
19  * Portions created by the Initial Developer are Copyright (C) 2006
20  * Coridan Inc. All Rights Reserved.
21  *
22  * Contributor(s): all the names of the contributors are added in the source
23  * code where applicable.
24  *
25  * Alternatively, the contents of this file may be used under the terms of the
26  * LGPL license (the "GNU LESSER GENERAL PUBLIC LICENSE"), in which case the
27  * provisions of LGPL are applicable instead of those above. If you wish to
28  * allow use of your version of this file only under the terms of the LGPL
29  * License and not to allow others to use your version of this file under
30  * the MPL, indicate your decision by deleting the provisions above and
31  * replace them with the notice and other provisions required by the LGPL.
32  * If you do not delete the provisions above, a recipient may use your version
33  * of this file under either the MPL or the GNU LESSER GENERAL PUBLIC LICENSE.
34  
35  *
36  * This library is free software; you can redistribute it and/or modify it
37  * under the terms of the MPL as stated above or under the terms of the GNU
38  * Lesser General Public License as published by the Free Software Foundation;
39  * either version 2.1 of the License, or any later version.
40  *
41  * This library is distributed in the hope that it will be useful, but WITHOUT
42  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
43  * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
44  * License for more details.
45  */

46 package org.mr.core.util;
47
48 import java.security.MessageDigest JavaDoc;
49 import java.security.NoSuchAlgorithmException JavaDoc;
50 import java.security.SecureRandom JavaDoc;
51
52
53
54
55 public final class UUID implements java.io.Serializable JavaDoc {
56
57
58     /**
59      * Explicit serialVersionUID for interoperability.
60      */

61
62     private static final long serialVersionUID = -4856846361193249489L;
63
64     /*
65     * The most significant 64 bits of this UUID.
66     *
67     * @serial
68     */

69
70     private final long mostSigBits;
71
72     /*
73     * The least significant 64 bits of this UUID.
74     *
75     * @serial
76     */

77
78     private final long leastSigBits;
79
80     /*
81     * The version number associated with this UUID. Computed on demand.
82     */

83
84     private transient int version = -1;
85
86     /*
87     * The variant number associated with this UUID. Computed on demand.
88     */

89
90     private transient int variant = -1;
91
92     /*
93     * The timestamp associated with this UUID. Computed on demand.
94     */

95
96     private transient volatile long timestamp = -1;
97
98     /*
99     * The clock sequence associated with this UUID. Computed on demand.
100     */

101
102     private transient int sequence = -1;
103
104     /*
105     * The node number associated with this UUID. Computed on demand.
106     */

107
108     private transient long node = -1;
109
110     /*
111     * The hashcode of this UUID. Computed on demand.
112     */

113
114     private transient int hashCode = -1;
115
116     /*
117     * The random number generator used by this class to create random
118     * based UUIDs.
119     */

120
121     private static volatile SecureRandom JavaDoc numberGenerator = null;
122
123     // Constructors and Factories
124

125     /*
126     * Private constructor which uses a byte array to construct the new UUID.
127     */

128
129     private UUID(byte[] data) {
130
131         long msb = 0;
132
133         long lsb = 0;
134         
135         if( data.length != 16){
136             throw new AssertionError JavaDoc();
137         }
138
139         for (int i = 0; i < 8; i++)
140
141             msb = (msb << 8) | (data[i] & 0xff);
142
143         for (int i = 8; i < 16; i++)
144
145             lsb = (lsb << 8) | (data[i] & 0xff);
146
147         this.mostSigBits = msb;
148
149         this.leastSigBits = lsb;
150
151     }
152
153
154     /**
155      * Constructs a new <tt>UUID</tt> using the specified data.
156      * <tt>mostSigBits</tt> is used for the most significant 64 bits
157      * of the <tt>UUID</tt> and <tt>leastSigBits</tt> becomes the
158      * least significant 64 bits of the <tt>UUID</tt>.
159      *
160      * @param mostSigBits
161      * @param leastSigBits
162      */

163
164     public UUID(long mostSigBits, long leastSigBits) {
165
166         this.mostSigBits = mostSigBits;
167
168         this.leastSigBits = leastSigBits;
169
170     }
171
172
173     /**
174      * Static factory to retrieve a type 4 (pseudo randomly generated) UUID.
175      * <p/>
176      * The <code>UUID</code> is generated using a cryptographically strong
177      * pseudo random number generator.
178      *
179      * @return a randomly generated <tt>UUID</tt>.
180      */

181
182     public static UUID randomUUID() {
183
184         SecureRandom JavaDoc ng = numberGenerator;
185
186         if (ng == null) {
187
188             numberGenerator = ng = new SecureRandom JavaDoc();
189
190         }
191
192
193         byte[] randomBytes = new byte[16];
194
195         ng.nextBytes(randomBytes);
196
197         randomBytes[6] &= 0x0f; /* clear version */
198
199         randomBytes[6] |= 0x40; /* set to version 4 */
200
201         randomBytes[8] &= 0x3f; /* clear variant */
202
203         randomBytes[8] |= 0x80; /* set to IETF variant */
204
205         UUID result = new UUID(randomBytes);
206
207         return new UUID(randomBytes);
208
209     }
210
211
212     /**
213      * Static factory to retrieve a type 3 (name based) <tt>UUID</tt> based on
214      * the specified byte array.
215      *
216      * @param name a byte array to be used to construct a <tt>UUID</tt>.
217      * @return a <tt>UUID</tt> generated from the specified array.
218      */

219
220     public static UUID nameUUIDFromBytes(byte[] name) {
221
222         MessageDigest JavaDoc md;
223
224         try {
225
226             md = MessageDigest.getInstance("MD5");
227
228         } catch (NoSuchAlgorithmException JavaDoc nsae) {
229
230             throw new InternalError JavaDoc("MD5 not supported");
231
232         }
233
234         byte[] md5Bytes = md.digest(name);
235
236         md5Bytes[6] &= 0x0f; /* clear version */
237
238         md5Bytes[6] |= 0x30; /* set to version 3 */
239
240         md5Bytes[8] &= 0x3f; /* clear variant */
241
242         md5Bytes[8] |= 0x80; /* set to IETF variant */
243
244         return new UUID(md5Bytes);
245
246     }
247
248
249     /**
250      * Creates a <tt>UUID</tt> from the string standard representation as
251      * described in the {@link #toString} method.
252      *
253      * @param name a string that specifies a <tt>UUID</tt>.
254      * @return a <tt>UUID</tt> with the specified value.
255      * @throws IllegalArgumentException if name does not conform to the
256      * string representation as described in {@link #toString}.
257      */

258
259     public static UUID fromString(String JavaDoc name) {
260
261         String JavaDoc[] components = name.split("-");
262
263         if (components.length != 5)
264
265             throw new IllegalArgumentException JavaDoc("Invalid UUID string: " + name);
266
267         for (int i = 0; i < 5; i++)
268
269             components[i] = "0x" + components[i];
270
271
272         long mostSigBits = Long.decode(components[0]).longValue();
273
274         mostSigBits <<= 16;
275
276         mostSigBits |= Long.decode(components[1]).longValue();
277
278         mostSigBits <<= 16;
279
280         mostSigBits |= Long.decode(components[2]).longValue();
281
282
283         long leastSigBits = Long.decode(components[3]).longValue();
284
285         leastSigBits <<= 48;
286
287         leastSigBits |= Long.decode(components[4]).longValue();
288
289
290         return new UUID(mostSigBits, leastSigBits);
291
292     }
293
294     // Field Accessor Methods
295

296
297     /**
298      * Returns the least significant 64 bits of this UUID's 128 bit value.
299      *
300      * @return the least significant 64 bits of this UUID's 128 bit value.
301      */

302
303     public long getLeastSignificantBits() {
304
305         return leastSigBits;
306
307     }
308
309
310     /**
311      * Returns the most significant 64 bits of this UUID's 128 bit value.
312      *
313      * @return the most significant 64 bits of this UUID's 128 bit value.
314      */

315
316     public long getMostSignificantBits() {
317
318         return mostSigBits;
319
320     }
321
322
323     /**
324      * The version number associated with this <tt>UUID</tt>. The version
325      * number describes how this <tt>UUID</tt> was generated.
326      * <p/>
327      * <p/>
328      * <p/>
329      * The version number has the following meaning:<p>
330      * <p/>
331      * <ul>
332      * <p/>
333      * <li>1 Time-based UUID
334      * <p/>
335      * <li>2 DCE security UUID
336      * <p/>
337      * <li>3 Name-based UUID
338      * <p/>
339      * <li>4 Randomly generated UUID
340      * <p/>
341      * </ul>
342      *
343      * @return the version number of this <tt>UUID</tt>.
344      */

345
346     public int version() {
347
348         if (version < 0) {
349
350             // Version is bits masked by 0x000000000000F000 in MS long
351

352             version = (int) ((mostSigBits >> 12) & 0x0f);
353
354         }
355
356         return version;
357
358     }
359
360
361     /**
362      * The variant number associated with this <tt>UUID</tt>. The variant
363      * <p/>
364      * number describes the layout of the <tt>UUID</tt>.
365      * <p/>
366      * <p/>
367      * <p/>
368      * The variant number has the following meaning:<p>
369      * <p/>
370      * <ul>
371      * <p/>
372      * <li>0 Reserved for NCS backward compatibility
373      * <p/>
374      * <li>2 The Leach-Salz variant (used by this class)
375      * <p/>
376      * <li>6 Reserved, Microsoft Corporation backward compatibility
377      * <p/>
378      * <li>7 Reserved for future definition
379      * <p/>
380      * </ul>
381      *
382      * @return the variant number of this <tt>UUID</tt>.
383      */

384
385     public int variant() {
386
387         if (variant < 0) {
388
389             // This field is composed of a varying number of bits
390

391             if ((leastSigBits >>> 63) == 0) {
392
393                 variant = 0;
394
395             } else if ((leastSigBits >>> 62) == 2) {
396
397                 variant = 2;
398
399             } else {
400
401                 variant = (int) (leastSigBits >>> 61);
402
403             }
404
405         }
406
407         return variant;
408
409     }
410
411
412     /**
413      * The timestamp value associated with this UUID.
414      * <p/>
415      * <p/>
416      * <p/>
417      * <p>The 60 bit timestamp value is constructed from the time_low,
418      * <p/>
419      * time_mid, and time_hi fields of this <tt>UUID</tt>. The resulting
420      * <p/>
421      * timestamp is measured in 100-nanosecond units since midnight,
422      * <p/>
423      * October 15, 1582 UTC.<p>
424      * <p/>
425      * <p/>
426      * <p/>
427      * The timestamp value is only meaningful in a time-based UUID, which
428      * <p/>
429      * has version type 1. If this <tt>UUID</tt> is not a time-based UUID then
430      * <p/>
431      * this method throws UnsupportedOperationException.
432      *
433      * @throws UnsupportedOperationException if this UUID is not a
434      * <p/>
435      * version 1 UUID.
436      */

437
438     public long timestamp() {
439
440         if (version() != 1) {
441
442             throw new UnsupportedOperationException JavaDoc("Not a time-based UUID");
443
444         }
445
446         long result = timestamp;
447
448         if (result < 0) {
449
450             result = (mostSigBits & 0x0000000000000FFFL) << 48;
451
452             result |= ((mostSigBits >> 16) & 0xFFFFL) << 32;
453
454             result |= mostSigBits >>> 32;
455
456             timestamp = result;
457
458         }
459
460         return result;
461
462     }
463
464
465     /**
466      * The clock sequence value associated with this UUID.
467      * <p/>
468      * <p/>
469      * <p/>
470      * <p>The 14 bit clock sequence value is constructed from the clock
471      * <p/>
472      * sequence field of this UUID. The clock sequence field is used to
473      * <p/>
474      * guarantee temporal uniqueness in a time-based UUID.<p>
475      * <p/>
476      * <p/>
477      * <p/>
478      * The clockSequence value is only meaningful in a time-based UUID, which
479      * <p/>
480      * has version type 1. If this UUID is not a time-based UUID then
481      * <p/>
482      * this method throws UnsupportedOperationException.
483      *
484      * @return the clock sequence of this <tt>UUID</tt>.
485      * @throws UnsupportedOperationException if this UUID is not a
486      * <p/>
487      * version 1 UUID.
488      */

489
490     public int clockSequence() {
491
492         if (version() != 1) {
493
494             throw new UnsupportedOperationException JavaDoc("Not a time-based UUID");
495
496         }
497
498         if (sequence < 0) {
499
500             sequence = (int) ((leastSigBits & 0x3FFF000000000000L) >>> 48);
501
502         }
503
504         return sequence;
505
506     }
507
508
509     /**
510      * The node value associated with this UUID.
511      * <p/>
512      * <p/>
513      * <p/>
514      * <p>The 48 bit node value is constructed from the node field of
515      * <p/>
516      * this UUID. This field is intended to hold the IEEE 802 address
517      * <p/>
518      * of the machine that generated this UUID to guarantee spatial
519      * <p/>
520      * uniqueness.<p>
521      * <p/>
522      * <p/>
523      * <p/>
524      * The node value is only meaningful in a time-based UUID, which
525      * <p/>
526      * has version type 1. If this UUID is not a time-based UUID then
527      * <p/>
528      * this method throws UnsupportedOperationException.
529      *
530      * @return the node value of this <tt>UUID</tt>.
531      * @throws UnsupportedOperationException if this UUID is not a
532      * <p/>
533      * version 1 UUID.
534      */

535
536     public long node() {
537
538         if (version() != 1) {
539
540             throw new UnsupportedOperationException JavaDoc("Not a time-based UUID");
541
542         }
543
544         if (node < 0) {
545
546             node = leastSigBits & 0x0000FFFFFFFFFFFFL;
547
548         }
549
550         return node;
551
552     }
553
554     // Object Inherited Methods
555

556
557     /**
558      * Returns a <code>String</code> object representing this
559      * <p/>
560      * <code>UUID</code>.
561      * <p/>
562      * <p/>
563      * <p/>
564      * <p>The UUID string representation is as described by this BNF :
565      * <p/>
566      * <pre>
567      * <p/>
568      * UUID = <time_low> "-" <time_mid> "-"
569      * <p/>
570      * <time_high_and_version> "-"
571      * <p/>
572      * <variant_and_sequence> "-"
573      * <p/>
574      * <node>
575      * <p/>
576      * time_low = 4*<hexOctet>
577      * <p/>
578      * time_mid = 2*<hexOctet>
579      * <p/>
580      * time_high_and_version = 2*<hexOctet>
581      * <p/>
582      * variant_and_sequence = 2*<hexOctet>
583      * <p/>
584      * node = 6*<hexOctet>
585      * <p/>
586      * hexOctet = <hexDigit><hexDigit>
587      * <p/>
588      * hexDigit =
589      * <p/>
590      * "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9"
591      * <p/>
592      * | "a" | "b" | "c" | "d" | "e" | "f"
593      * <p/>
594      * | "A" | "B" | "C" | "D" | "E" | "F"
595      * <p/>
596      * </pre>
597      *
598      * @return a string representation of this <tt>UUID</tt>.
599      */

600
601     public String JavaDoc toString() {
602
603         return (digits(mostSigBits >> 32, 8) + "-" +
604
605                 digits(mostSigBits >> 16, 4) + "-" +
606
607                 digits(mostSigBits, 4) + "-" +
608
609                 digits(leastSigBits >> 48, 4) + "-" +
610
611                 digits(leastSigBits, 12));
612
613     }
614
615
616     /**
617      * Returns val represented by the specified number of hex digits.
618      */

619
620     private static String JavaDoc digits(long val, int digits) {
621
622         long hi = 1L << (digits * 4);
623
624         return Long.toHexString(hi | (val & (hi - 1))).substring(1);
625
626     }
627
628
629     /**
630      * Returns a hash code for this <code>UUID</code>.
631      *
632      * @return a hash code value for this <tt>UUID</tt>.
633      */

634
635     public int hashCode() {
636
637         if (hashCode == -1) {
638
639             hashCode = (int) ((mostSigBits >> 32) ^
640
641                     mostSigBits ^
642
643                     (leastSigBits >> 32) ^
644
645                     leastSigBits);
646
647         }
648
649         return hashCode;
650
651     }
652
653
654     /**
655      * Compares this object to the specified object. The result is
656      * <p/>
657      * <tt>true</tt> if and only if the argument is not
658      * <p/>
659      * <tt>null</tt>, is a <tt>UUID</tt> object, has the same variant,
660      * <p/>
661      * and contains the same value, bit for bit, as this <tt>UUID</tt>.
662      *
663      * @param obj the object to compare with.
664      * @return <code>true</code> if the objects are the same;
665      * <p/>
666      * <code>false</code> otherwise.
667      */

668
669     public boolean equals(Object JavaDoc obj) {
670
671         if (!(obj instanceof UUID))
672
673             return false;
674
675         if (((UUID) obj).variant() != this.variant())
676
677             return false;
678
679         UUID id = (UUID) obj;
680
681         return (mostSigBits == id.mostSigBits &&
682
683                 leastSigBits == id.leastSigBits);
684
685     }
686
687     // Comparison Operations
688

689
690     /**
691      * Compares this UUID with the specified UUID.
692      * <p/>
693      * <p/>
694      * <p/>
695      * <p>The first of two UUIDs follows the second if the most significant
696      * <p/>
697      * field in which the UUIDs differ is greater for the first UUID.
698      *
699      * @param val <tt>UUID</tt> to which this <tt>UUID</tt> is to be compared.
700      * @return -1, 0 or 1 as this <tt>UUID</tt> is less than, equal
701      * <p/>
702      * to, or greater than <tt>val</tt>.
703      */

704
705     public int compareTo(UUID val) {
706
707         // The ordering is intentionally set up so that the UUIDs
708

709         // can simply be numerically compared as two numbers
710

711         return (this.mostSigBits < val.mostSigBits ? -1 :
712
713                 (this.mostSigBits > val.mostSigBits ? 1 :
714
715                         (this.leastSigBits < val.leastSigBits ? -1 :
716
717                                 (this.leastSigBits > val.leastSigBits ? 1 :
718
719                                         0))));
720
721     }
722
723
724     /**
725      * Reconstitute the <tt>UUID</tt> instance from a stream (that is,
726      * <p/>
727      * deserialize it). This is necessary to set the transient fields
728      * <p/>
729      * to their correct uninitialized value so they will be recomputed
730      * <p/>
731      * on demand.
732      */

733
734     private void readObject(java.io.ObjectInputStream JavaDoc in)
735
736             throws java.io.IOException JavaDoc, ClassNotFoundException JavaDoc {
737
738
739         in.defaultReadObject();
740
741         // Set "cached computation" fields to their initial values
742

743         version = -1;
744
745         variant = -1;
746
747         timestamp = -1;
748
749         sequence = -1;
750
751         node = -1;
752
753         hashCode = -1;
754
755     }
756
757 }
758
759
Popular Tags