Dateiverwaltung für die WebBox
ulrich
2017-04-06 a8280bb31a1e63505eafa09565d4275557aebddc
commit | author | age
a8280b 1
U 2 package de.uhilger.filecms.web;
3
4 /*
5  * ShortURL (https://github.com/delight-im/ShortURL)
6  * Copyright (c) delight.im (https://www.delight.im/)
7  * Licensed under the MIT License (https://opensource.org/licenses/MIT)
8  */
9
10 /**
11  * ShortURL: Bijective conversion between natural numbers (IDs) and short strings
12  *
13  * ShortURL.encode() takes an ID and turns it into a short string
14  * ShortURL.decode() takes a short string and turns it into an ID
15  *
16  * Features:
17  * + large alphabet (51 chars) and thus very short resulting strings
18  * + proof against offensive words (removed 'a', 'e', 'i', 'o' and 'u')
19  * + unambiguous (removed 'I', 'l', '1', 'O' and '0')
20  *
21  * Example output:
22  * 123456789 <=> pgK8p
23  */
24 public class ShortURL {
25
26     public static final String ALPHABET = "23456789bcdfghjkmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ-_";
27     public static final int BASE = ALPHABET.length();
28
29     public static String encode(int num) {
30         StringBuilder str = new StringBuilder();
31         while (num > 0) {
32             str.insert(0, ALPHABET.charAt(num % BASE));
33             num = num / BASE;
34         }
35         return str.toString();
36     }
37
38     public static int decode(String str) {
39         int num = 0;
40         for (int i = 0; i < str.length(); i++) {
41             num = num * BASE + ALPHABET.indexOf(str.charAt(i));
42         }
43         return num;
44     }
45
46 }