//By Milan D Ashara
//Server Side Unique Id Generator
//Use Only If you want to generate Unique ID < 32 Digit else use UID class
import java.util.HashMap;
import java.util.Random;
public class UniqueCode {
static HashMap<Character, Character> map=new HashMap<Character, Character>();
static
{
map.put('0', 'A');
map.put('1', 'Z');
map.put('2', 'K');
map.put('3', 'F');
map.put('4', 'V');
map.put('5', 'G');
map.put('6', 'L');
map.put('7', 'P');
map.put('8', 'Q');
map.put('9', 'T');
}
//create Unique Access Code
/*
* It can be used to generate unique access code from 13 digit to any number of digits you want
*
* */
private static StringBuilder createUniqueAccessCode(int aStart, long aEnd, Random aRandom) throws Exception{
if ( aStart > aEnd ) {
throw new IllegalArgumentException("Start cannot exceed End.");
}
StringBuilder accCode=new StringBuilder();
//get the range, casting to long to avoid overflow problems
long range = aEnd - (long)aStart + 1;
System.out.println("range>>>>>>>>>>>"+range);
// compute a fraction of the range, 0 <= frac < range
long fraction = (long)(range * aRandom.nextDouble());
// System.out.println("fraction>>>>>>>>>>>>>>>>>>>>"+fraction);
long randomNumber = fraction + (long)aStart;
accCode.append(randomNumber); //generate code in range of start and end
accCode.append(System.currentTimeMillis()); //generate 13 digit code
Thread.sleep(10);
//replace certain characters with alphabet
accCode.replace(4, 4, map.get(accCode.charAt(4)).toString());
accCode.deleteCharAt(5);
accCode.replace(1, 1, map.get(accCode.charAt(1)).toString());
accCode.deleteCharAt(2);
accCode.replace(3, 3, map.get(accCode.charAt(3)).toString());
accCode.deleteCharAt(4);
accCode.replace(6, 6, map.get(accCode.charAt(6)).toString());
accCode.deleteCharAt(7);
accCode.replace(11, 11, map.get(accCode.charAt(11)).toString());
accCode.deleteCharAt(12);
accCode.replace(13, 13, map.get(accCode.charAt(13)).toString());
accCode.deleteCharAt(14);
accCode.replace(14, 14, map.get(accCode.charAt(14)).toString());
accCode.deleteCharAt(15);
accCode.replace(15, 15, map.get(accCode.charAt(15)).toString());
accCode.deleteCharAt(16);
accCode.insert(4, '-');
accCode.insert(9, '-');
System.out.println("Generated : " + accCode.toString());
return accCode;
}
//test create 16 digit unique Id
public static void main(String[] args) throws Exception
{
// example to generate 16 digit unique code
for(int i=0;i<100;i++)
createUniqueAccessCode(100, 999L, new Random());
}
}
No comments:
Post a Comment