Material localization support
[debian/openrocket] / core / src / net / sf / openrocket / l10n / ResourceBundleTranslator.java
1 package net.sf.openrocket.l10n;
2
3 import java.util.Locale;
4 import java.util.MissingResourceException;
5 import java.util.ResourceBundle;
6
7 /**
8  * A translator that obtains translated strings from a resource bundle.
9  * 
10  * @author Sampo Niskanen <sampo.niskanen@iki.fi>
11  */
12 public class ResourceBundleTranslator implements Translator {
13         
14         private final ResourceBundle bundle;
15         private final ResourceBundle english;
16         
17         /**
18          * Create a ResourceBundleTranslator using the default Locale.
19          * 
20          * @param baseName      the base name of the resource bundle
21          */
22         public ResourceBundleTranslator(String baseName) {
23                 this(baseName, Locale.getDefault());
24         }
25         
26         /**
27          * Create a ResourceBundleTranslator using the specified Locale.
28          * 
29          * @param baseName      the base name of the resource bundle
30          * @param locale        the locale to use
31          */
32         public ResourceBundleTranslator(String baseName, Locale locale) {
33                 this.bundle = ResourceBundle.getBundle(baseName, locale);
34                 this.english = ResourceBundle.getBundle(baseName, Locale.ROOT);
35         }
36         
37         
38         /*
39          * NOTE:  This method must be thread-safe!
40          */
41         @Override
42         public synchronized String get(String key) {
43                 return bundle.getString(key);
44         }
45         
46         @Override
47         public synchronized String get(String base, String text) {
48                 String key = base + "." + L10N.normalize(text);
49                 try {
50                         return bundle.getString(key);
51                 } catch (MissingResourceException e) {
52                         return text;
53                 }
54         }
55         
56         @Override
57         public synchronized String getBaseText(String base, String translation) {
58                 String prefix = base + ".";
59                 for (String key : bundle.keySet()) {
60                         if (key.startsWith(prefix)) {
61                                 String value = bundle.getString(key);
62                                 if (value.equals(translation)) {
63                                         return english.getString(key);
64                                 }
65                         }
66                 }
67                 return translation;
68         }
69 }