1 package org.opentrafficsim.core.locale;
2
3 import java.util.Locale;
4 import java.util.MissingResourceException;
5 import java.util.ResourceBundle;
6
7 /**
8 * <p>
9 * Copyright (c) 2013-2014 Delft University of Technology, PO Box 5, 2600 AA, Delft, the Netherlands. All rights reserved. <br>
10 * BSD-style license. See <a href="http://opentrafficsim.org/node/13">OpenTrafficSim License</a>.
11 * <p>
12 * @version Jun 12, 2014 <br>
13 * @author <a href="http://www.tbm.tudelft.nl/averbraeck">Alexander Verbraeck</a>
14 * @author <a href="http://tudelft.nl/pknoppers">Peter Knoppers</a>
15 */
16 public class Localization
17 {
18 /** filename without .properties, to be found in src/main/resources folder. */
19 private final String bundleNamePrefix;
20
21 /** the resource bundle. */
22 private ResourceBundle resourceBundle;
23
24 /** current locale. */
25 private Locale currentLocale = null;
26
27 /**
28 * Create a Localization object.
29 * @param prefix String; the prefix of the properties files to use.
30 */
31 public Localization(final String prefix)
32 {
33 this.bundleNamePrefix = prefix;
34 }
35
36 /**
37 * Retrieve a string from a locale bundle. If retrieval fails the value of key string, surrounded by exclamation marks is
38 * returned.
39 * @param key the key for the locale in the properties file
40 * @return localized string, or, if a translation could not be found return the key surrounded by exclamation marks
41 */
42 public final String getString(final String key)
43 {
44 if (this.currentLocale == null || !this.currentLocale.equals(DefaultLocale.getLocale()))
45 {
46 if (DefaultLocale.getLocale() == null)
47 {
48 DefaultLocale.setLocale(new Locale("en"));
49 }
50 this.currentLocale = DefaultLocale.getLocale();
51 Locale.setDefault(this.currentLocale);
52 try
53 {
54 this.resourceBundle = ResourceBundle.getBundle(this.bundleNamePrefix, this.currentLocale);
55 }
56 catch (MissingResourceException e)
57 {
58 try
59 {
60 this.resourceBundle = ResourceBundle.getBundle("resources/" + this.bundleNamePrefix, this.currentLocale);
61 }
62 catch (MissingResourceException e2)
63 {
64 return '!' + key.substring(key.indexOf('.') + 1) + '!';
65 }
66 }
67 }
68 if (null == this.resourceBundle)
69 {
70 // Failed to find the resourceBundle (on a previous call to getString)
71 return '!' + key.substring(key.indexOf('.') + 1) + '!';
72 }
73 try
74 {
75 return this.resourceBundle.getString(key);
76 }
77 catch (MissingResourceException e)
78 {
79 return '!' + key.substring(key.indexOf('.') + 1) + '!';
80 }
81 }
82 }