1 package net.sf.openrocket.l10n;
3 import java.util.MissingResourceException;
5 import net.sf.openrocket.logging.TraceException;
6 import net.sf.openrocket.util.BugException;
9 * A translator that prepends a pre-defined class name in front of a translation key
10 * and retrieves the translator for that key, and only if that is missing reverts to
11 * the base key name. The base class name can either be provided to the constructor
12 * or retrieved from the stack.
14 * @author Sampo Niskanen <sampo.niskanen@iki.fi>
16 public class ClassBasedTranslator implements Translator {
19 private final Translator translator;
20 private final String className;
23 * Construct a translator using a specified class name.
25 * @param translator the translator from which to obtain the translations.
26 * @param className the base class name to prepend.
28 public ClassBasedTranslator(Translator translator, String className) {
29 this.translator = translator;
30 this.className = className;
34 * Construct a translator by obtaining the base class name from the stack.
36 * @param translator the translator from which to obtain the translations.
37 * @param levels the number of levels to move upwards in the stack from the point where this method is called.
39 public ClassBasedTranslator(Translator translator, int levels) {
40 this(translator, getStackClass(levels));
46 public String get(String key) {
47 String classKey = className + "." + key;
50 return translator.get(classKey);
51 } catch (MissingResourceException e) {
56 return translator.get(key);
57 } catch (MissingResourceException e) {
58 MissingResourceException mre = new MissingResourceException(
59 "Neither key '" + classKey + "' nor '" + key + "' could be found", e.getClassName(), key);
68 public String get(String base, String text) {
69 return translator.get(base, text);
73 public String getBaseText(String base, String translation) {
74 return translator.getBaseText(base, translation);
80 private static String getStackClass(int levels) {
81 TraceException trace = new TraceException();
82 StackTraceElement stack[] = trace.getStackTrace();
83 final int index = levels + 2;
84 if (stack.length <= index) {
85 throw new BugException("Stack trace is too short, length=" + stack.length + ", expected=" + index, trace);
88 StackTraceElement element = stack[index];
89 String cn = element.getClassName();
90 int pos = cn.lastIndexOf('.');
92 cn = cn.substring(pos + 1);
100 // For unit testing purposes
101 String getClassName() {