Tuesday, April 27, 2010

Java Code: URL Shortener

Wrote this code some time back for a programming interview, sharing it for everyone's use.
Its a 64 character encoded URL shortener code written in java. The code does not use any database backend but can be easily modified to support that.

Update: replacing the code text with Github Gist for better formatting support


package testjava;
import java.util.HashMap;
import java.util.Random;
/*
* URL Shortener
*/
public class URLShortener {
// storage for generated keys
private HashMap<String, String> keyMap; // key-url map
private HashMap<String, String> valueMap;// url-key map to quickly check
// whether an url is
// already entered in our system
private String domain; // Use this attribute to generate urls for a custom
// domain name defaults to http://fkt.in
private char myChars[]; // This array is used for character to number
// mapping
private Random myRand; // Random object used to generate random integers
private int keyLength; // the key length in URL defaults to 8
// Default Constructor
URLShortener() {
keyMap = new HashMap<String, String>();
valueMap = new HashMap<String, String>();
myRand = new Random();
keyLength = 8;
myChars = new char[62];
for (int i = 0; i < 62; i++) {
int j = 0;
if (i < 10) {
j = i + 48;
} else if (i > 9 && i <= 35) {
j = i + 55;
} else {
j = i + 61;
}
myChars[i] = (char) j;
}
domain = "http://fkt.in";
}
// Constructor which enables you to define tiny URL key length and base URL
// name
URLShortener(int length, String newDomain) {
this();
this.keyLength = length;
if (!newDomain.isEmpty()) {
newDomain = sanitizeURL(newDomain);
domain = newDomain;
}
}
// shortenURL
// the public method which can be called to shorten a given URL
public String shortenURL(String longURL) {
String shortURL = "";
if (validateURL(longURL)) {
longURL = sanitizeURL(longURL);
if (valueMap.containsKey(longURL)) {
shortURL = domain + "/" + valueMap.get(longURL);
} else {
shortURL = domain + "/" + getKey(longURL);
}
}
// add http part
return shortURL;
}
// expandURL
// public method which returns back the original URL given the shortened url
public String expandURL(String shortURL) {
String longURL = "";
String key = shortURL.substring(domain.length() + 1);
longURL = keyMap.get(key);
return longURL;
}
// Validate URL
// not implemented, but should be implemented to check whether the given URL
// is valid or not
boolean validateURL(String url) {
return true;
}
// sanitizeURL
// This method should take care various issues with a valid url
// e.g. www.google.com,www.google.com/, http://www.google.com,
// http://www.google.com/
// all the above URL should point to same shortened URL
// There could be several other cases like these.
String sanitizeURL(String url) {
if (url.substring(0, 7).equals("http://"))
url = url.substring(7);
if (url.substring(0, 8).equals("https://"))
url = url.substring(8);
if (url.charAt(url.length() - 1) == '/')
url = url.substring(0, url.length() - 1);
return url;
}
/*
* Get Key method
*/
private String getKey(String longURL) {
String key;
key = generateKey();
keyMap.put(key, longURL);
valueMap.put(longURL, key);
return key;
}
// generateKey
private String generateKey() {
String key = "";
boolean flag = true;
while (flag) {
key = "";
for (int i = 0; i <= keyLength; i++) {
key += myChars[myRand.nextInt(62)];
}
// System.out.println("Iteration: "+ counter + "Key: "+ key);
if (!keyMap.containsKey(key)) {
flag = false;
}
}
return key;
}
// test the code
public static void main(String args[]) {
URLShortener u = new URLShortener(5, "www.tinyurl.com/");
String urls[] = { "www.google.com/", "www.google.com",
"http://www.yahoo.com", "www.yahoo.com/", "www.amazon.com",
"www.amazon.com/page1.php", "www.amazon.com/page2.php",
"www.flipkart.in", "www.rediff.com", "www.techmeme.com",
"www.techcrunch.com", "www.lifehacker.com", "www.icicibank.com" };
for (int i = 0; i < urls.length; i++) {
System.out.println("URL:" + urls[i] + "\tTiny: "
+ u.shortenURL(urls[i]) + "\tExpanded: "
+ u.expandURL(u.shortenURL(urls[i])));
}
}
}

14 comments:

  1. Thanks for sharing the code.. Will try with storing the urls in database. Hopefully should work.

    ReplyDelete
  2. Thansk for your help and very greatful to getting this good solution...

    ReplyDelete
  3. Hi,

    Solution looks good,but the shorten url does not redirects to the long one.Is that something i am missing.

    ReplyDelete
  4. The loop at the end seems to be incomplete...could you please complete that

    ReplyDelete
  5. A url ending with a slash is not the same as a url without. Often it is, but it depends on the server. Just like the server decides if the path is case-sensitive or not (linux/windows). Whereas the host name isn't, and the protocol neither (equalsIgnoreCase("http://")).

    ReplyDelete
  6. Thansk for your help and very greatful

    ReplyDelete
  7. package com.firstgame;

    import java.awt.Color;
    import java.awt.Graphics;= 5;
    public int movementResetSpeed = 1;
    public int movementSpeed = 1;
    public int movementFrame = 1;
    public int noseHeight = 10;
    public int noseWidth = 10;

    public boolean objectDefine = false;
    public boolean falling = false;
    public boolean running = true;
    public boolean left = false;
    public boolean right = false;
    public boolean leftNose = true;
    public boolean rightNose = true;


    public Thread game;
    public Ac (Ad f) {
    setBackground(Color.blue);

    defineObjects();

    game = new Thread(this);
    game.start();

    f.addKeyListener(new KeyAdapter() {
    public void keyPressed(KeyEvent e) {
    if(e.getKeyCode() == keyLeft) {
    left = true;
    rightNose = false;
    leftNose = true;
    }
    if(e.getKeyCode() == keyRight) {
    right = true;
    leftNose = false;
    rightNose = true;
    }
    }
    public void keyReleased(KeyEvent e) {
    if(e.getKeyCode() == keyLeft) {
    left = false;
    }
    if(e.getKeyCode() == keyRight) {
    right = false;
    }
    }
    });
    }

    void defineObjects() {
    character = new Rectangle ((Am.width/2) - (characterwidth/2), (Am.height/2) - (characterheight/2), characterwidth, characterheight);
    floor = new Rectangle(0, 300, 600, 100);

    objectDefine = true;

    System.out.println("Shapes DefineObjects is running");

    repaint();
    }

    public void paint(Graphics g) {
    super.paint(g);

    if (objectDefine) {
    System.out.println("Graphics is running");
    g.setColor(Color.CYAN);
    g.fillRect(character.x, character.y, character.width, character.height);
    g.setColor(Color.green);
    g.fillRect(floor.x, floor.y, floor.width, floor.height);

    if(leftNose) {
    g.setColor(Color.yellow);
    g.fillRect(character.x - noseWidth, character.y + (character.height/4), noseWidth, noseHeight);
    } else if(rightNose) {
    g.setColor(Color.yellow);
    g.fillRect(character.x + character.width, character.y + (character.height/4), noseWidth, noseHeight);
    }
    }
    }

    public void run() {
    while (running) {

    //character feet
    Point pt1 = new Point(character.x, character.y + character.height);
    Point pt2 = new Point(character.x +character.width, character.y +character.height);


    //Falling
    if(fallingFrame >= fallingSpeed) {
    if (floor.contains(pt1) || floor.contains(pt2)) {
    falling = false;
    } else {
    character.y += 1;
    falling = true;
    }

    if (falling) {
    character.y += 1;
    }

    fallingFrame = 0;
    }else {
    fallingFrame += 1;
    }
    //movement speed check
    if(falling) {
    movementSpeed = movementFallingSpeed;
    } else {
    movementSpeed = movementResetSpeed;
    }

    //Movement
    if(movementFrame >= movementSpeed) {
    if(right) {
    character.x += 1;
    }

    if(left) {
    character.x -= 1;
    }

    movementFrame = -1;
    } else {
    movementFrame += 1;
    }

    fpsSetter();

    repaint();

    System.out.println("Run Method is running");
    }
    }
    public void fpsSetter() {
    try{
    game.sleep(fps/1000);
    }
    catch(Exception e) {
    e.printStackTrace();
    System.out.println("fpsSetter is running");

    }
    }
    }

    ReplyDelete
  8. Help required,

    Getting 404 while open tiny url.

    Logs as follows :-

    URL:http://localhost:8084/mobilox_website/home.do

    Tiny: www.mydevendra.com/voqLRH

    Expanded: localhost:8084/mobilox_website/home.do

    ReplyDelete
  9. I have a question on the generateKey() method. At some point you will run out of keys right?

    ReplyDelete
  10. cant redirect this tinyurl

    ReplyDelete
  11. Thank you for sharing such a Nice information about Java Code for Url Shortener.

    ReplyDelete
  12. Cool and I have a nifty proposal: How Long Renovate House home remodeling estimates

    ReplyDelete