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 /**
  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      * <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      * <ul>
 256      * <li>0    Reserved for NCS backward compatibility
 257      * <li>2    <a href="http://www.ietf.org/rfc/rfc4122.txt">IETF&nbsp;RFC&nbsp;4122</a>
 258      * (Leach-Salz), used by this class
 259      * <li>6    Reserved, Microsoft Corporation backward compatibility
 260      * <li>7    Reserved for future definition
 261      * </ul>
 262      *
 263      * @return  The variant number of this {@code UUID}
 264      */
 265     public int variant() {
 266         // This field is composed of a varying number of bits.
 267         // 0    -    -    Reserved for NCS backward compatibility
 268         // 1    0    -    The IETF aka Leach-Salz variant (used by this class)
 269         // 1    1    0    Reserved, Microsoft backward compatibility
 270         // 1    1    1    Reserved for future definition.
 271         return (int) ((leastSigBits >>> (64 - (leastSigBits >>> 62)))
 272                       & (leastSigBits >> 63));
 273     }
 274 
 275     /**
 276      * The timestamp value associated with this UUID.
 277      *
 278      * <p> The 60 bit timestamp value is constructed from the time_low,
 279      * time_mid, and time_hi fields of this {@code UUID}.  The resulting
 280      * timestamp is measured in 100-nanosecond units since midnight,
 281      * October 15, 1582 UTC.
 282      *
 283      * <p> The timestamp value is only meaningful in a time-based UUID, which
 284      * has version type 1.  If this {@code UUID} is not a time-based UUID then
 285      * this method throws UnsupportedOperationException.
 286      *
 287      * @throws UnsupportedOperationException
 288      *         If this UUID is not a version 1 UUID
 289      * @return The timestamp of this {@code UUID}.
 290      */
 291     public long timestamp() {
 292         if (version() != 1) {
 293             throw new UnsupportedOperationException("Not a time-based UUID");
 294         }
 295 
 296         return (mostSigBits & 0x0FFFL) << 48
 297              | ((mostSigBits >> 16) & 0x0FFFFL) << 32
 298              | mostSigBits >>> 32;
 299     }
 300 
 301     /**
 302      * The clock sequence value associated with this UUID.
 303      *
 304      * <p> The 14 bit clock sequence value is constructed from the clock
 305      * sequence field of this UUID.  The clock sequence field is used to
 306      * guarantee temporal uniqueness in a time-based UUID.
 307      *
 308      * <p> The {@code clockSequence} value is only meaningful in a time-based
 309      * UUID, which has version type 1.  If this UUID is not a time-based UUID
 310      * then this method throws UnsupportedOperationException.
 311      *
 312      * @return  The clock sequence of this {@code UUID}
 313      *
 314      * @throws  UnsupportedOperationException
 315      *          If this UUID is not a version 1 UUID
 316      */
 317     public int clockSequence() {
 318         if (version() != 1) {
 319             throw new UnsupportedOperationException("Not a time-based UUID");
 320         }
 321 
 322         return (int)((leastSigBits & 0x3FFF000000000000L) >>> 48);
 323     }
 324 
 325     /**
 326      * The node value associated with this UUID.
 327      *
 328      * <p> The 48 bit node value is constructed from the node field of this
 329      * UUID.  This field is intended to hold the IEEE 802 address of the machine
 330      * that generated this UUID to guarantee spatial uniqueness.
 331      *
 332      * <p> The node value is only meaningful in a time-based UUID, which has
 333      * version type 1.  If this UUID is not a time-based UUID then this method
 334      * throws UnsupportedOperationException.
 335      *
 336      * @return  The node value of this {@code UUID}
 337      *
 338      * @throws  UnsupportedOperationException
 339      *          If this UUID is not a version 1 UUID
 340      */
 341     public long node() {
 342         if (version() != 1) {
 343             throw new UnsupportedOperationException("Not a time-based UUID");
 344         }
 345 
 346         return leastSigBits & 0x0000FFFFFFFFFFFFL;
 347     }
 348 
 349     // Object Inherited Methods
 350 
 351     /**
 352      * Returns a {@code String} object representing this {@code UUID}.
 353      *
 354      * <p> The UUID string representation is as described by this BNF:
 355      * <blockquote><pre>
 356      * {@code
 357      * UUID                   = <time_low> "-" <time_mid> "-"
 358      *                          <time_high_and_version> "-"
 359      *                          <variant_and_sequence> "-"
 360      *                          <node>
 361      * time_low               = 4*<hexOctet>
 362      * time_mid               = 2*<hexOctet>
 363      * time_high_and_version  = 2*<hexOctet>
 364      * variant_and_sequence   = 2*<hexOctet>
 365      * node                   = 6*<hexOctet>
 366      * hexOctet               = <hexDigit><hexDigit>
 367      * hexDigit               =
 368      *       "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9"
 369      *       | "a" | "b" | "c" | "d" | "e" | "f"
 370      *       | "A" | "B" | "C" | "D" | "E" | "F"
 371      * }</pre></blockquote>
 372      *
 373      * @return  A string representation of this {@code UUID}
 374      */
 375     public String toString() {
 376         return (digits(mostSigBits >> 32, 8) + "-" +
 377                 digits(mostSigBits >> 16, 4) + "-" +
 378                 digits(mostSigBits, 4) + "-" +
 379                 digits(leastSigBits >> 48, 4) + "-" +
 380                 digits(leastSigBits, 12));
 381     }
 382 
 383     /** Returns val represented by the specified number of hex digits. */
 384     private static String digits(long val, int digits) {
 385         long hi = 1L << (digits * 4);
 386         return Long.toHexString(hi | (val & (hi - 1))).substring(1);
 387     }
 388 
 389     /**
 390      * Returns a hash code for this {@code UUID}.
 391      *
 392      * @return  A hash code value for this {@code UUID}
 393      */
 394     public int hashCode() {
 395         long hilo = mostSigBits ^ leastSigBits;
 396         return ((int)(hilo >> 32)) ^ (int) hilo;
 397     }
 398 
 399     /**
 400      * Compares this object to the specified object.  The result is {@code
 401      * true} if and only if the argument is not {@code null}, is a {@code UUID}
 402      * object, has the same variant, and contains the same value, bit for bit,
 403      * as this {@code UUID}.
 404      *
 405      * @param  obj
 406      *         The object to be compared
 407      *
 408      * @return  {@code true} if the objects are the same; {@code false}
 409      *          otherwise
 410      */
 411     public boolean equals(Object obj) {
 412         if ((null == obj) || (obj.getClass() != UUID.class))
 413             return false;
 414         UUID id = (UUID)obj;
 415         return (mostSigBits == id.mostSigBits &&
 416                 leastSigBits == id.leastSigBits);
 417     }
 418 
 419     // Comparison Operations
 420 
 421     /**
 422      * Compares this UUID with the specified UUID.
 423      *
 424      * <p> The first of two UUIDs is greater than the second if the most
 425      * significant field in which the UUIDs differ is greater for the first
 426      * UUID.
 427      *
 428      * @param  val
 429      *         {@code UUID} to which this {@code UUID} is to be compared
 430      *
 431      * @return  -1, 0 or 1 as this {@code UUID} is less than, equal to, or
 432      *          greater than {@code val}
 433      *
 434      */
 435     public int compareTo(UUID val) {
 436         // The ordering is intentionally set up so that the UUIDs
 437         // can simply be numerically compared as two numbers
 438         return (this.mostSigBits < val.mostSigBits ? -1 :
 439                 (this.mostSigBits > val.mostSigBits ? 1 :
 440                  (this.leastSigBits < val.leastSigBits ? -1 :
 441                   (this.leastSigBits > val.leastSigBits ? 1 :
 442                    0))));
 443     }
 444 }
--- EOF ---