java-org.hwo/src/org/hwo/i18n/Messages.java

85 lines
1.9 KiB
Java

package org.hwo.i18n;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
public class Messages {
protected static Messages pInstance;
protected static List<Messages> instanceList;
protected static Locale activeLocale;
protected String BUNDLE_NAME = "org.hwo.i18n.messages";
private ResourceBundle defaultResourceBundle;
private ResourceBundle localeResourceBundle;
protected Messages() {
initialize();
}
protected Messages(String bundleName)
{
BUNDLE_NAME = bundleName;
initialize();
}
private void initialize()
{
System.err.println(this.getClass().getName() + ": Using Locale:" + activeLocale.getCountry() + " / " + activeLocale.getLanguage());
defaultResourceBundle = ResourceBundle.getBundle(BUNDLE_NAME);
localeResourceBundle = ResourceBundle.getBundle(BUNDLE_NAME,activeLocale);
instanceList.add(this);
}
public static String getString(String key) {
for (Messages messages: instanceList)
{
if (messages.hasKey(key))
return messages.getInstanceString(key);
}
return '!' + key + '!';
}
public boolean hasKey(String key)
{
return localeResourceBundle.containsKey(key) | defaultResourceBundle.containsKey(key);
}
public String getInstanceString(String key)
{
try {
if (localeResourceBundle.containsKey(key))
return localeResourceBundle.getString(key);
if (defaultResourceBundle.containsKey(key))
return defaultResourceBundle.getString(key);
return '!' + key + '!';
} catch (MissingResourceException e) {
return '!' + key + '!';
}
}
public static Messages getInstance()
{
return pInstance;
}
static {
if (activeLocale == null)
activeLocale = Locale.getDefault();
if (instanceList == null)
instanceList = new LinkedList<Messages>();
if (pInstance == null)
pInstance = new Messages();
}
}