1 /*
   2  * Copyright (c) 2003, 2012, 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      * Provides access to String's non-public constructor that does not copy the char[]
  82      */
  83     private static final JavaLangAccess JAVA_LANG_ACCESS
  84             = SharedSecrets.getJavaLangAccess();
  85 
  86     /*
  87      * The most significant 64 bits of this UUID.
  88      *
  89      * @serial
  90      */
  91     private final long mostSigBits;
  92 
  93     /*
  94      * The least significant 64 bits of this UUID.
  95      *
  96      * @serial
  97      */
  98     private final long leastSigBits;
  99 
 100     /*
 101      * The random number generator used by this class to create random
 102      * based UUIDs. In a holder class to defer initialization until needed.
 103      */
 104     private static class Holder {
 105         static final SecureRandom numberGenerator = new SecureRandom();
 106     }
 107 
 108     // Constructors and Factories
 109 
 110     /*
 111      * Private constructor which uses a byte array to construct the new UUID.
 112      */
 113     private UUID(byte[] data) {
 114         long msb = 0;
 115         long lsb = 0;
 116         assert data.length == 16 : "data must be 16 bytes in length";
 117         for (int i=0; i<8; i++)
 118             msb = (msb << 8) | (data[i] & 0xff);
 119         for (int i=8; i<16; i++)
 120             lsb = (lsb << 8) | (data[i] & 0xff);
 121         this.mostSigBits = msb;
 122         this.leastSigBits = lsb;
 123     }
 124 
 125     /**
 126      * Constructs a new {@code UUID} using the specified data.  {@code
 127      * mostSigBits} is used for the most significant 64 bits of the {@code
 128      * UUID} and {@code leastSigBits} becomes the least significant 64 bits of
 129      * the {@code UUID}.
 130      *
 131      * @param  mostSigBits
 132      *         The most significant bits of the {@code UUID}
 133      *
 134      * @param  leastSigBits
 135      *         The least significant bits of the {@code UUID}
 136      */
 137     public UUID(long mostSigBits, long leastSigBits) {
 138         this.mostSigBits = mostSigBits;
 139         this.leastSigBits = leastSigBits;
 140     }
 141 
 142     /**
 143      * Static factory to retrieve a type 4 (pseudo randomly generated) UUID.
 144      *
 145      * The {@code UUID} is generated using a cryptographically strong pseudo
 146      * random number generator.
 147      *
 148      * @return  A randomly generated {@code UUID}
 149      */
 150     public static UUID randomUUID() {
 151         SecureRandom ng = Holder.numberGenerator;
 152 
 153         byte[] randomBytes = new byte[16];
 154         ng.nextBytes(randomBytes);
 155         randomBytes[6]  &= 0x0f;  /* clear version        */
 156         randomBytes[6]  |= 0x40;  /* set to version 4     */
 157         randomBytes[8]  &= 0x3f;  /* clear variant        */
 158         randomBytes[8]  |= 0x80;  /* set to IETF variant  */
 159         return new UUID(randomBytes);
 160     }
 161 
 162     /**
 163      * Static factory to retrieve a type 3 (name based) {@code UUID} based on
 164      * the specified byte array.
 165      *
 166      * @param  name
 167      *         A byte array to be used to construct a {@code UUID}
 168      *
 169      * @return  A {@code UUID} generated from the specified array
 170      */
 171     public static UUID nameUUIDFromBytes(byte[] name) {
 172         MessageDigest md;
 173         try {
 174             md = MessageDigest.getInstance("MD5");
 175         } catch (NoSuchAlgorithmException nsae) {
 176             throw new InternalError("MD5 not supported", nsae);
 177         }
 178         byte[] md5Bytes = md.digest(name);
 179         md5Bytes[6]  &= 0x0f;  /* clear version        */
 180         md5Bytes[6]  |= 0x30;  /* set to version 3     */
 181         md5Bytes[8]  &= 0x3f;  /* clear variant        */
 182         md5Bytes[8]  |= 0x80;  /* set to IETF variant  */
 183         return new UUID(md5Bytes);
 184     }
 185 
 186     /**
 187      * Creates a {@code UUID} from the string standard representation as
 188      * described in the {@link #toString} method.
 189      *
 190      * @param  str
 191      *         A string that specifies a {@code UUID}
 192      *
 193      * @return  A {@code UUID} with the specified value
 194      *
 195      * @throws  IllegalArgumentException
 196      *          If name does not conform to the string representation as
 197      *          described in {@link #toString}
 198      *
 199      */
 200     public static UUID fromString(String str) {
 201         int dashCount = 4;
 202         int [] dashPos = new int [6];
 203         dashPos[0] = -1;
 204         dashPos[5] = str.length();
 205 
 206         for (int i = str.length()-1; i >= 0; i--) {
 207             if (str.charAt(i) == '-') {
 208                 if (dashCount == 0) {
 209                     throw new IllegalArgumentException("Invalid UUID string: " + str);
 210                 }
 211                 dashPos[dashCount--] = i;
 212             }
 213         }
 214 
 215         if (dashCount > 0) {
 216             throw new IllegalArgumentException("Invalid UUID string: " + str);
 217         }
 218 
 219         long mostSigBits = decode(str, dashPos, 0) & 0xffffffffL;
 220         mostSigBits <<= 16;
 221         mostSigBits |= decode(str, dashPos, 1) & 0xffffL;
 222         mostSigBits <<= 16;
 223         mostSigBits |= decode(str,  dashPos, 2) & 0xffffL;
 224 
 225         long leastSigBits = decode(str,  dashPos, 3) & 0xffffL;
 226         leastSigBits <<= 48;
 227         leastSigBits |= decode(str,  dashPos, 4) & 0xffffffffffffL;
 228 
 229         return new UUID(mostSigBits, leastSigBits);
 230     }
 231 
 232     private static long decode(final String str, final int [] dashPos, final int field) {
 233         int start = dashPos[field]+1;
 234         int end = dashPos[field+1];
 235         if (start >= end) {
 236             throw new IllegalArgumentException("Invalid UUID string: " + str);
 237         }
 238         return decodeLongHexString(str, start, end);
 239     }
 240 
 241     private static final int NUM_ALPHA_DIFF = 'A' - '9' - 1;
 242     private static final int LOWER_UPPER_DIFF = 'a' - 'A';
 243 
 244     /**
 245      * Given a hexadecimal string, decode a portion into a long.
 246      * @param str the string to decode
 247      * @param start the start of the substring to decode
 248      * @param end the end of the substring to decode
 249      */
 250     public static long decodeLongHexString(CharSequence str, int start, int end)
 251     {
 252         long curr = 0;
 253         for (int i = start; i < end; i++) {
 254             int x = getNibbleFromHexChar(str.charAt(i));
 255             curr <<= 4;
 256             if (curr < 0) {
 257                 throw new NumberFormatException("long overflow");
 258             }
 259             curr |= x;
 260         }
 261         return curr;
 262     }
 263 
 264     /**
 265      * Given a hexadecimal digit, return the decimal value.
 266      * @param c the character to decode
 267      */
 268     public static int getNibbleFromHexChar(final char c)
 269     {
 270         int x = c - '0';
 271         if (x > 9) {
 272             x -= NUM_ALPHA_DIFF; // difference between '9' and 'A'
 273             if (x > 15) {
 274                 x -= LOWER_UPPER_DIFF; // difference between 'a' and 'A'
 275             }
 276             if (x < 10) {
 277                 throw new IllegalArgumentException(c + " is not a valid character for a hex string");
 278             }
 279         }
 280 
 281         if (x < 0 || x > 15) {
 282             throw new IllegalArgumentException(c + " is not a valid character for a hex string");
 283         }
 284 
 285         return x;
 286     }
 287 
 288     // Field Accessor Methods
 289 
 290     /**
 291      * Returns the least significant 64 bits of this UUID's 128 bit value.
 292      *
 293      * @return  The least significant 64 bits of this UUID's 128 bit value
 294      */
 295     public long getLeastSignificantBits() {
 296         return leastSigBits;
 297     }
 298 
 299     /**
 300      * Returns the most significant 64 bits of this UUID's 128 bit value.
 301      *
 302      * @return  The most significant 64 bits of this UUID's 128 bit value
 303      */
 304     public long getMostSignificantBits() {
 305         return mostSigBits;
 306     }
 307 
 308     /**
 309      * The version number associated with this {@code UUID}.  The version
 310      * number describes how this {@code UUID} was generated.
 311      *
 312      * The version number has the following meaning:
 313      * <p><ul>
 314      * <li>1    Time-based UUID
 315      * <li>2    DCE security UUID
 316      * <li>3    Name-based UUID
 317      * <li>4    Randomly generated UUID
 318      * </ul>
 319      *
 320      * @return  The version number of this {@code UUID}
 321      */
 322     public int version() {
 323         // Version is bits masked by 0x000000000000F000 in MS long
 324         return (int)((mostSigBits >> 12) & 0x0f);
 325     }
 326 
 327     /**
 328      * The variant number associated with this {@code UUID}.  The variant
 329      * number describes the layout of the {@code UUID}.
 330      *
 331      * The variant number has the following meaning:
 332      * <p><ul>
 333      * <li>0    Reserved for NCS backward compatibility
 334      * <li>2    <a href="http://www.ietf.org/rfc/rfc4122.txt">IETF&nbsp;RFC&nbsp;4122</a>
 335      * (Leach-Salz), used by this class
 336      * <li>6    Reserved, Microsoft Corporation backward compatibility
 337      * <li>7    Reserved for future definition
 338      * </ul>
 339      *
 340      * @return  The variant number of this {@code UUID}
 341      */
 342     public int variant() {
 343         // This field is composed of a varying number of bits.
 344         // 0    -    -    Reserved for NCS backward compatibility
 345         // 1    0    -    The IETF aka Leach-Salz variant (used by this class)
 346         // 1    1    0    Reserved, Microsoft backward compatibility
 347         // 1    1    1    Reserved for future definition.
 348         return (int) ((leastSigBits >>> (64 - (leastSigBits >>> 62)))
 349                       & (leastSigBits >> 63));
 350     }
 351 
 352     /**
 353      * The timestamp value associated with this UUID.
 354      *
 355      * <p> The 60 bit timestamp value is constructed from the time_low,
 356      * time_mid, and time_hi fields of this {@code UUID}.  The resulting
 357      * timestamp is measured in 100-nanosecond units since midnight,
 358      * October 15, 1582 UTC.
 359      *
 360      * <p> The timestamp value is only meaningful in a time-based UUID, which
 361      * has version type 1.  If this {@code UUID} is not a time-based UUID then
 362      * this method throws UnsupportedOperationException.
 363      *
 364      * @throws UnsupportedOperationException
 365      *         If this UUID is not a version 1 UUID
 366      */
 367     public long timestamp() {
 368         if (version() != 1) {
 369             throw new UnsupportedOperationException("Not a time-based UUID");
 370         }
 371 
 372         return (mostSigBits & 0x0FFFL) << 48
 373              | ((mostSigBits >> 16) & 0x0FFFFL) << 32
 374              | mostSigBits >>> 32;
 375     }
 376 
 377     /**
 378      * The clock sequence value associated with this UUID.
 379      *
 380      * <p> The 14 bit clock sequence value is constructed from the clock
 381      * sequence field of this UUID.  The clock sequence field is used to
 382      * guarantee temporal uniqueness in a time-based UUID.
 383      *
 384      * <p> The {@code clockSequence} value is only meaningful in a time-based
 385      * UUID, which has version type 1.  If this UUID is not a time-based UUID
 386      * then this method throws UnsupportedOperationException.
 387      *
 388      * @return  The clock sequence of this {@code UUID}
 389      *
 390      * @throws  UnsupportedOperationException
 391      *          If this UUID is not a version 1 UUID
 392      */
 393     public int clockSequence() {
 394         if (version() != 1) {
 395             throw new UnsupportedOperationException("Not a time-based UUID");
 396         }
 397 
 398         return (int)((leastSigBits & 0x3FFF000000000000L) >>> 48);
 399     }
 400 
 401     /**
 402      * The node value associated with this UUID.
 403      *
 404      * <p> The 48 bit node value is constructed from the node field of this
 405      * UUID.  This field is intended to hold the IEEE 802 address of the machine
 406      * that generated this UUID to guarantee spatial uniqueness.
 407      *
 408      * <p> The node value is only meaningful in a time-based UUID, which has
 409      * version type 1.  If this UUID is not a time-based UUID then this method
 410      * throws UnsupportedOperationException.
 411      *
 412      * @return  The node value of this {@code UUID}
 413      *
 414      * @throws  UnsupportedOperationException
 415      *          If this UUID is not a version 1 UUID
 416      */
 417     public long node() {
 418         if (version() != 1) {
 419             throw new UnsupportedOperationException("Not a time-based UUID");
 420         }
 421 
 422         return leastSigBits & 0x0000FFFFFFFFFFFFL;
 423     }
 424 
 425     // Object Inherited Methods
 426 
 427     /**
 428      * Returns a {@code String} object representing this {@code UUID}.
 429      *
 430      * <p> The UUID string representation is as described by this BNF:
 431      * <blockquote><pre>
 432      * {@code
 433      * UUID                   = <time_low> "-" <time_mid> "-"
 434      *                          <time_high_and_version> "-"
 435      *                          <variant_and_sequence> "-"
 436      *                          <node>
 437      * time_low               = 4*<hexOctet>
 438      * time_mid               = 2*<hexOctet>
 439      * time_high_and_version  = 2*<hexOctet>
 440      * variant_and_sequence   = 2*<hexOctet>
 441      * node                   = 6*<hexOctet>
 442      * hexOctet               = <hexDigit><hexDigit>
 443      * hexDigit               =
 444      *       "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9"
 445      *       | "a" | "b" | "c" | "d" | "e" | "f"
 446      *       | "A" | "B" | "C" | "D" | "E" | "F"
 447      * }</pre></blockquote>
 448      *
 449      * @return  A string representation of this {@code UUID}
 450      */
 451     public String toString()
 452     {
 453         return toString(getMostSignificantBits(), getLeastSignificantBits());
 454     }
 455 
 456     /**
 457      * Returns a {@code String} object representing a UUID passed in as
 458      * two longs.  Usually you will use {@link #toString()} instead.
 459      * @param msb the most significant bytes
 460      * @param lsb the least significant bytes
 461      */
 462     private static String toString(long msb, long lsb)
 463     {
 464         char[] uuidChars = new char[36];
 465 
 466         digits(uuidChars, 0, 8, msb >> 32);
 467         uuidChars[8] = '-';
 468         digits(uuidChars, 9, 4, msb >> 16);
 469         uuidChars[13] = '-';
 470         digits(uuidChars, 14, 4, msb);
 471         uuidChars[18] = '-';
 472         digits(uuidChars, 19, 4, lsb >> 48);
 473         uuidChars[23] = '-';
 474         digits(uuidChars, 24, 12, lsb);
 475 
 476         return JAVA_LANG_ACCESS.createStringSharedChars(uuidChars);
 477     }
 478 
 479     private static void digits(char[] dest, int offset, int digits, long val) {
 480         long mask = 1L << (digits * 4);
 481         JAVA_LANG_ACCESS.formatUnsignedLong(mask | (val & (mask - 1)), 4, dest, offset, digits);
 482     }
 483 
 484     /**
 485      * Returns a hash code for this {@code UUID}.
 486      *
 487      * @return  A hash code value for this {@code UUID}
 488      */
 489     public int hashCode() {
 490         long hilo = mostSigBits ^ leastSigBits;
 491         return ((int)(hilo >> 32)) ^ (int) hilo;
 492     }
 493 
 494     /**
 495      * Compares this object to the specified object.  The result is {@code
 496      * true} if and only if the argument is not {@code null}, is a {@code UUID}
 497      * object, has the same variant, and contains the same value, bit for bit,
 498      * as this {@code UUID}.
 499      *
 500      * @param  obj
 501      *         The object to be compared
 502      *
 503      * @return  {@code true} if the objects are the same; {@code false}
 504      *          otherwise
 505      */
 506     public boolean equals(Object obj) {
 507         if ((null == obj) || (obj.getClass() != UUID.class))
 508             return false;
 509         UUID id = (UUID)obj;
 510         return (mostSigBits == id.mostSigBits &&
 511                 leastSigBits == id.leastSigBits);
 512     }
 513 
 514     // Comparison Operations
 515 
 516     /**
 517      * Compares this UUID with the specified UUID.
 518      *
 519      * <p> The first of two UUIDs is greater than the second if the most
 520      * significant field in which the UUIDs differ is greater for the first
 521      * UUID.
 522      *
 523      * @param  val
 524      *         {@code UUID} to which this {@code UUID} is to be compared
 525      *
 526      * @return  -1, 0 or 1 as this {@code UUID} is less than, equal to, or
 527      *          greater than {@code val}
 528      *
 529      */
 530     public int compareTo(UUID val) {
 531         // The ordering is intentionally set up so that the UUIDs
 532         // can simply be numerically compared as two numbers
 533         return (this.mostSigBits < val.mostSigBits ? -1 :
 534                 (this.mostSigBits > val.mostSigBits ? 1 :
 535                  (this.leastSigBits < val.leastSigBits ? -1 :
 536                   (this.leastSigBits > val.leastSigBits ? 1 :
 537                    0))));
 538     }
 539 }