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