Skip to content
Java project #18Intermediate

URL Shortener Service

A simulated link shortener: URL validation and normalisation, base-62 codes that don't look sequential, custom aliases, expiry, click counting and top links.

Estimated time
~4 hours to build
Files
6 files · 358 lines
Technologies
Java 21, java.net.URI, HashMap, Records, Math.floorMod / multiplyExact

Introduction

Link shorteners look simple but contain several classic ideas: encoding numbers compactly in base 62, mapping in both directions with hash maps, normalising input so equivalent URLs share a code, and expiring data. This project builds the core service; no network access is involved.

Problem statement

Shorten http/https URLs into six-character codes (or user-chosen aliases of 3–20 letters, digits or hyphens). Normalise URLs (lower-case scheme and host, drop default ports, keep path and query) so equivalent URLs reuse the same code. Support optional expiry in days, opening a code (which counts a click and returns a redirect, or 404 if unknown or expired), information about a code, the top links by clicks, purging expired links, and a simulated clock that only moves forward.

Objectives

  • Implement base-62 encoding and decoding
  • Generate unique, non-sequential codes with a bijective scramble
  • Validate and normalise URLs with java.net.URI
  • Maintain two consistent maps (code→link, URL→code)

Features

  • Six-character scrambled codes and custom aliases
  • URL normalisation and de-duplication
  • Expiry, click counts, top links and purge
  • Clear errors for invalid URLs and aliases

Concepts demonstrated

  • Base conversion
  • Bijective mappings
  • Normalisation
  • Hash maps
  • Expiry

System architecture

Base62 converts numbers to and from strings over 62 symbols. Shortener takes a counter, multiplies it by a large odd constant modulo 62⁶ — a bijection, so every counter value gives a different code — and encodes the result as six base-62 digits. normalise uses URI to validate and canonicalise. byCode maps codes to immutable Link records (a click replaces the record with an updated copy); codeByUrl lets repeated URLs reuse their code. purgeExpired removes links from both maps.

Folder structure

TextProject tree
url-shortener/
├── README.md
├── src/Base62.java
├── src/Main.java
├── src/Shortener.java
├── tests/expected-output.txt
└── tests/sample-input.txt

Complete source code

src/Base62.java

28 lines
Javasrc/Base62.java
/** Encodes non-negative longs in base 62 (0-9, a-z, A-Z), giving short, URL-safe codes. */
public final class Base62 {
private static final String DIGITS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
private Base62() { }
public static String encode(long n) {
if (n < 0) throw new IllegalArgumentException("negative");
if (n == 0) return "0";
StringBuilder sb = new StringBuilder();
while (n > 0) {
sb.append(DIGITS.charAt((int) (n % 62)));
n /= 62;
}
return sb.reverse().toString();
}
public static long decode(String s) {
long n = 0;
for (char c : s.toCharArray()) {
int d = DIGITS.indexOf(c);
if (d < 0) throw new IllegalArgumentException("invalid character " + c);
n = Math.addExact(Math.multiplyExact(n, 62), d);
}
return n;
}
}

What each file does

src/Base62.java
Base-62 encoding and overflow-checked decoding.
src/Shortener.java
Normalisation, code generation, aliases, resolution with clicks, expiry and top links.
src/Main.java
The simulated clock and command loop.

How to run it

Compile

Terminal
javac -d out $(find src -name "*.java")
# Windows PowerShell: javac -d out (Get-ChildItem -Recurse src -Filter *.java).FullName

Run

Terminal
java -cp out Main

Test against the expected output

Terminal
java -cp out Main < tests/sample-input.txt > actual.txt
diff actual.txt tests/expected-output.txt
# Windows PowerShell:
# Get-Content tests\sample-input.txt | java -cp out Main > actual.txt

Expected output

Generated by running the project with tests/sample-input.txt. Your output should match tests/expected-output.txt exactly.

Texttests/expected-output.txt
=== URL Shortener (simulation) === day 1
>
https://kh.link/4c4WUp -> https://example.com/courses/java?level=beginner
>
https://kh.link/4c4WUp -> https://example.com/courses/java?level=beginner
>
https://kh.link/8o9TOO -> http://docs.example.org/api/Stream.html (expires after day 6)
>
Error: only http and https URLs can be shortened
>
Error: the URL needs a valid host
>
Error: only http and https URLs can be shortened
>
https://kh.link/java-course -> https://example.com/courses/java
>
Error: alias 'java-course' is taken
>
Error: aliases are 3-20 letters, digits or hyphens
>
302 redirect to https://example.com/courses/java (click 1)
>
302 redirect to https://example.com/courses/java (click 2)
>
302 redirect to https://example.com/courses/java (click 3)
>
404 not found or expired: zzzzzz
>
It is now day 7
>
404 not found or expired: 8o9TOO
>
java-course: https://example.com/courses/java, created day 1, 3 click(s), never expires
>
java-course 3 https://example.com/courses/java
4c4WUp 0 https://example.com/courses/java?level=beginner
>
Removed 1 expired link(s); 2 remain
>
Error: time only moves forward
>
Input
shorten https://Example.com:443/courses/java?level=beginner
shorten https://example.com/courses/java?level=beginner
shorten http://docs.example.org/api/Stream.html 5
shorten ftp://files.example.com/x
shorten https://localhost/test
shorten not-a-url
alias java-course https://example.com/courses/java
alias java-course https://example.com/other
alias x! https://example.com/
open java-course
open java-course
open java-course
open zzzzzz
day 7
open 8o9TOO
info java-course
top 3
purge
day 3
quit

Testing

  • Run with tests/sample-input.txt and compare with tests/expected-output.txt.
  • https://Example.com:443/courses/java?... and the lower-case form without the port get the same code.
  • ftp URLs, hosts without a dot and malformed text are rejected.
  • After moving to day 7, the link that expired after day 6 returns 404 and is removed by purge.

Common errors

Two URLs get the same code

Use a bijective mapping (an odd multiplier modulo 62^6) or check for collisions before storing.

Case differences create duplicates

Normalise the scheme and host to lower case before looking up the URL.

Possible improvements

  • Persist links to a file
  • Expose the service over HTTP with com.sun.net.httpserver
  • Add per-day click statistics

Additional challenges

  1. 1Decode a code back to its counter value and prove the mapping is reversible.
  2. 2Add a QR-code text renderer for a link.
  3. 3Rate-limit shortening to 5 links per user per day.

Built and tested it yourself? Mark it to update your dashboard.