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