Skip to content

Instantly share code, notes, and snippets.

@chongma
Created August 7, 2018 17:44
Show Gist options
  • Save chongma/dbd781f0a38c517b5c289353e0b387e1 to your computer and use it in GitHub Desktop.
Save chongma/dbd781f0a38c517b5c289353e0b387e1 to your computer and use it in GitHub Desktop.
package uk.me.kissy.document.templateMethod;
import java.util.List;
import java.util.TreeMap;
import freemarker.template.SimpleNumber;
import freemarker.template.SimpleScalar;
import freemarker.template.TemplateMethodModelEx;
import freemarker.template.TemplateModelException;
public class ListItemLabel implements TemplateMethodModelEx {
private final static TreeMap<Integer, String> map = new TreeMap<>();
static {
map.put(1000, "M");
map.put(900, "CM");
map.put(500, "D");
map.put(400, "CD");
map.put(100, "C");
map.put(90, "XC");
map.put(50, "L");
map.put(40, "XL");
map.put(10, "X");
map.put(9, "IX");
map.put(5, "V");
map.put(4, "IV");
map.put(1, "I");
}
// Copied from Stackoverflow https://stackoverflow.com/a/19759564/2735286
private static String toRoman(int number) {
int l = map.floorKey(number);
if (number == l) {
return map.get(number);
}
return map.get(l) + toRoman(number - l);
}
// Copied from
// https://stackoverflow.com/questions/10813154/how-do-i-convert-a-number-to-a-letter-in-java
private static String toAlphabetic(int i) {
if (i < 0) {
return "-" + toAlphabetic(-i - 1);
}
int quot = i / 26;
int rem = i % 26;
char letter = (char) ((int) 'A' + rem);
if (quot == 0) {
return "" + letter;
} else {
return toAlphabetic(quot - 1) + letter;
}
}
@Override
public Object exec(List arguments) throws TemplateModelException {
final String typeOrdered = ((SimpleScalar) arguments.get(0)).getAsString();
final Integer number = ((SimpleNumber) arguments.get(1)).getAsNumber().intValue();
if ("A".equals(typeOrdered)) {
String value = toAlphabetic(number);
return new SimpleScalar(value.toLowerCase());
} else if ("a".equals(typeOrdered)) {
String value = toAlphabetic(number);
return new SimpleScalar(value.toLowerCase());
} else if ("I".equals(typeOrdered)) {
String value = toRoman(number);
return new SimpleScalar(value);
} else if ("i".equals(typeOrdered)) {
String value = toRoman(number);
return new SimpleScalar(value.toLowerCase());
} else {
// default numeric
return new SimpleNumber(number);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment