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);
67 private static String getStackClass(int levels) {
68 TraceException trace = new TraceException();
69 StackTraceElement stack[] = trace.getStackTrace();
70 final int index = levels + 2;
71 if (stack.length <= index) {
72 throw new BugException("Stack trace is too short, length=" + stack.length + ", expected=" + index, trace);
75 StackTraceElement element = stack[index];
76 String cn = element.getClassName();
77 int pos = cn.lastIndexOf('.');
79 cn = cn.substring(pos + 1);
87 // For unit testing purposes
88 String getClassName() {