1 package org.djunits.locale;
2
3 import java.io.Serializable;
4 import java.util.Locale;
5 import java.util.MissingResourceException;
6 import java.util.ResourceBundle;
7
8
9
10
11
12
13
14
15
16
17
18
19 public class Localization implements Serializable
20 {
21
22 private static final long serialVersionUID = 1L;
23
24
25 private final String bundleNamePrefix;
26
27
28 private ResourceBundle resourceBundle;
29
30
31 private Locale currentLocale = null;
32
33
34 private ResourceBundle defaultResourceBundle;
35
36
37 private Locale defaultLocale = null;
38
39
40
41
42
43 public Localization(final String prefix)
44 {
45 this.bundleNamePrefix = prefix;
46 getString("xyz");
47 }
48
49
50
51
52
53
54
55 public final String getString(final String key)
56 {
57 if (this.currentLocale == null || !this.currentLocale.equals(DefaultLocale.getLocale()))
58 {
59 if (DefaultLocale.getLocale() == null)
60 {
61 DefaultLocale.setLocale(new Locale("en"));
62 }
63 this.currentLocale = DefaultLocale.getLocale();
64 Locale.setDefault(this.currentLocale);
65 try
66 {
67 this.resourceBundle = ResourceBundle.getBundle(this.bundleNamePrefix, this.currentLocale);
68 }
69 catch (MissingResourceException e)
70 {
71 try
72 {
73 this.resourceBundle = ResourceBundle.getBundle("resources/" + this.bundleNamePrefix, this.currentLocale);
74 }
75 catch (MissingResourceException e2)
76 {
77 return '!' + key.substring(key.indexOf('.') + 1) + '!';
78 }
79 }
80 }
81 if (null == this.resourceBundle)
82 {
83
84 return '!' + key.substring(key.indexOf('.') + 1) + '!';
85 }
86 try
87 {
88 return this.resourceBundle.getString(key);
89 }
90 catch (MissingResourceException e)
91 {
92 return '!' + key.substring(key.indexOf('.') + 1) + '!';
93 }
94 }
95
96
97
98
99
100
101
102 public final String getDefaultString(final String key)
103 {
104 if (this.defaultLocale == null)
105 {
106 this.defaultLocale = new Locale("en");
107 try
108 {
109 this.defaultResourceBundle = ResourceBundle.getBundle(this.bundleNamePrefix, this.defaultLocale);
110 }
111 catch (MissingResourceException e)
112 {
113 try
114 {
115 this.defaultResourceBundle =
116 ResourceBundle.getBundle("resources/" + this.bundleNamePrefix, this.defaultLocale);
117 }
118 catch (MissingResourceException e2)
119 {
120 return '!' + key.substring(key.indexOf('.') + 1) + '!';
121 }
122 }
123 }
124 if (null == this.defaultResourceBundle)
125 {
126
127 return '!' + key.substring(key.indexOf('.') + 1) + '!';
128 }
129 try
130 {
131 return this.defaultResourceBundle.getString(key);
132 }
133 catch (MissingResourceException e)
134 {
135 return '!' + key.substring(key.indexOf('.') + 1) + '!';
136 }
137 }
138
139
140
141
142 public boolean isDefault()
143 {
144 if (this.currentLocale == null || this.defaultLocale == null | !this.currentLocale.equals(this.defaultLocale)
145 || !this.currentLocale.equals(DefaultLocale.getLocale()))
146 {
147 return false;
148 }
149 return true;
150 }
151 }