/*
 * The contents of this file are subject to the terms 
 * of the Common Development and Distribution License 
 * (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/CDDLv1.0.html or
 * glassfish/bootstrap/legal/CDDLv1.0.txt.
 * See the License for the specific language governing 
 * permissions and limitations under the License.
 * 
 * When distributing Covered Code, include this CDDL 
 * Header Notice in each file and include the License file 
 * at glassfish/bootstrap/legal/CDDLv1.0.txt.  
 * If applicable, add the following below the CDDL Header, 
 * with the fields enclosed by brackets [] replaced by
 * you own identifying information: 
 * "Portions Copyrighted [year] [name of copyright owner]"
 * 
 * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
 */

/*
 * UuidUtil.java
 *
 * Created on October 15, 2002, 9:39 AM
 */

package com.sun.enterprise.util.uuid;

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);
        
        //random number
        String nextRandom = getNextRandomString();
        
        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);
        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);
        if(s.length() < 8)
        {
            result = s;
        } else {
            result = s.substring(0, 7);
        }
        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()));
    }
}



