Java/Development Class/UUID GUID

Материал из Java эксперт
Перейти к: навигация, поиск

A 32 byte GUID generator

  
/*************************************************************************
 *                                                                       *
 *  EJBCA: The OpenSource Certificate Authority                          *
 *                                                                       *
 *  This software is free software; you can redistribute it and/or       *
 *  modify it under the terms of the GNU Lesser General Public           *
 *  License as published by the Free Software Foundation; either         *
 *  version 2.1 of the License, or any later version.                    *
 *                                                                       *
 *  See terms of license at gnu.org.                                     *
 *                                                                       *
 *************************************************************************/

/** Shamelessly ripped from generated XDoclet source, because I don"t want to generate util classes.
 * 
 * @author XDoclet.sf.net
 * @version $Id: GUIDGenerator.java 5585 2008-05-01 20:55:00Z anatom $
 */
public class GUIDGenerator {
     /** Cached per JVM server IP. */
     private static String hexServerIP = null;
     // initialise the secure random instance
     private static final java.security.SecureRandom seeder = new java.security.SecureRandom();
     
     /**
      * A 32 byte GUID generator (Globally Unique ID). These artificial keys SHOULD <strong>NOT </strong> be seen by the user,
      * not even touched by the DBA but with very rare exceptions, just manipulated by the database and the programs.
      *
      * Usage: Add an id field (type java.lang.String) to your EJB, and add setId(XXXUtil.generateGUID(this)); to the ejbCreate method.
      */
     public static final String generateGUID(Object o) {
         StringBuffer tmpBuffer = new StringBuffer(16);
         if (hexServerIP == null) {
             java.net.InetAddress localInetAddress = null;
             try {
                 localInetAddress = java.net.InetAddress.getLocalHost();
             } catch (java.net.UnknownHostException uhe) {
                 return null;
             }
             byte serverIP[] = localInetAddress.getAddress();
             hexServerIP = hexFormat(getInt(serverIP), 8);
         }
         String hashcode = hexFormat(System.identityHashCode(o), 8);
         tmpBuffer.append(hexServerIP);
         tmpBuffer.append(hashcode);
         long timeNow      = System.currentTimeMillis();
         int timeLow       = (int)timeNow & 0xFFFFFFFF;
         int node          = seeder.nextInt();
         StringBuffer guid = new StringBuffer(32);
         guid.append(hexFormat(timeLow, 8));
         guid.append(tmpBuffer.toString());
         guid.append(hexFormat(node, 8));
         return guid.toString();
     }
     
     private static int getInt(byte bytes[]) {
         int i = 0;
         int j = 24;
         for (int k = 0; j >= 0; k++) {
             int l = bytes[k] & 0xff;
             i += l << j;
             j -= 8;
         }
         return i;
     }
     private static String hexFormat(int i, int j) {
         String s = Integer.toHexString(i);
         return padHex(s, j) + s;
     }
     private static String padHex(String s, int i) {
         StringBuffer tmpBuffer = new StringBuffer();
         if (s.length() < i) {
             for (int j = 0; j < i - s.length(); j++) {
                 tmpBuffer.append("0");
             }
         }
         return tmpBuffer.toString();
     }
}





Algorithm for generating Random GUID

  
import java.security.*;
public class RandomGUIDdemo {
    // Generate 20 of "em!
    public static void main(String[] args) {
  for(int i=1; i<=20; i++) {
      RandomGUID myguid = new RandomGUID(false);
      System.out.println(i + " " + myguid.toString());
  }
    }
}

/*
 * RandomGUID
 * @version 1.2.1 11/05/02
 * @author Marc A. Mnich
 *
 * From www.JavaExchange.ru, Open Software licensing
 *
 * 11/05/02 -- Performance enhancement from Mike Dubman.  
 *             Moved InetAddr.getLocal to static block.  Mike has measured
 *             a 10 fold improvement in run time.
 * 01/29/02 -- Bug fix: Improper seeding of nonsecure Random object
 *             caused duplicate GUIDs to be produced.  Random object
 *             is now only created once per JVM.
 * 01/19/02 -- Modified random seeding and added new constructor
 *             to allow secure random feature.
 * 01/14/02 -- Added random function seeding with JVM run time
 *
 */
import java.net.*;
import java.util.*;
import java.security.*;
/*
 * In the multitude of java GUID generators, I found none that
 * guaranteed randomness.  GUIDs are guaranteed to be globally unique
 * by using ethernet MACs, IP addresses, time elements, and sequential
 * numbers.  GUIDs are not expected to be random and most often are
 * easy/possible to guess given a sample from a given generator.
 * SQL Server, for example generates GUID that are unique but
 * sequencial within a given instance.
 *
 * GUIDs can be used as security devices to hide things such as
 * files within a filesystem where listings are unavailable (e.g. files
 * that are served up from a Web server with indexing turned off).
 * This may be desireable in cases where standard authentication is not
 * appropriate. In this scenario, the RandomGUIDs are used as directories.
 * Another example is the use of GUIDs for primary keys in a database
 * where you want to ensure that the keys are secret.  Random GUIDs can
 * then be used in a URL to prevent hackers (or users) from accessing
 * records by guessing or simply by incrementing sequential numbers.
 *
 * There are many other possiblities of using GUIDs in the realm of
 * security and encryption where the element of randomness is important.
 * This class was written for these purposes but can also be used as a
 * general purpose GUID generator as well.
 *
 * RandomGUID generates truly random GUIDs by using the system"s
 * IP address (name/IP), system time in milliseconds (as an integer),
 * and a very large random number joined together in a single String
 * that is passed through an MD5 hash.  The IP address and system time
 * make the MD5 seed globally unique and the random number guarantees
 * that the generated GUIDs will have no discernable pattern and
 * cannot be guessed given any number of previously generated GUIDs.
 * It is generally not possible to access the seed information (IP, time,
 * random number) from the resulting GUIDs as the MD5 hash algorithm
 * provides one way encryption.
 *
 * ----> Security of RandomGUID: <-----
 * RandomGUID can be called one of two ways -- with the basic java Random
 * number generator or a cryptographically strong random generator
 * (SecureRandom).  The choice is offered because the secure random
 * generator takes about 3.5 times longer to generate its random numbers
 * and this performance hit may not be worth the added security
 * especially considering the basic generator is seeded with a
 * cryptographically strong random seed.
 *
 * Seeding the basic generator in this way effectively decouples
 * the random numbers from the time component making it virtually impossible
 * to predict the random number component even if one had absolute knowledge
 * of the System time.  Thanks to Ashutosh Narhari for the suggestion
 * of using the static method to prime the basic random generator.
 *
 * Using the secure random option, this class compies with the statistical
 * random number generator tests specified in FIPS 140-2, Security
 * Requirements for Cryptographic Modules, secition 4.9.1.
 *
 * I converted all the pieces of the seed to a String before handing
 * it over to the MD5 hash so that you could print it out to make
 * sure it contains the data you expect to see and to give a nice
 * warm fuzzy.  If you need better performance, you may want to stick
 * to byte[] arrays.
 *
 * I believe that it is important that the algorithm for
 * generating random GUIDs be open for inspection and modification.
 * This class is free for all uses.
 *
 *
 * - Marc
 */
public class RandomGUID extends Object {
    public String valueBeforeMD5 = "";
    public String valueAfterMD5 = "";
    private static Random myRand;
    private static SecureRandom mySecureRand;
    private static String s_id;
    /*
     * Static block to take care of one time secureRandom seed.
     * It takes a few seconds to initialize SecureRandom.  You might
     * want to consider removing this static block or replacing
     * it with a "time since first loaded" seed to reduce this time.
     * This block will run only once per JVM instance.
     */
    static {
        mySecureRand = new SecureRandom();
        long secureInitializer = mySecureRand.nextLong();
        myRand = new Random(secureInitializer);
        try {
            s_id = InetAddress.getLocalHost().toString();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }

    /*
     * Default constructor.  With no specification of security option,
     * this constructor defaults to lower security, high performance.
     */
    public RandomGUID() {
        getRandomGUID(false);
    }
    /*
     * Constructor with security option.  Setting secure true
     * enables each random number generated to be cryptographically
     * strong.  Secure false defaults to the standard Random function seeded
     * with a single cryptographically strong random number.
     */
    public RandomGUID(boolean secure) {
        getRandomGUID(secure);
    }
    /*
     * Method to generate the random GUID
     */
    private void getRandomGUID(boolean secure) {
        MessageDigest md5 = null;
        StringBuffer sbValueBeforeMD5 = new StringBuffer();
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            System.out.println("Error: " + e);
        }
        try {
            long time = System.currentTimeMillis();
            long rand = 0;
            if (secure) {
                rand = mySecureRand.nextLong();
            } else {
                rand = myRand.nextLong();
            }
            // This StringBuffer can be a long as you need; the MD5
            // hash will always return 128 bits.  You can change
            // the seed to include anything you want here.
            // You could even stream a file through the MD5 making
            // the odds of guessing it at least as great as that
            // of guessing the contents of the file!
            sbValueBeforeMD5.append(s_id);
            sbValueBeforeMD5.append(":");
            sbValueBeforeMD5.append(Long.toString(time));
            sbValueBeforeMD5.append(":");
            sbValueBeforeMD5.append(Long.toString(rand));
            valueBeforeMD5 = sbValueBeforeMD5.toString();
            md5.update(valueBeforeMD5.getBytes());
            byte[] array = md5.digest();
            StringBuffer sb = new StringBuffer();
            for (int j = 0; j < array.length; ++j) {
                int b = array[j] & 0xFF;
                if (b < 0x10) sb.append("0");
                sb.append(Integer.toHexString(b));
            }
            valueAfterMD5 = sb.toString();
        } catch (Exception e) {
            System.out.println("Error:" + e);
        }
    }

    /*
     * Convert to the standard format for GUID
     * (Useful for SQL Server UniqueIdentifiers, etc.)
     * Example: C2FEEEAC-CFCD-11D1-8B05-00600806D9B6
     */
    public String toString() {
        String raw = valueAfterMD5.toUpperCase();
        StringBuffer sb = new StringBuffer();
        sb.append(raw.substring(0, 8));
        sb.append("-");
        sb.append(raw.substring(8, 12));
        sb.append("-");
        sb.append(raw.substring(12, 16));
        sb.append("-");
        sb.append(raw.substring(16, 20));
        sb.append("-");
        sb.append(raw.substring(20));
        return sb.toString();
    }
    /*
     * Demonstraton and self test of class
     */
    public static void main(String args[]) {
        for (int i=0; i< 100; i++) {
      RandomGUID myGUID = new RandomGUID();
      System.out.println("Seeding String=" + myGUID.valueBeforeMD5);
      System.out.println("rawGUID=" + myGUID.valueAfterMD5);
      System.out.println("RandomGUID=" + myGUID.toString());
        }
    }
}





A unique identifier

  
/* 
 * This file is part of the Echo Web Application Framework (hereinafter "Echo").
 * Copyright (C) 2002-2009 NextApp, Inc.
 *
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (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.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 */

/**
 * A unique identifier.
 */
public class Uid {
    private static final String machineIdString = Integer.toHexString(new Object().hashCode());
    private static int globalCount = 0;
    
    private final int count = ++globalCount;
    private final long time = System.currentTimeMillis();
    
    /**
     * Generates a new identifier String.
     */
    public static final String generateUidString() {
        String idString = new Uid().toString();
        return idString;
    }
    /**
     * Generates a new identifier.
     */
    private Uid() {
        super();
    }
    
    /**
     * @see java.lang.Object#toString()
     */
    public String toString() {
        String timeString = Long.toHexString(time);
        String countString = Integer.toHexString(count);
        
        return machineIdString + "_" + timeString + "_" + countString;
    }
}





Create your own basic UUID

  
/*
 Derby - Class org.apache.derby.impl.services.uuid.BasicUUID
 Licensed to the Apache Software Foundation (ASF) under one or more
 contributor license agreements.  See the NOTICE file distributed with
 this work for additional information regarding copyright ownership.
 The ASF licenses this file to you 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.
 */
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.io.StringReader;
public class BasicUUID {
  /*
   * * Fields of BasicUUID
   */
  private long majorId; // only using 48 bits
  private long timemillis;
  private int sequence;
  /*
   * * Methods of BasicUUID
   */
  /**
   * Constructor only called by BasicUUIDFactory.
   */
  public BasicUUID(long majorId, long timemillis, int sequence) {
    this.majorId = majorId;
    this.timemillis = timemillis;
    this.sequence = sequence;
  }
  /**
   * Constructor only called by BasicUUIDFactory. Constructs a UUID from the
   * string representation produced by toString.
   * 
   * @see BasicUUID#toString
   */
  public BasicUUID(String uuidstring) {
    StringReader sr = new StringReader(uuidstring);
    sequence = (int) readMSB(sr);
    long ltimemillis = readMSB(sr) << 32;
    ltimemillis += readMSB(sr) << 16;
    ltimemillis += readMSB(sr);
    timemillis = ltimemillis;
    majorId = readMSB(sr);
  }
  /**
   * Constructor only called by BasicUUIDFactory. Constructs a UUID from the
   * byte array representation produced by toByteArrayio.
   * 
   * @see BasicUUID#toByteArray
   */
  public BasicUUID(byte[] b) {
    int lsequence = 0;
    for (int ix = 0; ix < 4; ix++) {
      lsequence = lsequence << 8;
      lsequence = lsequence | (0xff & b[ix]);
    }
    long ltimemillis = 0;
    for (int ix = 4; ix < 10; ix++) {
      ltimemillis = ltimemillis << 8;
      ltimemillis = ltimemillis | (0xff & b[ix]);
    }
    long linetaddr = 0;
    for (int ix = 10; ix < 16; ix++) {
      linetaddr = linetaddr << 8;
      linetaddr = linetaddr | (0xff & b[ix]);
    }
    sequence = lsequence;
    timemillis = ltimemillis;
    majorId = linetaddr;
  }
  /*
   * Formatable methods
   */
  // no-arg constructor, required by Formatable
  public BasicUUID() {
    super();
  }
  /**
   * Write this out.
   * 
   * @exception IOException
   *              error writing to log stream
   */
  public void writeExternal(ObjectOutput out) throws IOException {
    // RESOLVE: write out the byte array instead?
    out.writeLong(majorId);
    out.writeLong(timemillis);
    out.writeInt(sequence);
  }
  /**
   * Read this in
   * 
   * @exception IOException
   *              error reading from log stream
   */
  public void readExternal(ObjectInput in) throws IOException {
    majorId = in.readLong();
    timemillis = in.readLong();
    sequence = in.readInt();
  }
  private static void writeMSB(char[] data, int offset, long value, int nbytes) {
    for (int i = nbytes - 1; i >= 0; i--) {
      long b = (value & (255L << (8 * i))) >>> (8 * i);
      int c = (int) ((b & 0xf0) >> 4);
      data[offset++] = (char) (c < 10 ? c + "0" : (c - 10) + "a");
      c = (int) (b & 0x0f);
      data[offset++] = (char) (c < 10 ? c + "0" : (c - 10) + "a");
    }
  }
  /**
   * Read a long value, msb first, from its character representation in the
   * string reader, using "-" or end of string to delimit.
   */
  private static long readMSB(StringReader sr) {
    long value = 0;
    try {
      int c;
      while ((c = sr.read()) != -1) {
        if (c == "-")
          break;
        value <<= 4;
        int nibble;
        if (c <= "9")
          nibble = c - "0";
        else if (c <= "F")
          nibble = c - "A" + 10;
        else
          nibble = c - "a" + 10;
        value += nibble;
      }
    } catch (Exception e) {
    }
    return value;
  }
  /*
   * * Methods of UUID
   */
  /**
   * Implement value equality.
   * 
   */
  public boolean equals(Object otherObject) {
    if (!(otherObject instanceof BasicUUID))
      return false;
    BasicUUID other = (BasicUUID) otherObject;
    return (this.sequence == other.sequence) && (this.timemillis == other.timemillis)
        && (this.majorId == other.majorId);
  }
  /**
   * Provide a hashCode which is compatible with the equals() method.
   */
  public int hashCode() {
    long hc = majorId ^ timemillis;
    return sequence ^ ((int) (hc >> 4));
  }
  /**
   * Produce a string representation of this UUID which can be passed to
   * UUIDFactory.recreateUUID later on to reconstruct it. The funny
   * representation is designed to (sort of) match the format of Microsoft"s
   * UUIDGEN utility.
   */
  public String toString() {
    return stringWorkhorse("-");
  }
  /**
   * Produce a string representation of this UUID which is suitable for use as a
   * unique ANSI identifier.
   */
  public String toANSIidentifier() {
    return "U" + stringWorkhorse("X");
  }
  /**
   * Private workhorse of the string making routines.
   * 
   * @param separator
   *          Character to separate number blocks. Null means do not include a
   *          separator.
   * 
   * @return string representation of UUID.
   */
  public String stringWorkhorse(char separator) {
    char[] data = new char[36];
    writeMSB(data, 0, (long) sequence, 4);
    int offset = 8;
    if (separator != 0)
      data[offset++] = separator;
    long ltimemillis = timemillis;
    writeMSB(data, offset, (ltimemillis & 0x0000ffff00000000L) >>> 32, 2);
    offset += 4;
    if (separator != 0)
      data[offset++] = separator;
    writeMSB(data, offset, (ltimemillis & 0x00000000ffff0000L) >>> 16, 2);
    offset += 4;
    if (separator != 0)
      data[offset++] = separator;
    writeMSB(data, offset, (ltimemillis & 0x000000000000ffffL), 2);
    offset += 4;
    if (separator != 0)
      data[offset++] = separator;
    writeMSB(data, offset, majorId, 6);
    offset += 12;
    return new String(data, 0, offset);
  }
  /**
   * Store this UUID in a byte array. Arrange the bytes in the UUID in the same
   * order the code which stores a UUID in a string does.
   * 
   * @see org.apache.derby.catalog.UUID#toByteArray
   */
  public byte[] toByteArray() {
    byte[] result = new byte[16];
    int lsequence = sequence;
    result[0] = (byte) (lsequence >>> 24);
    result[1] = (byte) (lsequence >>> 16);
    result[2] = (byte) (lsequence >>> 8);
    result[3] = (byte) lsequence;
    long ltimemillis = timemillis;
    result[4] = (byte) (ltimemillis >>> 40);
    result[5] = (byte) (ltimemillis >>> 32);
    result[6] = (byte) (ltimemillis >>> 24);
    result[7] = (byte) (ltimemillis >>> 16);
    result[8] = (byte) (ltimemillis >>> 8);
    result[9] = (byte) ltimemillis;
    long linetaddr = majorId;
    result[10] = (byte) (linetaddr >>> 40);
    result[11] = (byte) (linetaddr >>> 32);
    result[12] = (byte) (linetaddr >>> 24);
    result[13] = (byte) (linetaddr >>> 16);
    result[14] = (byte) (linetaddr >>> 8);
    result[15] = (byte) linetaddr;
    return result;
  }
  /**
   * Clone this UUID.
   * 
   * @return a copy of this UUID
   */
  public BasicUUID cloneMe() {
    return new BasicUUID(majorId, timemillis, sequence);
  }
  public String toHexString() {
    return stringWorkhorse((char) 0);
  }
}





Generate pseudo-GUID sequences

  
/* 
 * 
 * The ObjectStyle Group Software License, version 1.1
 * ObjectStyle Group - http://objectstyle.org/
 * 
 * Copyright (c) 2002-2005, Andrei (Andrus) Adamchik and individual authors
 * of the software. All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 * 
 * 3. The end-user documentation included with the redistribution, if any,
 *    must include the following acknowlegement:
 *    "This product includes software developed by independent contributors
 *    and hosted on ObjectStyle Group web site (http://objectstyle.org/)."
 *    Alternately, this acknowlegement may appear in the software itself,
 *    if and wherever such third-party acknowlegements normally appear.
 * 
 * 4. The names "ObjectStyle Group" and "Cayenne" must not be used to endorse
 *    or promote products derived from this software without prior written
 *    permission. For written permission, email
 *    "andrus at objectstyle dot org".
 * 
 * 5. Products derived from this software may not be called "ObjectStyle"
 *    or "Cayenne", nor may "ObjectStyle" or "Cayenne" appear in their
 *    names without prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED ``AS IS"" AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE OBJECTSTYLE GROUP OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * 
 * 
 * This software consists of voluntary contributions made by many
 * individuals and hosted on ObjectStyle Group web site.  For more
 * information on the ObjectStyle Group, please see
 * <http://objectstyle.org/>.
 */
import java.net.UnknownHostException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * helper class to generate pseudo-GUID sequences.
 * 
 * @author Andrus Adamchik
 */
public class IDUtil {
    
    private static final int BITMASK_0 = 0xff;
    private static final int BITMASK_1 = 0xff << 8;
    private static final int BITMASK_2 = 0xff << 16;
    private static final int BITMASK_3 = 0xff << 24;
    private static final int BITMASK_4 = 0xff << 32;
    private static final int BITMASK_5 = 0xff << 40;
    private static final int BITMASK_6 = 0xff << 48;
    private static final int BITMASK_7 = 0xff << 56;
    // this id sequence needs to be long enough to feel
    // the gap within the same timestamp millisecond
    private static volatile int currentId;
    private static MessageDigest md;
    private static byte[] ipAddress;
    static {
        try {
            md = MessageDigest.getInstance("MD5");
        }
        catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("Can"t initialize MessageDigest.", e);
        }
        try {
            ipAddress = java.net.InetAddress.getLocalHost().getAddress();
        }
        catch (UnknownHostException e) {
            // use loopback interface
            ipAddress = new byte[] {
                    127, 0, 0, 1
            };
        }
    }
    /**
     * Prints a byte value to a StringBuffer as a double digit hex value.
     * 
     * @since 1.2
     */
    public static void appendFormattedByte(StringBuffer buffer, byte byteValue) {
        final String digits = "0123456789ABCDEF";
        buffer.append(digits.charAt((byteValue >>> 4) & 0xF));
        buffer.append(digits.charAt(byteValue & 0xF));
    }
    /**
     * @param length the length of returned byte[]
     * @return A pseudo-unique byte array of the specified length. Length must be at least
     *         16 bytes, or an exception is thrown.
     * @since 1.0.2
     */
    public synchronized static byte[] pseudoUniqueByteSequence(int length) {
        if (length < 16) {
            throw new IllegalArgumentException(
                    "Can"t generate unique byte sequence shorter than 16 bytes: "
                            + length);
        }
        if (length == 16) {
            return pseudoUniqueByteSequence16();
        }
        byte[] bytes = new byte[length];
        for (int i = 0; i <= length - 16; i += 16) {
            byte[] nextSequence = pseudoUniqueByteSequence16();
            System.arraycopy(nextSequence, 0, bytes, i, 16);
        }
        // leftovers?
        int leftoverLen = length % 16;
        if (leftoverLen > 0) {
            byte[] nextSequence = pseudoUniqueByteSequence16();
            System.arraycopy(nextSequence, 0, bytes, length - leftoverLen, leftoverLen);
        }
        return bytes;
    }
    public synchronized static byte[] pseudoUniqueSecureByteSequence(int length) {
        if (length < 16) {
            throw new IllegalArgumentException(
                    "Can"t generate unique byte sequence shorter than 16 bytes: "
                            + length);
        }
        if (length == 16) {
            return pseudoUniqueSecureByteSequence16();
        }
        byte[] bytes = new byte[length];
        for (int i = 0; i <= length - 16; i += 16) {
            byte[] nextSequence = pseudoUniqueSecureByteSequence16();
            System.arraycopy(nextSequence, 0, bytes, i, 16);
        }
        // leftovers?
        int leftoverLen = length % 16;
        if (leftoverLen > 0) {
            byte[] nextSequence = pseudoUniqueSecureByteSequence16();
            System.arraycopy(nextSequence, 0, bytes, length - leftoverLen, leftoverLen);
        }
        return bytes;
    }
    public static final byte[] pseudoUniqueByteSequence8() {
        byte[] bytes = new byte[8];
        // bytes 0..2 - incrementing #
        // bytes 3..5 - timestamp high bytes
        // bytes 6..7 - IP address
        int nextInt = nextInt();
        bytes[0] = (byte) ((nextInt & (0xff << 16)) >>> 16);
        bytes[1] = (byte) ((nextInt & (0xff << 8)) >>> 8);
        bytes[2] = (byte) (nextInt & 0xff);
        // append 3 high bytes of timestamp
        long t = System.currentTimeMillis();
        bytes[3] = (byte) ((t & BITMASK_2) >>> 16);
        bytes[4] = (byte) ((t & BITMASK_1) >>> 8);
        bytes[5] = (byte) (t & BITMASK_0);
        // append 2 last bytes of IP address
        System.arraycopy(ipAddress, 2, bytes, 6, 2);
        return bytes;
    }
    /**
     * @return A pseudo unique 16-byte array.
     */
    public static final byte[] pseudoUniqueByteSequence16() {
        byte[] bytes = new byte[16];
        // bytes 0..3 - incrementing #
        // bytes 4..11 - timestamp
        // bytes 12..15 - IP address
        int nextInt = nextInt();
        bytes[0] = (byte) ((nextInt & BITMASK_3) >>> 24);
        bytes[1] = (byte) ((nextInt & BITMASK_2) >>> 16);
        bytes[2] = (byte) ((nextInt & BITMASK_1) >>> 8);
        bytes[3] = (byte) (nextInt & BITMASK_0);
        long t = System.currentTimeMillis();
        bytes[4] = (byte) ((t & BITMASK_7) >>> 56);
        bytes[5] = (byte) ((t & BITMASK_6) >>> 48);
        bytes[6] = (byte) ((t & BITMASK_5) >>> 40);
        bytes[7] = (byte) ((t & BITMASK_4) >>> 32);
        bytes[8] = (byte) ((t & BITMASK_3) >>> 24);
        bytes[9] = (byte) ((t & BITMASK_2) >>> 16);
        bytes[10] = (byte) ((t & BITMASK_1) >>> 8);
        bytes[11] = (byte) (t & BITMASK_0);
        System.arraycopy(ipAddress, 0, bytes, 12, 4);
        return bytes;
    }
    /**
     * @return A pseudo unique digested 16-byte array.
     */
    public static byte[] pseudoUniqueSecureByteSequence16() {
        byte[] bytes = pseudoUniqueByteSequence16();
        synchronized (md) {
            return md.digest(bytes);
        }
    }
    private static final int nextInt() {
        if (currentId == Integer.MAX_VALUE) {
            currentId = 0;
        }
        return currentId++;
    }
    private IDUtil() {
    }
}





Generates a UUID

  
/**************************************************************************************
 * Copyright (c) Jonas Bon�r, 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 
 */
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();
    }
}





Generates random UUIDs

  
/* 
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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.
 *
 */
import java.security.SecureRandom;
/**
 *
 * RandomUuidFactory is a {@linkplain UuidFactory UuidFactory} that generates 
 * random UUIDs. This implementation uses the JDK"s java.security.SecureRandom 
 * to generate sufficiently random values for the UUIDs.
 * <br><br>
 * This class is a singleton, so it must be constructed through the static 
 * getInstance() method.
 *
 * @author Dan Jemiolo (danj)
 *
 */
public class RandomUuidFactory 
{
    private static final RandomUuidFactory _SINGLETON = new RandomUuidFactory();
    
    private static final char[] _HEX_VALUES = new char[] {
            "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", 
            "a", "b", "c", "d", "e", "f"
    };
    
    //
    // Used to create all random numbers - guarantees unique strings 
    // during the process lifetime
    //
    private static final SecureRandom _RNG = new SecureRandom();
    
    /**
     * 
     * The default constructor is explicit so we can make it private and 
     * require use of getInstance() for instantiation.
     * 
     * @see #getInstance()
     *
     */
    private RandomUuidFactory()
    {
        //
        // this is just to prevent instantiation
        //
    }
    
    /**
     * 
     * @return A unique UUID of the form <em>uuid:<b>X</b></em>, where 
     *        <b>X</b> is the generated value.
     *
     */
    public String createUUID()
    {
        //
        // first get 16 random bytes...
        //
        byte[] bytes = new byte[16];
        _RNG.nextBytes(bytes);
        
        StringBuffer uuid = new StringBuffer(41);
        uuid.append("uuid:");
        
        //
        // ...then we need to shift so they"re valid hex (0-9, a-f)
        //
        for (int n = 0; n < 16; ++n) 
        {
            //
            // (there"s really no elegant way to add the dashes...)
            //
            if (n == 4 || n == 6 || n == 8 || n == 10)
                uuid.append("-");
            
            //
            // shift the bits so they are proper hex
            //
            int hex = bytes[n] & 255;
            uuid.append(_HEX_VALUES[hex >> 4]);
            uuid.append(_HEX_VALUES[hex & 15]);
        }
        
        return uuid.toString();
    }
    
    /**
     * 
     * @return The singleton instance of this class.
     *
     */
    public static RandomUuidFactory getInstance()
    {
        return _SINGLETON;
    }
}





Generator for Globally unique Strings

  
/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You 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.
 */
import java.net.InetAddress;
import java.net.ServerSocket;

/**
 * Generator for Globally unique Strings.
 */
public class UuidGenerator {
    private static final String UNIQUE_STUB;
    private static int instanceCount;
    private static String hostName;
    private String seed;
    private long sequence;
    static {
        String stub = "";
        boolean canAccessSystemProps = true;
        try {
            SecurityManager sm = System.getSecurityManager();
            if (sm != null) {
                sm.checkPropertiesAccess();
            }
        } catch (SecurityException se) {
            canAccessSystemProps = false;
        }
        if (canAccessSystemProps) {
            try {
                hostName = InetAddress.getLocalHost().getHostName();
                ServerSocket ss = new ServerSocket(0);
                stub = "/" + ss.getLocalPort() + "-" + System.currentTimeMillis() + "/";
                Thread.sleep(100);
                ss.close();
            } catch (Exception ioe) {
                System.out.println("Could not generate unique stub" + ioe);
            }
        } else {
            hostName = "localhost";
            stub = "-1-" + System.currentTimeMillis() + "-";
        }
        UNIQUE_STUB = generateSanitizedId(stub);
    }
    public UuidGenerator(String prefix) {
        synchronized (UNIQUE_STUB) {
            this.seed = generateSanitizedId(prefix + UNIQUE_STUB + (instanceCount++) + "-");
        }
    }
    public UuidGenerator() {
        this("ID-" + hostName);
    }
    /**
     * As we have to find the hostname as a side-affect of generating a unique
     * stub, we allow it"s easy retrevial here
     * 
     * @return the local host name
     */
    public static String getHostName() {
        return hostName;
    }
    /**
     * Generate a unqiue id
     */
    public synchronized String generateId() {
        return this.seed + (this.sequence++);
    }
    /**
     * Generate a unique ID - that is friendly for a URL or file system
     * 
     * @return a unique id
     */
    public String generateSanitizedId() {
        return generateSanitizedId(generateId());
    }
    /**
     * Ensures that the id is friendly for a URL or file system
     *
     * @param id the unique id
     * @return the id as file friendly id
     */
    public static String generateSanitizedId(String id) {
        id = id.replace(":", "-");
        id = id.replace("_", "-");
        id = id.replace(".", "-");
        id = id.replace("/", "-");
        id = id.replace("\\", "-");
        return id;
    }
}





Get a unique identifier Using java.rmi.dgc.VMID

  
public class Main {
  public static void main(String arg[]) {
    System.out.println(new java.rmi.dgc.VMID().toString());
  }
}
//4129eb1d7419293f:-148094f1:11fc9788387:-8000





ID generator

  
/*
    GNU LESSER GENERAL PUBLIC LICENSE
    Copyright (C) 2006 The Lobo Project
    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Lesser General Public
    License as published by the Free Software Foundation; either
    version 2.1 of the License, or (at your option) any later version.
    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Lesser General Public License for more details.
    You should have received a copy of the GNU Lesser General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
    Contact info: lobochief@users.sourceforge.net
*/
/*
 * Created on Jun 7, 2005
 */
import java.util.*;
import java.util.logging.*;
import java.security.*;
import java.math.*;
import java.net.InetAddress;
/**
 * @author J. H. S.
 */
public class ID {
  private static final Random RANDOM1;
  private static final Random RANDOM2;
  private static final Random RANDOM3;
  private static final long globalProcessID;
    private static final Logger logger = Logger.getLogger(ID.class.getName());
    static {
    long time = System.currentTimeMillis();
    long nanoTime = System.nanoTime();
    long freeMemory = Runtime.getRuntime().freeMemory();
    long addressHashCode;
    try {
      InetAddress inetAddress;
      inetAddress = InetAddress.getLocalHost();
      addressHashCode = inetAddress.getHostName().hashCode() ^ inetAddress.getHostAddress().hashCode();
    } catch(Exception err) {
      logger.log(Level.WARNING, "Unable to get local host information.", err);
      addressHashCode = ID.class.hashCode();
    }   
    globalProcessID = time ^ nanoTime ^ freeMemory ^ addressHashCode;   
    RANDOM1 = new Random(time);
    RANDOM2 = new Random(nanoTime);
    RANDOM3 = new Random(addressHashCode ^ freeMemory);
  }
  
  private ID() {
  }
  
  public static long generateLong() {
    return Math.abs(RANDOM1.nextLong() ^ RANDOM2.nextLong() ^ RANDOM3.nextLong());
  }
  
  public static int generateInt() {
    return (int) generateLong();
  }
  
  public static byte[] getMD5Bytes(String content) {
        try {
            MessageDigest digest = MessageDigest.getInstance("MD5");
            return digest.digest(content.getBytes("UTF-8"));
        } catch (NoSuchAlgorithmException e) {
          throw new IllegalStateException(e);
    } catch(java.io.UnsupportedEncodingException uee) {
      throw new IllegalStateException(uee);
    }
  }
  public static String getHexString(byte[] bytes) {
    // This method cannot change even if it"s wrong.
    BigInteger bigInteger = BigInteger.ZERO;
    int shift = 0;
    for(int i = bytes.length; --i >= 0;) {
      BigInteger contrib = BigInteger.valueOf(bytes[i] & 0xFF);
      contrib = contrib.shiftLeft(shift);
      bigInteger = bigInteger.add(contrib);
      shift += 8;
    }
    return bigInteger.toString(16).toUpperCase();
  }
  
  /**
   * Gets a process ID that is nearly guaranteed to be globally unique.
   */
  public static long getGlobalProcessID() {
    return globalProcessID;
  }
  
  public static int random(int min, int max) {
    if(max <= min) {
      return min;
    }
    return Math.abs(RANDOM1.nextInt()) % (max - min) + min;
  }
}





Long Sequence Generator

  
/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You 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.
 */
public class LongSequenceGenerator {
    private long lastSequenceId;
    public synchronized long getNextSequenceId() {
        return ++lastSequenceId;
    }
    public synchronized long getLastSequenceId() {
        return lastSequenceId;
    }
    public synchronized void setLastSequenceId(long l) {
        lastSequenceId = l;
    }
}





Random GUID

  
/*
Seeding String=joeyin/137.82.182.17:1152652666395:-2655885710548956891
rawGUID=ba6d3836cb5cd6f2e1bf66620cfc1b08
RandomGUID=BA6D3836-CB5C-D6F2-E1BF-66620CFC1B08
Seeding String=joeyin/137.82.182.17:1152652666395:8837199841642248984
rawGUID=55acedd65014369f2500e07fcaeb7c8c
RandomGUID=55ACEDD6-5014-369F-2500-E07FCAEB7C8C
Seeding String=joeyin/137.82.182.17:1152652666395:4210831876271338242
rawGUID=7a96375818c113c70fe74bb4fdba30de
RandomGUID=7A963758-18C1-13C7-0FE7-4BB4FDBA30DE
Seeding String=joeyin/137.82.182.17:1152652666395:-5617766000346159985
rawGUID=822dfcd0217938364415e5809fe46a91
RandomGUID=822DFCD0-2179-3836-4415-E5809FE46A91
Seeding String=joeyin/137.82.182.17:1152652666395:-7651391643447498604
rawGUID=19d58fd5c185b286a0a8f3f36f396ebb
RandomGUID=19D58FD5-C185-B286-A0A8-F3F36F396EBB
Seeding String=joeyin/137.82.182.17:1152652666395:-621723023330936579
rawGUID=feff7e4a8e3459d428ec55f3ffb04005
RandomGUID=FEFF7E4A-8E34-59D4-28EC-55F3FFB04005
*/
/*
 * RandomGUID
 * @version 1.2.1 11/05/02
 * @author Marc A. Mnich
 *
 * From www.JavaExchange.ru, Open Software licensing
 *
 * 11/05/02 -- Performance enhancement from Mike Dubman.  
 *             Moved InetAddr.getLocal to static block.  Mike has measured
 *             a 10 fold improvement in run time.
 * 01/29/02 -- Bug fix: Improper seeding of nonsecure Random object
 *             caused duplicate GUIDs to be produced.  Random object
 *             is now only created once per JVM.
 * 01/19/02 -- Modified random seeding and added new constructor
 *             to allow secure random feature.
 * 01/14/02 -- Added random function seeding with JVM run time
 *
 */
import java.net.*;
import java.util.*;
import java.security.*;
/*
 * In the multitude of java GUID generators, I found none that
 * guaranteed randomness.  GUIDs are guaranteed to be globally unique
 * by using ethernet MACs, IP addresses, time elements, and sequential
 * numbers.  GUIDs are not expected to be random and most often are
 * easy/possible to guess given a sample from a given generator.
 * SQL Server, for example generates GUID that are unique but
 * sequencial within a given instance.
 *
 * GUIDs can be used as security devices to hide things such as
 * files within a filesystem where listings are unavailable (e.g. files
 * that are served up from a Web server with indexing turned off).
 * This may be desireable in cases where standard authentication is not
 * appropriate. In this scenario, the RandomGUIDs are used as directories.
 * Another example is the use of GUIDs for primary keys in a database
 * where you want to ensure that the keys are secret.  Random GUIDs can
 * then be used in a URL to prevent hackers (or users) from accessing
 * records by guessing or simply by incrementing sequential numbers.
 *
 * There are many other possiblities of using GUIDs in the realm of
 * security and encryption where the element of randomness is important.
 * This class was written for these purposes but can also be used as a
 * general purpose GUID generator as well.
 *
 * RandomGUID generates truly random GUIDs by using the system"s
 * IP address (name/IP), system time in milliseconds (as an integer),
 * and a very large random number joined together in a single String
 * that is passed through an MD5 hash.  The IP address and system time
 * make the MD5 seed globally unique and the random number guarantees
 * that the generated GUIDs will have no discernable pattern and
 * cannot be guessed given any number of previously generated GUIDs.
 * It is generally not possible to access the seed information (IP, time,
 * random number) from the resulting GUIDs as the MD5 hash algorithm
 * provides one way encryption.
 *
 * ----> Security of RandomGUID: <-----
 * RandomGUID can be called one of two ways -- with the basic java Random
 * number generator or a cryptographically strong random generator
 * (SecureRandom).  The choice is offered because the secure random
 * generator takes about 3.5 times longer to generate its random numbers
 * and this performance hit may not be worth the added security
 * especially considering the basic generator is seeded with a
 * cryptographically strong random seed.
 *
 * Seeding the basic generator in this way effectively decouples
 * the random numbers from the time component making it virtually impossible
 * to predict the random number component even if one had absolute knowledge
 * of the System time.  Thanks to Ashutosh Narhari for the suggestion
 * of using the static method to prime the basic random generator.
 *
 * Using the secure random option, this class compies with the statistical
 * random number generator tests specified in FIPS 140-2, Security
 * Requirements for Cryptographic Modules, secition 4.9.1.
 *
 * I converted all the pieces of the seed to a String before handing
 * it over to the MD5 hash so that you could print it out to make
 * sure it contains the data you expect to see and to give a nice
 * warm fuzzy.  If you need better performance, you may want to stick
 * to byte[] arrays.
 *
 * I believe that it is important that the algorithm for
 * generating random GUIDs be open for inspection and modification.
 * This class is free for all uses.
 *
 *
 * - Marc
 */
public class RandomGUID extends Object {

    public String valueBeforeMD5 = "";
    public String valueAfterMD5 = "";
    private static Random myRand;
    private static SecureRandom mySecureRand;
    private static String s_id;
    /*
     * Static block to take care of one time secureRandom seed.
     * It takes a few seconds to initialize SecureRandom.  You might
     * want to consider removing this static block or replacing
     * it with a "time since first loaded" seed to reduce this time.
     * This block will run only once per JVM instance.
     */
    static {
        mySecureRand = new SecureRandom();
        long secureInitializer = mySecureRand.nextLong();
        myRand = new Random(secureInitializer);
        try {
            s_id = InetAddress.getLocalHost().toString();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }

    /*
     * Default constructor.  With no specification of security option,
     * this constructor defaults to lower security, high performance.
     */
    public RandomGUID() {
        getRandomGUID(false);
    }
    /*
     * Constructor with security option.  Setting secure true
     * enables each random number generated to be cryptographically
     * strong.  Secure false defaults to the standard Random function seeded
     * with a single cryptographically strong random number.
     */
    public RandomGUID(boolean secure) {
        getRandomGUID(secure);
    }
    /*
     * Method to generate the random GUID
     */
    private void getRandomGUID(boolean secure) {
        MessageDigest md5 = null;
        StringBuffer sbValueBeforeMD5 = new StringBuffer();
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            System.out.println("Error: " + e);
        }
        try {
            long time = System.currentTimeMillis();
            long rand = 0;
            if (secure) {
                rand = mySecureRand.nextLong();
            } else {
                rand = myRand.nextLong();
            }
            // This StringBuffer can be a long as you need; the MD5
            // hash will always return 128 bits.  You can change
            // the seed to include anything you want here.
            // You could even stream a file through the MD5 making
            // the odds of guessing it at least as great as that
            // of guessing the contents of the file!
            sbValueBeforeMD5.append(s_id);
            sbValueBeforeMD5.append(":");
            sbValueBeforeMD5.append(Long.toString(time));
            sbValueBeforeMD5.append(":");
            sbValueBeforeMD5.append(Long.toString(rand));
            valueBeforeMD5 = sbValueBeforeMD5.toString();
            md5.update(valueBeforeMD5.getBytes());
            byte[] array = md5.digest();
            StringBuffer sb = new StringBuffer();
            for (int j = 0; j < array.length; ++j) {
                int b = array[j] & 0xFF;
                if (b < 0x10) sb.append("0");
                sb.append(Integer.toHexString(b));
            }
            valueAfterMD5 = sb.toString();
        } catch (Exception e) {
            System.out.println("Error:" + e);
        }
    }

    /*
     * Convert to the standard format for GUID
     * (Useful for SQL Server UniqueIdentifiers, etc.)
     * Example: C2FEEEAC-CFCD-11D1-8B05-00600806D9B6
     */
    public String toString() {
        String raw = valueAfterMD5.toUpperCase();
        StringBuffer sb = new StringBuffer();
        sb.append(raw.substring(0, 8));
        sb.append("-");
        sb.append(raw.substring(8, 12));
        sb.append("-");
        sb.append(raw.substring(12, 16));
        sb.append("-");
        sb.append(raw.substring(16, 20));
        sb.append("-");
        sb.append(raw.substring(20));
        return sb.toString();
    }
    /*
     * Demonstraton and self test of class
     */
    public static void main(String args[]) {
        for (int i=0; i< 100; i++) {
      RandomGUID myGUID = new RandomGUID();
      System.out.println("Seeding String=" + myGUID.valueBeforeMD5);
      System.out.println("rawGUID=" + myGUID.valueAfterMD5);
      System.out.println("RandomGUID=" + myGUID.toString());
        }
    }
}





Session ID generator

  
/*
 * Copyright 2005 Joe Walker
 *
 * 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.
 */
// Revised from dwr
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Random;

/**
 * Code to generate page ids.
 * IdGenerators are expensive to setup so it is suggested that you share
 * instances wherever possible. This action will also enhance security.
 * Much of this code is adapted from org.apache.catalina.session.ManagerBase.
 * Specifically Revision 1.37 which has been unchanged in the past 18 months.
 * I have taken out the /dev/urandom stuff and simplified things to the point
 * where we can audit it to work out what might be broken.
 * @author Joe Walker [joe at getahead dot ltd dot uk]
 */
public class IdGenerator
{
    /**
     * Seed the random number
     */
    public IdGenerator()
    {
        // Start with the current system time as a seed
        long seed = System.currentTimeMillis();
        // Also throw in the system identifier for "this" from toString
        char[] entropy = toString().toCharArray();
        for (int i = 0; i < entropy.length; i++)
        {
            //noinspection IntegerMultiplicationImplicitCastToLong
            long update = ((byte) entropy[i]) << ((i % 8) * 8);
            seed ^= update;
        }
        random.setSeed(seed);
    }
    /**
     * Generate and return a new session identifier.
     * @param length The number of bytes to generate
     * @return A new page id string
     */
    public synchronized String generateId(int length)
    {
        byte[] buffer = new byte[length];
        // Render the result as a String of hexadecimal digits
        StringBuffer reply = new StringBuffer();
        int resultLenBytes = 0;
        while (resultLenBytes < length)
        {
            random.nextBytes(buffer);
            buffer = getDigest().digest(buffer);
            for (int j = 0; j < buffer.length && resultLenBytes < length; j++)
            {
                byte b1 = (byte) ((buffer[j] & 0xf0) >> 4);
                if (b1 < 10)
                {
                    reply.append((char) ("0" + b1));
                }
                else
                {
                    reply.append((char) ("A" + (b1 - 10)));
                }
                byte b2 = (byte) (buffer[j] & 0x0f);
                if (b2 < 10)
                {
                    reply.append((char) ("0" + b2));
                }
                else
                {
                    reply.append((char) ("A" + (b2 - 10)));
                }
                resultLenBytes++;
            }
        }
        return reply.toString();
    }
    /**
     * @return the algorithm
     */
    public synchronized String getAlgorithm()
    {
        return algorithm;
    }
    /**
     * @param algorithm the algorithm to set
     */
    public synchronized void setAlgorithm(String algorithm)
    {
        this.algorithm = algorithm;
        digest = null;
    }
    /**
     * Return the MessageDigest object to be used for calculating
     * session identifiers.  If none has been created yet, initialize
     * one the first time this method is called.
     * @return The hashing algorithm
     */
    private MessageDigest getDigest()
    {
        if (digest == null)
        {
            try
            {
                digest = MessageDigest.getInstance(algorithm);
            }
            catch (NoSuchAlgorithmException ex)
            {
                try
                {
                    digest = MessageDigest.getInstance(DEFAULT_ALGORITHM);
                }
                catch (NoSuchAlgorithmException ex2)
                {
                    digest = null;
                    throw new IllegalStateException("No algorithms for IdGenerator");
                }
            }
            System.out.println("Using MessageDigest: " + digest.getAlgorithm());
        }
        return digest;
    }
    /* (non-Javadoc)
     * @see java.lang.Object#toString()
     */
    @SuppressWarnings({"EmptyMethod"})
    @Override
    public final String toString()
    {
        // This is to make the point that we need toString to return something
        // that includes some sort of system identifier as does the default.
        // Don"t change this unless you really know what you are doing.
        return super.toString();
    }
    /**
     * The default message digest algorithm to use if we cannot use
     * the requested one.
     */
    protected static final String DEFAULT_ALGORITHM = "MD5";
    /**
     * The message digest algorithm to be used when generating session
     * identifiers.  This must be an algorithm supported by the
     * <code>java.security.MessageDigest</code> class on your platform.
     */
    private String algorithm = DEFAULT_ALGORITHM;
    /**
     * A random number generator to use when generating session identifiers.
     */
    private Random random = new SecureRandom();
    /**
     * Return the MessageDigest implementation to be used when creating session
     * identifiers.
     */
    private MessageDigest digest = null;
}





Simple Id Generator

  
// Copyright (c) 2003-2009, Jodd Team (jodd.org). All Rights Reserved.

/**
 * Simple synchronized int ids sequence generator. It takes the positive sequence range (boundaries are included).
 * Optionally, it supports cycling, when counter reaches the max value. Otherwise an exception is thrown.
 * @see SimpleLongIdGenerator
 */
public class SimpleIdGenerator {
  protected volatile int value;
  protected int initialValue;
  protected int maxValue;
  protected boolean cycle;
  /**
   * Creates a new default cycled id generator. Starts from 1 and counts up to max int value.
   */
  public SimpleIdGenerator() {
    this(1, Integer.MAX_VALUE, true);
  }
  /**
   * Creates a new cycled id generator with specified initial value.
   */
  public SimpleIdGenerator(int initialValue) {
    this(initialValue, Integer.MAX_VALUE, true);
  }
  /**
   * Creates a new cycled id generator with specified range.
   */
  public SimpleIdGenerator(int initialValue, int maxValue) {
    this(initialValue, maxValue, true);
  }
  /**
   * Creates a new id generator with specified range and cycling flag.
   */
  public SimpleIdGenerator(int initialValue, int maxValue, boolean cycle) {
    if (initialValue < 0) {
      throw new IllegalArgumentException("Initial value "" + initialValue + "" must be a positive number.");
    }
    if (maxValue <= initialValue) {
      throw new IllegalArgumentException("Max value "" + maxValue + "" is less or equals to initial value "" + initialValue + "".");
    }
    this.initialValue = this.value = initialValue;
    this.maxValue = maxValue;
    this.cycle = cycle;
  }
  /**
   * Returns the next value from the sequence. Thread-safe.
   */
  public synchronized int next() {
    int id = value;
    value++;
    if ((value > maxValue) || (value < 0)) {
      if (cycle == false) {
        throw new IllegalStateException("Max value already reached.");
      }
      value = initialValue;
    }
    return id;
  }
}





Simple Long Id Generator

  
// Copyright (c) 2003-2009, Jodd Team (jodd.org). All Rights Reserved.

/**
 * Simple synchronized sequence id generator. It generates long numbers in a
 * sequence. When counter reaches max long, it will be set back to zero.
 */
public class SimpleLongIdGenerator {
  protected volatile long value;
  protected long initialValue;
  protected long maxValue;
  protected boolean cycle;
  /**
   * Creates a new default cycled id generator. Starts from 1 and counts up to max long value.
   */
  public SimpleLongIdGenerator() {
    this(1, Long.MAX_VALUE, true);
  }
  /**
   * Creates a new cycled id generator with specified initial value.
   */
  public SimpleLongIdGenerator(long initialValue) {
    this(initialValue, Long.MAX_VALUE, true);
  }
  /**
   * Creates a new cycled id generator with specified range.
   */
  public SimpleLongIdGenerator(long initialValue, long maxValue) {
    this(initialValue, maxValue, true);
  }
  /**
   * Creates a new id generator with specified range and cycling flag.
   */
  public SimpleLongIdGenerator(long initialValue, long maxValue, boolean cycle) {
    if (initialValue < 0) {
      throw new IllegalArgumentException("Initial value "" + initialValue + "" must be a positive number.");
    }
    if (maxValue <= initialValue) {
      throw new IllegalArgumentException("Max value "" + maxValue + "" is less or equals to initial value "" + initialValue + "".");
    }
    this.initialValue = this.value = initialValue;
    this.maxValue = maxValue;
    this.cycle = cycle;
  }
  /**
   * Returns the next value from the sequence. Thread-safe.
   */
  public synchronized long next() {
    long id = value;
    value++;
    if ((value > maxValue) || (value < 0)) {
      if (cycle == false) {
        throw new IllegalStateException("Max value already reached.");
      }
      value = initialValue;
    }
    return id;
  }
}





Thread-safe version of the Axiom UUIDGenerator

 
/*
 *  Licensed to the Apache Software Foundation (ASF) under one
 *  or more contributor license agreements.  See the NOTICE file
 *  distributed with this work for additional information
 *  regarding copyright ownership.  The ASF licenses this file
 *  to you 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.
 */
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;
/**
 * This is a thread-safe version of the Axiom UUIDGenerator
 * to be used until it is fixed in the next Axiom release
 */
public class UUIDGenerator {
    /** This class will give UUIDs for axis2. */
    private static String baseUUID = null;
    private static long incrementingValue = 0;
    private static Random myRand = null;
    private static boolean useNano = false;
    /**
     * MD5 a random string with localhost/date etc will return 128 bits construct a string of 18
     * characters from those bits.
     *
     * @return string
     */
    public static String getUUID() {
        if (baseUUID == null) {
            baseUUID = getInitialUUID();
            baseUUID = "urn:uuid:" + baseUUID;
        }
        if (++incrementingValue >= Long.MAX_VALUE) {
            incrementingValue = 0;
        }
        if (useNano) {
            return baseUUID + (System.nanoTime() + incrementingValue) +
                Integer.toString(myRand.nextInt());
        } else {
            return baseUUID + (System.currentTimeMillis() + incrementingValue +
                Integer.toString(myRand.nextInt()));
        }
    }
    protected static String getInitialUUID() {
        try {
            if (System.class.getMethod("nanoTime", new Class[0]) != null) {
                useNano = true;
            }
        } catch (NoSuchMethodException ignore) {}
        if (myRand == null) {
            myRand = new Random();
        }
        long rand = myRand.nextLong();
        String sid;
        try {
            sid = InetAddress.getLocalHost().toString();
        } catch (UnknownHostException e) {
            sid = Thread.currentThread().getName();
        }
        StringBuffer sb = new StringBuffer();
        sb.append(sid);
        sb.append(":");
        sb.append(Long.toString(rand));
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            //System.out.println("Error: " + e);
            //todo heve to be properly handle
        }
        md5.update(sb.toString().getBytes());
        byte[] array = md5.digest();
        StringBuffer sb2 = new StringBuffer();
        for (int j = 0; j < array.length; ++j) {
            int b = array[j] & 0xFF;
            sb2.append(Integer.toHexString(b));
        }
        int begin = myRand.nextInt();
        if (begin < 0) begin = begin * -1;
        begin = begin % 8;
        return sb2.toString().substring(begin, begin + 18).toUpperCase();
    }
}





Using java.util.concurrent.AtomicLong: A numerical id, start at zero and increment by one.

  
import java.util.concurrent.atomic.AtomicLong;
public class Main {
  public static void main(String[] argv) {
    AtomicLong nextId = new AtomicLong();
    System.out.println(nextId.getAndIncrement());
  }
}





Using java.util.UUID

  
import java.util.UUID;
public class Main {
  public static void main(String arg[]) {
    System.out.println(UUID.randomUUID());
  }
}
//138a4222-e898-484f-8347-dafc01c5b03b





UUID generation

  
//Revised from act.soap.util;
import java.util.*;
import java.security.SecureRandom;
public class UUID {
    private int    d1;
    private short  d2;
    private short  d3;
    private byte[] d4;
    public static final UUID nil = new UUID(0, (short) 0, (short) 0, new byte[] {  0, 0, 0, 0, 0, 0, 0, 0 } );
    static Random random = new Random();
    public static UUID generate() {
        int d1 = random.nextInt() % 65536;
        d1 += random.nextInt() % 65535 * 65535;
        int d2 = random.nextInt();
        int d3 = random.nextInt();
        byte[] d4 = new byte[8];
        for (int i = 0; i < 4; i++) {
            int t = random.nextInt();
            d4[i * 2] = (byte) (t % 256);
            d4[i * 2 + 1] = (byte) (t / 256 % 256);
        }
        return new UUID(d1, (short) (d2 % 65536), (short) (d3 % 65536), d4);
    }
    public UUID() {
        d1 = 0;
        d2 = 0;
        d3 = 0;
        d4 = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0 };
    }
    public UUID(int d1, short d2, short d3, byte[] d4) {
        this.d1 = d1;
        this.d2 = d2;
        this.d3 = d3;
        this.d4 = new byte[8];
        for (int i = 0; i < 8; i++)
            this.d4[i] = d4[i];
    }
    public String toString() {
        String temp1, temp2, temp3, temp4, temp;
        temp1 = Integer.toHexString(d1);
        while (temp1.length() < 8)
            temp1 = new String("0") + temp1;
        if (d2 < 0)
            temp2 = Integer.toHexString(d2 + 65536);
        else
            temp2 = Integer.toHexString(d2);
        while (temp2.length() < 4)
            temp2 = new String("0") + temp2;
        if (d3 < 0)
            temp3 = Integer.toHexString(d3 + 65536);
        else
            temp3 = Integer.toHexString(d3);
        while (temp3.length() < 4)
            temp3 = new String("0") + temp3;
        temp = temp1 + "-" + temp2 + "-" + temp3 + "-";
        for (int i = 0; i < d4.length; i++) {
            if (d4[i] < 0)
                temp4 = Integer.toHexString(d4[i] + 256);
            else
                temp4 = Integer.toHexString(d4[i]);
            while (temp4.length() < 2)
                temp4 = new String("0") + temp4;
            temp += temp4;
        }
        return temp;
    }
        public static void main( String[] args ) {
        for( int i = 0 ; i< 100 ; i++ ) {
            System.out.println( UUID.generate().toString() );
        }
    }
}





UUID generator

 
/*
 * Copyright 2004,2005 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.
 */

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;

/**
 * UUID generator  
 */
public class UUIDGenerator {
    
    private static String baseUUID = null;
    private static long incrementingValue = 0;

    private static Random myRand = null;
    /**
     * MD5 a random string with localhost/date etc will return 128 bits
     * construct a string of 18 characters from those bits.
     *
     * @return string
     */
    public static String getUUID() {
        if (baseUUID == null) {
            getInitialUUID();
        }
        long i = ++incrementingValue;
        if(i >= Long.MAX_VALUE || i < 0){
            incrementingValue = 0;
            i = 0;
        }
        return baseUUID + System.currentTimeMillis() + i;
    }
    protected static synchronized void getInitialUUID() {
        if (baseUUID != null) {
            return;
        }
        if (myRand == null) {
            myRand = new Random();
        }
        long rand = myRand.nextLong();
        String sid;
        try {
            sid = InetAddress.getLocalHost().toString();
        } catch (UnknownHostException e) {
            sid = Thread.currentThread().getName();
        }
        StringBuffer sb = new StringBuffer();
        sb.append(sid);
        sb.append(":");
        sb.append(Long.toString(rand));
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            //todo have to be properly handled
        }
        md5.update(sb.toString().getBytes());
        byte[] array = md5.digest();
        StringBuffer sb2 = new StringBuffer();
        for (int j = 0; j < array.length; ++j) {
            int b = array[j] & 0xFF;
            sb2.append(Integer.toHexString(b));
        }
        int begin = myRand.nextInt();
        if (begin < 0) begin = begin * -1;
        begin = begin % 8;
        baseUUID = sb2.toString().substring(begin, begin + 18).toUpperCase();
    }
}





UUID generator from http://www1.ics.uci.edu

  
/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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.    
 */
import java.io.IOException;
import java.net.InetAddress;
import java.security.SecureRandom;
import java.util.Random;
import java.util.UUID;

/**
 * UUID value generator.  Type 1 generator is based on the time-based generator  
 * in the Apache Commons Id project:  http://jakarta.apache.org/commons/sandbox
 * /id/uuid.html  The type 4 generator uses the standard Java UUID generator.
 *
 * The type 1 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.
 *
 * 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, Kevin Sutter
 * @nojavadoc
 * @since 0.3.3
 */
public class UUIDGenerator {
    // supported UUID types
    public static final int TYPE1 = 1;
    public static final int TYPE4 = 4;
    // indexes within the uuid array for certain boundaries
    private static final byte IDX_TIME_HI = 6;
    private static final byte IDX_TYPE = 6; // multiplexed
    private static final byte IDX_TIME_MID = 4;
    private static final byte IDX_TIME_LO = 0;
    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 = 0xB1D069B5400L;
    private static final long MILLI_MULT = 10000L;
    // 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.  
    private static Random RANDOM;
    // 4-byte IP address + 2 random bytes to compensate for the fact that
    // the MAC address is usually 6 bytes
    private static byte[] IP;
    // counter is initialized to 0 and is incremented for each uuid request
    // within the same timestamp window.
    private static int _counter;
    // 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 = 0;
        
    /*
     * Initializer for type 1 UUIDs.  Creates random generator and genenerates
     * the node portion of the UUID using the IP address.
     */
    private static synchronized void initializeForType1()
    {
        if (RANDOM != null)
            return;
        // note that secure random is very slow the first time
        // it is used; consider switching to a standard random
        RANDOM = new SecureRandom();
        _seq = (short) RANDOM.nextInt(MAX_14BIT);
        
        byte[] ip = null;
        try {
            ip = InetAddress.getLocalHost().getAddress();
        } catch (IOException ioe) {
            throw new RuntimeException(ioe);
        }
        IP = new byte[6];
        RANDOM.nextBytes(IP);
        System.arraycopy(ip, 0, IP, 2, ip.length);        
    }
    /**
     * Return a unique UUID value.
     */
    public static byte[] next(int type) {
        if (type == TYPE4) {
            return createType4();
        }
        return createType1();
    }
      
    /*
     * Creates a type 1 UUID 
     */
    public static byte[] createType1() {
        if (RANDOM == null)
            initializeForType1();
        // set ip addr
        byte[] uuid = new byte[16];
        System.arraycopy(IP, 0, uuid, 10, IP.length);
        // Set time info.  Have to do this processing within a synchronized
        // block because of the statics...
        long now = 0;
        synchronized (UUIDGenerator.class) {
            // 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
        byte[] timeBytes = Long.toString(now).getBytes();
        // 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;
    }
    /*
     * Creates a type 4 UUID
     */
    private static byte[] createType4() {
        UUID type4 = UUID.randomUUID();
        byte[] uuid = new byte[16];
        longToBytes(type4.getMostSignificantBits(), uuid, 0);
        longToBytes(type4.getLeastSignificantBits(), uuid, 8);
        return uuid;
    }
    
    /*
     * Converts a long to byte values, setting them in a byte array
     * at a given starting position.
     */
    private static void longToBytes(long longVal, byte[] buf, int sPos) {
        sPos += 7;
        for(int i = 0; i < 8; i++)         
            buf[sPos-i] = (byte)(longVal >>> (i * 8));
    }
    /**
     * Return the next unique uuid value as a 16-character string.
     */
    public static String nextString(int type) {
        byte[] bytes = next(type);
        try {
            return new String(bytes, "ISO-8859-1");
        } catch (Exception e) {
            return new String(bytes);
        }
    }
    /**
     * Return the next unique uuid value as a 32-character hex string.
     */
    public static String nextHex(int type) {
        return Base16Encoder.encode(next(type));
    }
    /**
     * Get the timestamp to be used for this uuid.  Must be called from
     * a synchronized block.
     *
     * @return long timestamp
     */
    // package-visibility for testing
    static long getTime() {
        if (RANDOM == null)
            initializeForType1();
        long newTime = getUUIDTime();
        if (newTime <= _lastMillis) {
            incrementSequence();
            newTime = getUUIDTime();
        }
        _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
        }
    }

}
/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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.    
 */
/**
 * Base 16 encoder.
 *
 * @author Marc Prud"hommeaux
 * @nojavadoc
 */
 class Base16Encoder {
    private final static char[] HEX = new char[]{
        "0", "1", "2", "3", "4", "5", "6", "7",
        "8", "9", "A", "B", "C", "D", "E", "F" };
    /**
     * Convert bytes to a base16 string.
     */
    public static String encode(byte[] byteArray) {
        StringBuffer hexBuffer = new StringBuffer(byteArray.length * 2);
        for (int i = 0; i < byteArray.length; i++)
            for (int j = 1; j >= 0; j--)
                hexBuffer.append(HEX[(byteArray[i] >> (j * 4)) & 0xF]);
        return hexBuffer.toString();
    }
    /**
     * Convert a base16 string into a byte array.
     */
    public static byte[] decode(String s) {
        int len = s.length();
        byte[] r = new byte[len / 2];
        for (int i = 0; i < r.length; i++) {
            int digit1 = s.charAt(i * 2), digit2 = s.charAt(i * 2 + 1);
            if (digit1 >= "0" && digit1 <= "9")
                digit1 -= "0";
            else if (digit1 >= "A" && digit1 <= "F")
                digit1 -= "A" - 10;
            if (digit2 >= "0" && digit2 <= "9")
                digit2 -= "0";
            else if (digit2 >= "A" && digit2 <= "F")
                digit2 -= "A" - 10;
            r[i] = (byte) ((digit1 << 4) + digit2);
        }
        return r;
    }
}





UUID generator from Sun Microsystems

  
/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 * 
 * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
 * 
 * The contents of this file are subject to the terms of either the GNU
 * General Public License Version 2 only ("GPL") or the Common Development
 * and Distribution License("CDDL") (collectively, the "License").  You
 * may not use this file except in compliance with the License. You can obtain
 * a copy of the License at https://glassfish.dev.java.net/public/CDDL+GPL.html
 * or glassfish/bootstrap/legal/LICENSE.txt.  See the License for the specific
 * language governing permissions and limitations under the License.
 * 
 * When distributing the software, include this License Header Notice in each
 * file and include the License file at glassfish/bootstrap/legal/LICENSE.txt.
 * Sun designates this particular file as subject to the "Classpath" exception
 * as provided by Sun in the GPL Version 2 section of the License file that
 * accompanied this code.  If applicable, add the following below the License
 * Header, with the fields enclosed by brackets [] replaced by your own
 * identifying information: "Portions Copyrighted [year]
 * [name of copyright owner]"
 * 
 * Contributor(s):
 * 
 * If you wish your version of this file to be governed by only the CDDL or
 * only the GPL Version 2, indicate your decision by adding "[Contributor]
 * elects to include this software in this distribution under the [CDDL or GPL
 * Version 2] license."  If you don"t indicate a single choice of license, a
 * recipient has the option to distribute your version of this file under
 * either the CDDL, the GPL Version 2 or to extend the choice of license to
 * its licensees as provided above.  However, if you add GPL Version 2 code
 * and therefore, elected the GPL Version 2 license, then the option applies
 * only if the new code is made subject to such option by the copyright
 * holder.
 */
/*
 * UuidUtil.java
 *
 * Created on October 15, 2002, 9:39 AM
 */
import java.net.InetAddress;
import java.rmi.server.UID;
import java.security.SecureRandom;
/**
 * Class UuidUtil
 * 
 * 
 */
public class UuidUtil {
  static final String _inetAddr = initInetAddr();
  // first method (from MarketMaker Guid)
  public static String generateUuidMM() {
    return new StringBuffer(new UID().toString()).reverse().append(":").append(_inetAddr)
        .toString();
  }
  // second method
  public static String generateUuid() {
    return generateUuid(new Object());
  }
  // this method can take in the session object
  // and insure better uniqueness guarantees
  public static String generateUuid(Object obj) {
    // low order time bits
    long presentTime = System.currentTimeMillis();
    int presentTimeLow = (int) presentTime & 0xFFFFFFFF;
    String presentTimeStringLow = formatHexString(presentTimeLow);
    StringBuffer sb = new StringBuffer(50);
    sb.append(presentTimeStringLow);
    // sb.append(":");
    sb.append(getIdentityHashCode(obj));
    // sb.append(":");
    // sb.append(_inetAddr);
    sb.append(addRandomTo(_inetAddr));
    // sb.append(":");
    sb.append(getNextRandomString());
    return sb.toString();
  }
  /**
   * Method initInetAddr
   * 
   * 
   * @return
   * 
   * @audience
   */
  private static String initInetAddr() {
    try {
      byte[] bytes = InetAddress.getLocalHost().getAddress();
      StringBuffer b = new StringBuffer();
      String s = null;
      for (int i = 0; i < bytes.length; i++) {
        s = Integer.toHexString(bytes[i]);
        if (bytes[i] < 0) {
          b.append(s.substring(s.length() - 2));
        } else {
          b.append(s);
        }
      }
      return b.toString();
    } catch (Exception ex) {
      // must return a value
      return "a48eb993";
      // return null;
    }
  }
  private static String addRandomTo(String hexString) {
    long hexAsLong = convertToLong(hexString);
    int nextRandom = getNextInt();
    long resultInt = hexAsLong + nextRandom;
    String result = Long.toHexString(resultInt);
    // START PWC 6425338
    // Always return a length of 7
    int len = result.length();
    if (len < 7) {
      result = padto7(result);
    } else {
      result = result.substring(len - 7, len);
    }
    // END PWC 6425338
    return result;
  }
  /**
   * Method getIdentityHashCode
   * 
   * 
   * @return
   * 
   * @audience
   */
  private static String getIdentityHashCode(Object obj) {
    String result = null;
    try {
      int hc = System.identityHashCode(obj);
      return formatHexString(hc);
    } catch (Exception ex) {
      // must return a value
      // return null;
      return "8AF5182";
    }
  }
  private static String formatHexString(int inputInt) {
    String result = null;
    String s = Integer.toHexString(inputInt);
    /*
     * PWC 6425338 if(s.length() < 8) { result = s; } else { result =
     * s.substring(0, 7); }
     */
    // START PWC 6425338
    // Always return a length of 7
    int len = s.length();
    if (len < 7) {
      result = padto7(s);
    } else {
      result = s.substring(len - 7, len);
    }
    // END PWC 6425338
    return result;
  }
  private static synchronized int getNextInt() {
    return _seeder.nextInt();
  }
  private static String getNextRandomString() {
    int nextInt = getNextInt();
    return formatHexString(nextInt);
  }
  private static long convertToLong(String hexString) {
    long result = 0;
    try {
      result = (Long.valueOf(hexString, 16)).longValue();
    } catch (NumberFormatException ex) {
    }
    return result;
  }
  private static SecureRandom _seeder = new SecureRandom();
  /**
   * Method main
   * 
   * 
   * @param args
   * 
   * @audience
   */
  public static void main(String[] args) {
    System.out.println(UuidUtil.generateUuidMM());
    System.out.println(UuidUtil.generateUuid());
    System.out.println(UuidUtil.generateUuid(new Object()));
  }
  // START PWC 6425338
  /*
   * Pads the given string to a length of 7.
   */
  private static String padto7(String s) {
    int i = 0;
    char[] chars = new char[7];
    int len = s.length();
    while (i < len) {
      chars[i] = s.charAt(i);
      i++;
    }
    while (i < 7) {
      chars[i++] = "0";
    }
    return new String(chars);
  }
  // END PWC 6425338
}





UUID generator of 32 bytes long values

  
// Copyright (c) 2003-2009, Jodd Team (jodd.org). All Rights Reserved.

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
/**
 * UUID generator of 32 bytes long values. It is builded from:
 * <ol>
 * <li> (0-7) IPAddress as HEX - 8 bytes
 * <li> (8-19) CurrentTimeMillis() as HEX - Display all 12 bytes
 * <li> (20-23) SecureRandom() as HEX - Keep only 4 significant bytes. Since this is "random" it doesn"t really matter how many bytes you keep or eliminate
 * <li> (24-31) System.identityHashCode as Hex - 8 bytes
 * </ol>
 */
public class Uuid32Generator {
  public static String generateUUID() {
    return new Uuid32Generator().generate();
  }
  private static final String ZEROS = "000000000000"; // 12
  public String generate() {
    StringBuilder strRetVal = new StringBuilder();
    String strTemp;
    try {
      // IPAddress segment
      InetAddress addr = InetAddress.getLocalHost();
      byte[] ipaddr = addr.getAddress();
      for (byte anIpaddr : ipaddr) {
        Byte b = new Byte(anIpaddr);
        strTemp = Integer.toHexString(b.intValue() & 0x000000ff);
        strRetVal.append(ZEROS.substring(0, 2 - strTemp.length()));
        strRetVal.append(strTemp);
      }
      strRetVal.append(":");
      // CurrentTimeMillis() segment
      strTemp = Long.toHexString(System.currentTimeMillis());
      strRetVal.append(ZEROS.substring(0, 12 - strTemp.length()));
      strRetVal.append(strTemp).append(":");
      // random segment
      SecureRandom prng = SecureRandom.getInstance("SHA1PRNG");
      strTemp = Integer.toHexString(prng.nextInt());
      while (strTemp.length() < 8) {
        strTemp = "0" + strTemp;
      }
      strRetVal.append(strTemp.substring(4)).append(":");
      // IdentityHash() segment
      strTemp = Long.toHexString(System.identityHashCode(this));
      strRetVal.append(ZEROS.substring(0, 8 - strTemp.length()));
      strRetVal.append(strTemp);
    } catch (UnknownHostException uhex) {
      throw new RuntimeException("Unknown host.", uhex);
    } catch (NoSuchAlgorithmException nsaex) {
      throw new RuntimeException("Algorithm "SHA1PRNG" is unavailiable.", nsaex);
    }
    return strRetVal.toString().toUpperCase();
  }
}