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