UUID.java 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  1. /* UUID.java -- Class that represents a UUID object.
  2. Copyright (C) 2006 Free Software Foundation, Inc.
  3. This file is part of GNU Classpath.
  4. GNU Classpath is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2, or (at your option)
  7. any later version.
  8. GNU Classpath is distributed in the hope that it will be useful, but
  9. WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with GNU Classpath; see the file COPYING. If not, write to the
  14. Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
  15. 02110-1301 USA.
  16. Linking this library statically or dynamically with other modules is
  17. making a combined work based on this library. Thus, the terms and
  18. conditions of the GNU General Public License cover the whole
  19. combination.
  20. As a special exception, the copyright holders of this library give you
  21. permission to link this library with independent modules to produce an
  22. executable, regardless of the license terms of these independent
  23. modules, and to copy and distribute the resulting executable under
  24. terms of your choice, provided that you also meet, for each linked
  25. independent module, the terms and conditions of the license of that
  26. module. An independent module is a module which is not derived from
  27. or based on this library. If you modify this library, you may extend
  28. this exception to your version of the library, but you are not
  29. obligated to do so. If you do not wish to do so, delete this
  30. exception statement from your version. */
  31. package java.util;
  32. import java.io.Serializable;
  33. import java.security.MessageDigest;
  34. import java.security.NoSuchAlgorithmException;
  35. /**
  36. * This class represents a 128-bit UUID value.
  37. *
  38. * There are several types of UUID, and while this class can be used to store
  39. * them, only the Leach-Salz (variant 2) UUID specified in RFC-4122 will
  40. * give meaningful results from the method calls.
  41. * See: http://tools.ietf.org/html/4122 for the details
  42. *
  43. * The format of a Leach-Salz (variant 2) time-based (version 1) UUID
  44. * is as follows:
  45. * time_low - upper 32 bits of the most significant 64 bits,
  46. * this is the least-significant part of the timestamp.
  47. *
  48. * time_mid - bits 16-31 of the most significant 64 bits,
  49. * this is the middle portion of the timestamp.
  50. *
  51. * version - bits 8-15 of the most significant 64 bits.
  52. *
  53. * time_hi - bits 0-7 of the most significant 64 bits,
  54. * the most significant portion of the timestamp.
  55. *
  56. * clock_and_reserved - bits 48-63 of the least significant 64 bits.
  57. * a variable number of bits hold the variant
  58. * (see the spec)
  59. *
  60. * node identifier - bits 0-47 of the least signficant 64 bits.
  61. *
  62. * These fields are valid only for version 1, in the remaining versions,
  63. * only the version and variant fields are set, all others are used for data.
  64. *
  65. * @since 1.5
  66. * @author Sven de Marothy
  67. */
  68. public final class UUID
  69. extends Object
  70. implements Serializable, Comparable<UUID>
  71. {
  72. private static final long serialVersionUID = -4856846361193249489L;
  73. /**
  74. * Serialized field - most significant 64 bits.
  75. */
  76. private long mostSigBits;
  77. /**
  78. * Serialized field - least significant 64 bits.
  79. */
  80. private long leastSigBits;
  81. /**
  82. * Random-number generator.
  83. */
  84. private static transient Random r = new Random();
  85. /**
  86. * Constructs a new UUID.
  87. *
  88. * @since 1.5
  89. */
  90. public UUID(long mostSigBits, long leastSigBits)
  91. {
  92. this.mostSigBits = mostSigBits;
  93. this.leastSigBits = leastSigBits;
  94. }
  95. /**
  96. * Returns the clock-sequence value of this UUID.
  97. * This field only exists in a time-based (version 1) UUID.
  98. *
  99. * @throws UnsupportedOperationException if the UUID type is not 1.
  100. * @returns an int containing the clock-sequence value.
  101. */
  102. public int clockSequence()
  103. {
  104. if( version() != 1 )
  105. throw new UnsupportedOperationException("Not a type 1 UUID");
  106. return (int)((leastSigBits & 0x3FFF000000000000L) >> 48);
  107. }
  108. /**
  109. * Compare this UUID to another.
  110. * The comparison is performed as between two 128-bit integers.
  111. *
  112. * @return -1 if this < val, 0 if they are equal, 1 if this > val.
  113. */
  114. public int compareTo(UUID o)
  115. {
  116. if( mostSigBits < o.mostSigBits )
  117. return -1;
  118. if( mostSigBits > o.mostSigBits )
  119. return 1;
  120. if( leastSigBits < o.leastSigBits )
  121. return -1;
  122. if( leastSigBits > o.mostSigBits )
  123. return 1;
  124. return 0;
  125. }
  126. /**
  127. * Compare a (UUID) object to this one
  128. */
  129. public boolean equals(Object obj)
  130. {
  131. if( !(obj instanceof UUID ) )
  132. return false;
  133. return ( ((UUID)obj).mostSigBits == mostSigBits &&
  134. ((UUID)obj).leastSigBits == leastSigBits );
  135. }
  136. /**
  137. * Creates a UUID object from a Sting representation.
  138. *
  139. * For the format of the string,
  140. * @see #toString()
  141. *
  142. * @return a new UUID object.
  143. */
  144. public static UUID fromString(String name)
  145. {
  146. StringTokenizer st = new StringTokenizer( name.trim(), "-" );
  147. if( st.countTokens() < 5 )
  148. throw new IllegalArgumentException( "Incorrect UUID string"+
  149. " representation:"+name );
  150. long msb = (Long.parseLong(st.nextToken(), 16) << 32); // time low
  151. msb |= (Long.parseLong(st.nextToken(), 16) << 16); // time mid
  152. msb |= Long.parseLong(st.nextToken(), 16); // time high
  153. long lsb = (Long.parseLong(st.nextToken(), 16) << 48); // clock
  154. lsb |= Long.parseLong(st.nextToken(), 16); // node
  155. return new UUID(msb, lsb);
  156. }
  157. /**
  158. * Returns a String representation of the UUID.
  159. *
  160. * The format of the standard string representation (given in RFC4122) is:
  161. *
  162. * time-low "-" time-mid "-"
  163. * time-high-and-version "-"
  164. * clock-seq-and-reserved
  165. * clock-seq-low "-" node
  166. *
  167. * Where each field is represented as a hex string.
  168. *
  169. * @return the String representation.
  170. */
  171. public String toString()
  172. {
  173. return // time-low first
  174. padHex( (( mostSigBits & 0xFFFFFFFF00000000L) >> 32) & 0xFFFFFFFFL, 8)
  175. + "-" + // then time-mid
  176. padHex( (( mostSigBits & 0xFFFF0000L ) >> 16), 4 )
  177. + "-" + // time-high
  178. padHex( ( mostSigBits & 0x0000000000000000FFFFL ), 4 )
  179. + "-" + // clock (note - no reason to separate high and low here)
  180. padHex( (((leastSigBits & 0xFFFF000000000000L) >> 48) & 0xFFFF), 4 )
  181. + "-" + // finally the node value.
  182. padHex(leastSigBits & 0xFFFFFFFFFFFFL, 12);
  183. }
  184. /**
  185. * Returns the least significant 64 bits of the UUID as a <code>long</code>.
  186. */
  187. public long getLeastSignificantBits()
  188. {
  189. return leastSigBits;
  190. }
  191. /**
  192. * Returns the most significant 64 bits of the UUID as a <code>long</code>.
  193. */
  194. public long getMostSignificantBits()
  195. {
  196. return mostSigBits;
  197. }
  198. /**
  199. * Returns a hash of this UUID.
  200. */
  201. public int hashCode()
  202. {
  203. int l1 = (int)(leastSigBits & 0xFFFFFFFFL);
  204. int l2 = (int)((leastSigBits & 0xFFFFFFFF00000000L) >> 32);
  205. int m1 = (int)(mostSigBits & 0xFFFFFFFFL);
  206. int m2 = (int)((mostSigBits & 0xFFFFFFFF00000000L) >> 32);
  207. return (l1 ^ l2) ^ (m1 ^ m2);
  208. }
  209. /**
  210. * Creates a UUID version 3 object (name based with MD5 hashing)
  211. * from a series of bytes representing a name.
  212. */
  213. public static UUID nameUUIDFromBytes(byte[] name)
  214. {
  215. long msb, lsb;
  216. byte[] hash;
  217. try
  218. {
  219. MessageDigest md5 = MessageDigest.getInstance("MD5");
  220. hash = md5.digest( name );
  221. }
  222. catch (NoSuchAlgorithmException e)
  223. {
  224. throw new UnsupportedOperationException("No MD5 algorithm available.");
  225. }
  226. msb = ((hash[0] & 0xFFL) << 56) | ((hash[1] & 0xFFL) << 48) |
  227. ((hash[2] & 0xFFL) << 40) | ((hash[3] & 0xFFL) << 32) |
  228. ((hash[4] & 0xFFL) << 24) | ((hash[5] & 0xFFL) << 16) |
  229. ((hash[6] & 0xFFL) << 8) | (hash[7] & 0xFFL);
  230. lsb = ((hash[8] & 0xFFL) << 56) | ((hash[9] & 0xFFL) << 48) |
  231. ((hash[10] & 0xFFL) << 40) | ((hash[11] & 0xFFL) << 32) |
  232. ((hash[12] & 0xFFL) << 24) | ((hash[13] & 0xFFL) << 16) |
  233. ((hash[14] & 0xFFL) << 8) | (hash[15] & 0xFFL);
  234. lsb &= 0x3FFFFFFFFFFFFFFFL;
  235. lsb |= 0x8000000000000000L; // set top two bits to variant 2
  236. msb &= 0xFFFFFFFFFFFF0FFFL;
  237. msb |= 0x3000; // Version 3;
  238. return new UUID(msb, lsb);
  239. }
  240. /**
  241. * Returns the 48-bit node value in a long.
  242. * This field only exists in a time-based (version 1) UUID.
  243. *
  244. * @throws UnsupportedOperationException if the UUID type is not 1.
  245. * @returns a long with the node value in the lower 48 bits.
  246. */
  247. public long node()
  248. {
  249. if( version() != 1 )
  250. throw new UnsupportedOperationException("Not a type 1 UUID");
  251. return (leastSigBits & 0xFFFFFFFFFFFFL);
  252. }
  253. /**
  254. * Returns the 60-bit timestamp value of the UUID in a long.
  255. * This field only exists in a time-based (version 1) UUID.
  256. *
  257. * @throws UnsupportedOperationException if the UUID type is not 1.
  258. * @returns a long with the timestamp value.
  259. */
  260. public long timestamp()
  261. {
  262. if( version() != 1 )
  263. throw new UnsupportedOperationException("Not a type 1 UUID");
  264. long time = (( mostSigBits & 0xFFFFFFFF00000000L) >> 32);
  265. time |= (( mostSigBits & 0xFFFF0000L ) << 16);
  266. long time_hi = ( mostSigBits & 0xFFFL );
  267. time |= (time_hi << 48);
  268. return time;
  269. }
  270. /**
  271. * Generate a Leach-Salz (Variant 2) randomly generated (version 4)
  272. * UUID.
  273. *
  274. */
  275. public static UUID randomUUID()
  276. {
  277. long lsb = r.nextLong();
  278. long msb = r.nextLong();
  279. lsb &= 0x3FFFFFFFFFFFFFFFL;
  280. lsb |= 0x8000000000000000L; // set top two bits to variant 2
  281. msb &= 0xFFFFFFFFFFFF0FFFL;
  282. msb |= 0x4000; // Version 4;
  283. return new UUID( msb, lsb );
  284. }
  285. /**
  286. * Returns a hex String from l, padded to n spaces.
  287. */
  288. private String padHex( long l, int n )
  289. {
  290. String s = Long.toHexString( l );
  291. while( s.length() < n )
  292. s = "0" + s;
  293. return s;
  294. }
  295. /**
  296. * Returns the variant of the UUID
  297. *
  298. * This may be:
  299. * 0 = Reserved for NCS backwards-compatibility
  300. * 2 = Leach-Salz (supports the other methods in this class)
  301. * 6 = Reserved for Microsoft backwards-compatibility
  302. * 7 = (reserved for future use)
  303. */
  304. public int variant()
  305. {
  306. // Get the top 3 bits (not all may be part of the variant)
  307. int v = (int)((leastSigBits & 0xE000000000000000L) >> 61);
  308. if( (v & 0x04) == 0 ) // msb of the variant is 0
  309. return 0;
  310. if( (v & 0x02) == 0 ) // variant is 0 1 (Leach-Salz)
  311. return 2;
  312. return v; // 6 or 7
  313. }
  314. /**
  315. * Returns the version # of the UUID.
  316. *
  317. * Valid version numbers for a variant 2 UUID are:
  318. * 1 = Time based UUID
  319. * 2 = DCE security UUID
  320. * 3 = Name-based UUID using MD5 hashing
  321. * 4 = Randomly generated UUID
  322. * 5 = Name-based UUID using SHA-1 hashing
  323. *
  324. * @return the version number
  325. */
  326. public int version()
  327. {
  328. return (int)((mostSigBits & 0xF000L) >> 12);
  329. }
  330. }