openjpa-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From kwsut...@apache.org
Subject svn commit: r472597 - in /incubator/openjpa/trunk/openjpa-lib/src: main/java/org/apache/openjpa/lib/util/Bytes.java main/java/org/apache/openjpa/lib/util/UUIDGenerator.java test/java/org/apache/openjpa/lib/util/TestUUIDGenerator.java
Date Wed, 08 Nov 2006 19:10:57 GMT
Author: kwsutter
Date: Wed Nov  8 11:10:56 2006
New Revision: 472597

URL: http://svn.apache.org/viewvc?view=rev&rev=472597
Log:
Replace the UUIDGenerator with an implementation based on the Apache Commons Id implementation.
 This change removes the LGPL implication from the original implementation.

Added:
    incubator/openjpa/trunk/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/Bytes.java
Modified:
    incubator/openjpa/trunk/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/UUIDGenerator.java
    incubator/openjpa/trunk/openjpa-lib/src/test/java/org/apache/openjpa/lib/util/TestUUIDGenerator.java

Added: incubator/openjpa/trunk/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/Bytes.java
URL: http://svn.apache.org/viewvc/incubator/openjpa/trunk/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/Bytes.java?view=auto&rev=472597
==============================================================================
--- incubator/openjpa/trunk/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/Bytes.java
(added)
+++ incubator/openjpa/trunk/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/Bytes.java
Wed Nov  8 11:10:56 2006
@@ -0,0 +1,164 @@
+/*
+ * Copyright 2003-2006 The Apache Software Foundation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.openjpa.lib.util;
+
+/**
+ * This class came from the Apache Commons Id sandbox project in support
+ * of the UUIDGenerator implementation.
+ *
+ * <p>Static methods for managing byte arrays (all methods follow Big
+ * Endian order where most significant bits are in front).</p>
+ *
+ */
+public final class Bytes {
+
+    /**
+     * <p>Hide constructor in utility class.</p>
+     */
+    private Bytes() {
+    }
+
+    /**
+     * Appends two bytes array into one.
+     *
+     * @param a A byte[].
+     * @param b A byte[].
+     * @return A byte[].
+     */
+    public static byte[] append(byte[] a, byte[] b) {
+        byte[] z = new byte[a.length + b.length];
+        System.arraycopy(a, 0, z, 0, a.length);
+        System.arraycopy(b, 0, z, a.length, b.length);
+        return z;
+    }
+
+    /**
+     * Returns a 8-byte array built from a long.
+     *
+     * @param n The number to convert.
+     * @return A byte[].
+     */
+    public static byte[] toBytes(long n) {
+        return toBytes(n, new byte[8]);
+    }
+
+    /**
+     * Build a 8-byte array from a long.  No check is performed on the
+     * array length.
+     *
+     * @param n The number to convert.
+     * @param b The array to fill.
+     * @return A byte[].
+     */
+    public static byte[] toBytes(long n, byte[] b) {
+        b[7] = (byte) (n);
+        n >>>= 8;
+        b[6] = (byte) (n);
+        n >>>= 8;
+        b[5] = (byte) (n);
+        n >>>= 8;
+        b[4] = (byte) (n);
+        n >>>= 8;
+        b[3] = (byte) (n);
+        n >>>= 8;
+        b[2] = (byte) (n);
+        n >>>= 8;
+        b[1] = (byte) (n);
+        n >>>= 8;
+        b[0] = (byte) (n);
+
+        return b;
+    }
+
+    /**
+     * Build a long from first 8 bytes of the array.
+     *
+     * @param b The byte[] to convert.
+     * @return A long.
+     */
+    public static long toLong(byte[] b) {
+        return ((((long) b[7]) & 0xFF)
+                + ((((long) b[6]) & 0xFF) << 8)
+                + ((((long) b[5]) & 0xFF) << 16)
+                + ((((long) b[4]) & 0xFF) << 24)
+                + ((((long) b[3]) & 0xFF) << 32)
+                + ((((long) b[2]) & 0xFF) << 40)
+                + ((((long) b[1]) & 0xFF) << 48)
+                + ((((long) b[0]) & 0xFF) << 56));
+    }
+
+    /**
+    * Compares two byte arrays for equality.
+    *
+    * @param a A byte[].
+    * @param b A byte[].
+    * @return True if the arrays have identical contents.
+    */
+    public static boolean areEqual(byte[] a, byte[] b) {
+        int aLength = a.length;
+        if (aLength != b.length) {
+            return false;
+        }
+
+        for (int i = 0; i < aLength; i++) {
+            if (a[i] != b[i]) {
+                return false;
+            }
+        }
+        return true;
+    }
+
+    /**
+     * <p>Compares two byte arrays as specified by <code>Comparable</code>.
+     *
+     * @param lhs - left hand value in the comparison operation.
+     * @param rhs - right hand value in the comparison operation.
+     * @return  a negative integer, zero, or a positive integer as <code>lhs</code>
+     *  is less than, equal to, or greater than <code>rhs</code>.
+     */
+    public static int compareTo(byte[] lhs, byte[] rhs) {
+        if (lhs == rhs) {
+            return 0;
+        }
+        if (lhs == null) {
+            return -1;
+        }
+        if (rhs == null) {
+            return +1;
+        }
+        if (lhs.length != rhs.length) {
+            return ((lhs.length < rhs.length) ? -1 : +1);
+        }
+        for (int i = 0; i < lhs.length; i++) {
+            if (lhs[i] < rhs[i]) {
+                return -1;
+            } else if (lhs[i] > rhs[i]) {
+                return 1;
+            }
+        }
+        return 0;
+    }
+
+    /**
+     * Build a short from first 2 bytes of the array.
+     *
+     * @param b The byte[] to convert.
+     * @return A short.
+     */
+    public static short toShort(byte[] b) {
+        return  (short) ((b[1] & 0xFF) + ((b[0] & 0xFF) << 8));
+    }
+}

Modified: incubator/openjpa/trunk/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/UUIDGenerator.java
URL: http://svn.apache.org/viewvc/incubator/openjpa/trunk/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/UUIDGenerator.java?view=diff&rev=472597&r1=472596&r2=472597
==============================================================================
--- incubator/openjpa/trunk/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/UUIDGenerator.java
(original)
+++ incubator/openjpa/trunk/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/UUIDGenerator.java
Wed Nov  8 11:10:56 2006
@@ -23,18 +23,18 @@
 import org.apache.commons.lang.exception.NestableRuntimeException;
 
 /**
- * UUID value generator. Based on the time-based generator in the LGPL
- * project:<br /> 
- * http://www.doomdark.org/doomdark/proj/jug/<br />
+ * UUID value generator.  Based on the time-based generator in the Apache
+ * Commons Id project:  http://jakarta.apache.org/commons/sandbox/id/uuid.html
+ *
  * The code has been vastly simplified and modified to replace the ethernet
  * address of the host machine with the IP, since we do not want to require
  * native libs and Java cannot access the MAC address directly.
- * Aside from the above modification, implements the IETF UUID draft
- * specification, found here:<br />
+ *
+ * In spirit, implements the IETF UUID draft specification, found here:<br />
  * http://www1.ics.uci.edu/~ejw/authoring/uuid-guid/draft-leach-uuids-guids-01
  * .txt
  *
- * @author Abe White
+ * @author Abe White, Kevin Sutter
  * @nojavadoc
  * @since 0.3.3
  */
@@ -48,13 +48,21 @@
     private static final byte IDX_TIME_SEQ = 8;
     private static final byte IDX_VARIATION = 8; // multiplexed
 
+    // indexes and lengths within the timestamp for certain boundaries
+    private static final byte TS_TIME_LO_IDX = 4;
+    private static final byte TS_TIME_LO_LEN = 4;
+    private static final byte TS_TIME_MID_IDX = 2;
+    private static final byte TS_TIME_MID_LEN = 2;
+    private static final byte TS_TIME_HI_IDX = 0;
+    private static final byte TS_TIME_HI_LEN = 2;
+
     // offset to move from 1/1/1970, which is 0-time for Java, to gregorian
     // 0-time 10/15/1582, and multiplier to go from 100nsec to msec units
     private static final long GREG_OFFSET = 0x01b21dd213814000L;
     private static final long MILLI_MULT = 10000L;
 
-    // type of UUID; is this part of the spec?
-    private final static byte TYPE_TIME_BASED = 1;
+    // type of UUID -- time based
+    private final static byte TYPE_TIME_BASED = 0x10;
 
     // random number generator used to reduce conflicts with other JVMs, and
     // hasher for strings.  note that secure random is very slow the first time
@@ -65,18 +73,23 @@
     // the MAC address is usually 6 bytes
     private static final byte[] IP;
 
-    // counter is initialized not to 0 but to a random 8-bit number, and each
-    // time clock changes, lowest 8-bits of counter are preserved. the purpose
-    // is to reduce chances of multi-JVM collisions without reducing perf
-    // awhite: I don't really understand this precaution, but it was in the
-    // original algo
+    // counter is initialized to 0 and is incremented for each uuid request
+    // within the same timestamp window.
     private static int _counter;
 
-    // last used millis time, and a randomized sequence that gets reset
-    // whenever the time is reset
-    private static long _last = 0L;
-    private static byte[] _seq = new byte[2];
+    // current timestamp (used to detect multiple uuid requests within same
+    // timestamp)
+    private static long _currentMillis;
+
+    // last used millis time, and a semi-random sequence that gets reset
+    // when it overflows
+    private static long _lastMillis = 0L;
+    private static final int MAX_14BIT = 0x3FFF;
+    private static short _seq = (short)RANDOM.nextInt(MAX_14BIT);
 
+    /*
+     * Static initializer to get the IP address of the host machine.
+     */
     static {
         byte[] ip = null;
         try {
@@ -88,8 +101,6 @@
         IP = new byte[6];
         RANDOM.nextBytes(IP);
         System.arraycopy(ip, 0, IP, 2, ip.length);
-
-        resetTime();
     }
 
     /**
@@ -100,54 +111,35 @@
         byte[] uuid = new byte[16];
         System.arraycopy(IP, 0, uuid, 10, IP.length);
 
-        // set time info
-        long now = System.currentTimeMillis();
+        // Set time info.  Have to do this processing within a synchronized
+        // block because of the statics...
+        long now = 0;
         synchronized (UUIDGenerator.class) {
-            // if time moves backwards somehow, spec says to reset randomization
-            if (now < _last)
-                resetTime();
-            else if (now == _last && _counter == MILLI_MULT) {
-                // if we run out of slots in this milli, increment
-                now++;
-                _last = now;
-                _counter &= 0xFF; // rest counter?
-            } else if (now > _last) {
-                _last = now;
-                _counter &= 0xFF; // rest counter?
-            }
-
-            // translate timestamp to 100ns slot since beginning of gregorian
-            now *= MILLI_MULT;
-            now += GREG_OFFSET;
-
-            // add nano slot
-            now += _counter;
-            _counter++; // increment counter
-
-            // set random info
-            for (int i = 0; i < _seq.length; i++)
-                uuid[IDX_TIME_SEQ + i] = _seq[i];
+            // Get the time to use for this uuid.  This method has the side
+            // effect of modifying the clock sequence, as well.
+            now = getTime();
+
+            // Insert the resulting clock sequence into the uuid
+            uuid[IDX_TIME_SEQ] = (byte) ((_seq & 0x3F00) >>> 8);
+            uuid[IDX_VARIATION] |= 0x80;
+            uuid[IDX_TIME_SEQ+1] = (byte) (_seq & 0xFF);
+
         }
 
         // have to break up time because bytes are spread through uuid
-        int timeHi = (int) (now >>> 32);
-        int timeLo = (int) now;
+        byte[] timeBytes = Bytes.toBytes(now);
 
-        uuid[IDX_TIME_HI] = (byte) (timeHi >>> 24);
-        uuid[IDX_TIME_HI + 1] = (byte) (timeHi >>> 16);
-        uuid[IDX_TIME_MID] = (byte) (timeHi >>> 8);
-        uuid[IDX_TIME_MID + 1] = (byte) timeHi;
-
-        uuid[IDX_TIME_LO] = (byte) (timeLo >>> 24);
-        uuid[IDX_TIME_LO + 1] = (byte) (timeLo >>> 16);
-        uuid[IDX_TIME_LO + 2] = (byte) (timeLo >>> 8);
-        uuid[IDX_TIME_LO + 3] = (byte) timeLo;
-
-        // set type info
-        uuid[IDX_TYPE] &= (byte) 0x0F;
-        uuid[IDX_TYPE] |= (byte) (TYPE_TIME_BASED << 4);
-        uuid[IDX_VARIATION] &= 0x3F;
-        uuid[IDX_VARIATION] |= 0x80;
+        // Copy time low
+        System.arraycopy(timeBytes, TS_TIME_LO_IDX, uuid, IDX_TIME_LO,
+                TS_TIME_LO_LEN);
+        // Copy time mid
+        System.arraycopy(timeBytes, TS_TIME_MID_IDX, uuid, IDX_TIME_MID,
+                TS_TIME_MID_LEN);
+        // Copy time hi
+        System.arraycopy(timeBytes, TS_TIME_HI_IDX, uuid, IDX_TIME_HI,
+                TS_TIME_HI_LEN);
+        //Set version (time-based)
+        uuid[IDX_TYPE] |= TYPE_TIME_BASED; // 0001 0000
 
         return uuid;
     }
@@ -172,16 +164,58 @@
     }
 
     /**
-     * Reset the random time sequence and counter. Must be called from
-     * synchronized code.
+     * Get the timestamp to be used for this uuid.  Must be called from
+     * a synchronized block.
+     *
+     * @return long timestamp
      */
-    private static void resetTime() {
-        _last = 0L;
-        RANDOM.nextBytes(_seq);
-
-        // awhite: I don't understand this; copied from original algo
-        byte[] tmp = new byte[1];
-        RANDOM.nextBytes(tmp);
-        _counter = tmp[0] & 0xFF;
+    private static long getTime() {
+        long newTime = getUUIDTime();
+        if (newTime <= _lastMillis) {
+            incrementSequence();
+        }
+        _lastMillis = newTime;
+        return newTime;
     }
+
+    /**
+     * Gets the appropriately modified timestamep for the UUID.  Must be called
+     * from a synchronized block.
+     *
+     * @return long timestamp in 100ns intervals since the Gregorian change
+     * offset
+     */
+    private static long getUUIDTime() {
+        if (_currentMillis != System.currentTimeMillis()) {
+            _currentMillis = System.currentTimeMillis();
+            _counter = 0;  // reset counter
+        }
+
+        // check to see if we have created too many uuid's for this timestamp
+        if (_counter + 1 >= MILLI_MULT) {
+            // Original algorithm threw exception.  Seemed like overkill.
+            // Let's just increment the timestamp instead and start over...
+            _currentMillis++;
+            _counter = 0;
+        }
+
+        // calculate time as current millis plus offset times 100 ns ticks
+        long currentTime = (_currentMillis + GREG_OFFSET) * MILLI_MULT;
+
+        // return the uuid time plus the artificial tick counter incremented
+        return currentTime + _counter++;
+    }
+
+    /**
+     * Increments the clock sequence for this uuid.  Must be called from a
+     * synchronized block.
+     */
+    private static void incrementSequence() {
+        // increment, but if it's greater than its 14-bits, reset it
+        if (++_seq > MAX_14BIT) {
+            _seq = (short)RANDOM.nextInt(MAX_14BIT);  // semi-random
+        }
+    }
+
+
 }

Modified: incubator/openjpa/trunk/openjpa-lib/src/test/java/org/apache/openjpa/lib/util/TestUUIDGenerator.java
URL: http://svn.apache.org/viewvc/incubator/openjpa/trunk/openjpa-lib/src/test/java/org/apache/openjpa/lib/util/TestUUIDGenerator.java?view=diff&rev=472597&r1=472596&r2=472597
==============================================================================
--- incubator/openjpa/trunk/openjpa-lib/src/test/java/org/apache/openjpa/lib/util/TestUUIDGenerator.java
(original)
+++ incubator/openjpa/trunk/openjpa-lib/src/test/java/org/apache/openjpa/lib/util/TestUUIDGenerator.java
Wed Nov  8 11:10:56 2006
@@ -26,13 +26,13 @@
 
     public void testUniqueString() {
         Set seen = new HashSet();
-        for (int i = 0; i < 1000; i++)
+        for (int i = 0; i < 10000; i++)
             assertTrue(seen.add(UUIDGenerator.nextString()));
     }
 
     public void testUniqueHex() {
         Set seen = new HashSet();
-        for (int i = 0; i < 1000; i++)
+        for (int i = 0; i < 10000; i++)
             assertTrue(seen.add(UUIDGenerator.nextHex()));
     }
 }



Mime
View raw message