package org.jboss.ejb.plugins.keygenerator.uuid;
import org.jboss.ejb.plugins.keygenerator.KeyGenerator;
import java.net.InetAddress;
import java.security.SecureRandom;
public class UUIDKeyGenerator
implements KeyGenerator
{
SecureRandom seeder;
private String midValue;
public UUIDKeyGenerator()
throws Exception
{
StringBuffer buffer = new StringBuffer( 16 );
byte[] addr = InetAddress.getLocalHost().getAddress();
buffer.append( toHex( toInt(addr), 8 ) );
buffer.append( toHex( System.identityHashCode(this), 8 ) );
midValue = buffer.toString();
seeder = new SecureRandom();
int node = seeder.nextInt();
}
public Object generateKey()
{
StringBuffer buffer = new StringBuffer( 32 );
buffer.append(toHex((int)(System.currentTimeMillis() & 0xFFFFFFFF), 8));
buffer.append( midValue );
buffer.append( toHex( seeder.nextInt(), 8 ) );
return buffer.toString();
}
private String toHex( int value, int length )
{
char[] hexDigits =
{ '0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F' };
StringBuffer buffer = new StringBuffer( length );
int shift = (length - 1) << 2;
int i = -1;
while( ++i < length )
{
buffer.append( hexDigits[(value >> shift) & 0x0000000F] );
value <<= 4;
}
return buffer.toString();
}
private static int toInt( byte[] bytes )
{
int value = 0;
int i = -1;
while( ++i < bytes.length )
{
value <<= 8;
int b = bytes[ i ] & 0xff;
value |= b;
}
return value;
}
}