Generates a UUID : UUID GUID « Development Class « Java






Generates a UUID

     
/**************************************************************************************
 * Copyright (c) Jonas Bonr, Alexandre Vasseur. All rights reserved.                 *
 * http://aspectwerkz.codehaus.org                                                    *
 * ---------------------------------------------------------------------------------- *
 * The software in this package is published under the terms of the LGPL license      *
 * a copy of which has been included with this distribution in the license.txt file.  *
 **************************************************************************************/


import java.net.InetAddress;
import java.security.SecureRandom;

/**
 * Generates a UUID. <p/>A Universally Unique Identifier (UUID) is a 128 bit number generated according to an algorithm
 * that is garanteed to be unique in time A space from all other UUIDs.
 *
 * @author <a href="mailto:jboner@codehaus.org">Jonas Bonr </a>
 */
public class UuidGenerator {
    /**
     * Random seeder.
     */
    private static SecureRandom s_seeder = null;

    /**
     * Mid value, needed for calculation.
     */
    private static String s_midValue = null;

    /**
     * Defines if the generator is initialized or not.
     */
    private static boolean s_initialized = false;

    /**
     * Private constructor to prevent subclassing
     */
    private UuidGenerator() {
    }

    /**
     * Returns a unique uuid.
     *
     * @param obj the calling object (this)
     * @return a unique uuid
     */
    public static String generate(Object obj) {
        if (!s_initialized) {
            initialize(obj);
        }
        long timeNow = System.currentTimeMillis();

        // get int value as unsigned
        int timeLow = (int) timeNow & 0xFFFFFFFF;
        int node = s_seeder.nextInt();
        return (hexFormat(timeLow, 8) + s_midValue + hexFormat(node, 8));
    }

    /**
     * Initializes the factory.
     *
     * @param obj
     */
    private synchronized static void initialize(final Object obj) {
        try {
            InetAddress inet = InetAddress.getLocalHost();
            byte[] bytes = inet.getAddress();
            String hexInetAddress = hexFormat(getInt(bytes), 8);
            String thisHashCode = hexFormat(System.identityHashCode(obj), 8);
            s_midValue = hexInetAddress + thisHashCode;
            s_seeder = new SecureRandom();
            s_seeder.nextInt();
        } catch (java.net.UnknownHostException e) {
            throw new Error("can not initialize the UuidGenerator generator");
        }
        s_initialized = true;
    }

    /**
     * Utility method.
     *
     * @param abyte
     * @return
     */
    private static int getInt(final byte[] abyte) {
        int i = 0;
        int j = 24;
        for (int k = 0; j >= 0; k++) {
            int l = abyte[k] & 0xff;
            i += (l << j);
            j -= 8;
        }
        return i;
    }

    /**
     * Utility method.
     *
     * @param i
     * @param j
     * @return
     */
    private static String hexFormat(final int i, final int j) {
        String s = Integer.toHexString(i);
        return padHex(s, j) + s;
    }

    /**
     * Utility method.
     *
     * @param str
     * @param i
     * @return
     */
    private static String padHex(final String str, final int i) {
        StringBuffer buf = new StringBuffer();
        if (str.length() < i) {
            for (int j = 0; j < (i - str.length()); j++) {
                buf.append('0');
            }
        }
        return buf.toString();
    }
}

   
    
    
    
    
  








Related examples in the same category

1.Random GUID
2.Algorithm for generating Random GUID
3.Get a unique identifier Using java.rmi.dgc.VMID
4.Using java.util.UUID
5.Create your own basic UUID
6.Session ID generator
7.UUID generator from Sun Microsystems
8.UUID generator from http://www1.ics.uci.edu
9.Using java.util.concurrent.AtomicLong: A numerical id, start at zero and increment by one.
10.A 32 byte GUID generator
11.A unique identifier
12.Generate pseudo-GUID sequences
13.Generates random UUIDs
14.Generator for Globally unique Strings
15.ID generator
16.Simple Id Generator
17.UUID generation
18.UUID generator of 32 bytes long values
19.Simple Long Id Generator
20.Long Sequence Generator
21.UUID generator
22.Thread-safe version of the Axiom UUIDGenerator
23.Convert an array of bytes into a List of Strings using UTF-8.
24.Your own UUID
25.Your own UUID 2
26.Create GUIDs according to the principles at http://www.opengroup.org/dce/info/draft-leach-uuids-guids-01.txt.
27.Get Unique Id