// // You use this software at your own risk. It shouldn't be used to run // nuclear power stations or fly aeroplanes. // // @author Simon Buckle (simon@simonbuckle.com) // // Copyright 2009 // package com.simonbuckle; import java.util.BitSet; import java.util.HashMap; import java.util.Map; import java.util.Random; public class URLShortener { private static final char[] alphabet = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' }; private static final int sizeOfAlphabet = alphabet.length; private static final int RETRY_LIMIT = 5; private static final int MASK = 0x3F; private static final int SHIFT = 6; // The length of the (output) code private int numOfChars; // Check to see what codes we have already generated private BitSet codes; public URLShortener(int n) { if (n < 1 || n > 5) throw new IllegalArgumentException("Length must be between 1 and 5."); this.numOfChars = n; this.codes = new BitSet((int)Math.pow(sizeOfAlphabet, n)); } public String generateCode() { String result = null; int attempt = 1; while (attempt <= RETRY_LIMIT) { int c = genCode(); if (!codes.get(c)) { codes.set(c); result = strFromCode(c); break; } // else try again } return result; } private String strFromCode(int n) { StringBuilder result = new StringBuilder(); for(int i=0; i>= SHIFT; } return result.toString(); } private int genCode() { int code = 0; Random generator = new Random(System.currentTimeMillis()); for(int i=0; i map = new HashMap(); String code = shortener.generateCode(); map.put(code, "http://www.simonbuckle.com/"); System.out.println(code + " : " + map.get(code)); } }