I'm trying to make a program localized in Java.
package javaapplication8;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.ResourceBundle;
public class LanguageController {
private final Map supportedLanguages;
private final ResourceBundle translation;
public LanguageController(String language){
supportedLanguages = new HashMap();
supportedLanguages.put("English",Locale.ENGLISH);
supportedLanguages.put("Italiano",Locale.ITALIAN);
//here I get error
translation = ResourceBundle.getBundle("language", supportedLanguages.get(language));
}
public String getWord(String keyword)
{
return translation.getString(keyword);
}
}
Than in a class I try to print a word in two different languages, italian and english. I have two proprieties file
Language.proprieties
Language_it.proprieties
In the class:
LanguageController langController_it = new LanguageController("Italiano");
System.out.println(langController_it.getWord("Option"));
LanguageController langController_en = new LanguageController("English");
System.out.println(langController_en.getWord("Option"));
EDIT: First problem solution java.util.MissingResourceException: Can't find bundle for base name 'property_file name', locale en_US
I still have error in that line supportedLanguages.get(language)
There are several problems with your application (and with your question for that matter).
First of all, you do not use parametrized collection:
private final Map supportedLanguages;
This map will always return Object, but the getBundle() method has different signature:
public static ResourceBundle getBundle(String baseName, Locale locale);
I am sure that's exactly what Netbeans is complaining about. The ugly way to fix this would be to cast the parameter to Locale:
translation = ResourceBundle.getBundle("language", (Locale) supportedLanguages.get(language));
The better way would be to use type parameters in Map declaration:
private final Map<String, Locale> supportedLanguages = new HashMap<>();
Another possible issue with your application is where you keep properties files with translations. Unfortunately, Java is extremely sensitive where it comes to file location and you have to provide the fully qualified path to a properties file. It changes a bit with Java 8 and ResourceBundle's SPI providers, but that's a different story.
Last, but not least, it seems that you are trying to implement the common anti-pattern, that is language switcher. If you are implementing desktop application, please don't do this mistake!
It is just enough to get user interface default locale:
Locale locale = Locale.getDefault(LocaleCategory.DISPLAY);
Believe it or not, but the ResourceBundle class will try to fall-back to the most appropriate language for the user. If I already have set the UI language in my Operating System preferences, why are you bothering to make a choice again?
Honestly, language switcher make sense for static web sites sometimes, but not for web applications, and definitely not for desktop applications.
Related
I am currently working on a platform that has multi-language options and also the language is defined by IP. So I'm trying to build an architecture for testing both scenarios dynamically. The domain is always the same: Example: www.page.com (If you are logged in from Britain the web application is loaded in English, if you are visiting the page from France the page is loaded in French.)
I have an idea to make different abstract classes with error messages for example:
public class ErrorMessagesEN {
public static final String MANDATORY_FIELD = "This field is mandatory...";
public static final String SOME_OTHER_ERROR_MSG = "Some error message on english"
//etc.....
}
public class ErrorMessagesFR {
public static final String MANDATORY_FIELD = "Error message in French"
public static final String SOME_OTHER_ERROR_MSG = "Some error message on French"
etc.....
}
In the test method i provide parameter "EN" or "FR" for example:
homepage.signIn(String location)
So is there any option to make for example:
if (location=="EN") {
load the ErrorMessageEN
//etc......
}
The keys for the Strings are the same but the classes are different, so how can I provide different imports of the classes by the location parameter for example? Or are there any better approaches for this situation? Any links or ideas?
Thanks!
PS. If you need more info to help me please ask! :)
I understand how to internationalize a java program, but I have a problem.
Language in my program can be switched anytime, but my program can exist in many states, which means that it may or may not have several JLabels, JPanels, JFrames, etc, open. Is there a class or a method which will update the current GUI to the switched language, or does it have to be done manually?
If nothing else works, I'll just require user to restart the program to switch the language, but runtime change would be nice...
The solution generally used is to have a hash of user-facing strings in a central manager class. You make a call into that class whenever you want to populate a field with data:
JLabel label = new JLabel();
label.setText(LocalizationManager.get("MY_LABEL_TEXT"));
Inside the LocalizationManager you will have to fetch the current language of the program, then look up the appropriate string for MY_LABEL_TEXT in the appropriate language. The manager then returns the now 'localized' string, or some default if the language or string isn't available.
Think of the manager as a slightly more complicated Map; it's mapping from a key (ie 'MY_LABEL_TEXT') to what you want to display ("Good day!" or "Bienvenido!") depending on which language you're in. There are a lot of ways to implement this, but you want the manager to be static or a singleton (loaded once) for memory/performance reasons.
For instance: (1)
public class LocalizationManager {
private SupportedLanguage currentLanguage = SupportedLanguage.ENGLISH;//defaults to english
private Map<SupportedLanguage, Map<String, String>> translations;
public LocalizationManager() {
//Initialize the strings.
//This is NOT a good way; don't hardcode it. But it shows how they're set up.
Map<String, String> english = new HashMap<String, String>();
Map<String, String> french = new HashMap<String, String>();
english.set("MY_LABEL_TEXT", "Good day!");
french.set("MY_LABEL_TEXT", "Beinvenido!");//is that actually french?
translations.set(SupportedLanguage.ENGLISH, english);
translations.set(SupportedLanguage.FRENCH, french);
}
public get(String key) {
return this.translations.get(this.currentLanguage).get(key);
}
public setLanguage(SupportedLanguage language) {
this.currentLanguage = language;
}
public enum SupportedLanguage {
ENGLISH, CHINESE, FRENCH, KLINGON, RUSSIAN;
}
}
(1) I haven't tested this, nor is it a singleton, but it's an off the cuff example.
I am working on a project that has been through multiple hands with a sometimes rushed development. Over time the message.properties file has become out of sync with the jsps that use it. Now I don't know which properties are used and which aren't. Is there a tool (eclipse plugin perhaps) that can root out dead messages?
The problem is that messages may be accessed by JSP or Java, and resource names may be constructed rather than literal strings.
Simple grepping may be able to identify "obvious" resource access. The other solution, a resource lookup mechanism that tracks what's used, is only semi-reliable as well since code paths may determine which resources are used, and unless every path is traveled, you may miss some.
A combination of the two will catch most everything (over time).
Alternatively you can hide the functionality of ResourceBundle behind another façade ResourceBundle, which should generally pipe all calls to original one, but add logging and/or statistics collection on the top.
The example can be as following:
import java.util.Collection;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.NoSuchElementException;
import java.util.ResourceBundle;
public class WrapResourceBundle {
static class LoggingResourceBundle extends ResourceBundle {
private Collection<String> usedKeys = new HashSet<String>();
public LoggingResourceBundle(ResourceBundle parentResourceBundle) {
setParent(parentResourceBundle);
}
#Override
protected Object handleGetObject(String key) {
Object value = parent.getObject(key);
if (value != null) {
usedKeys.add(key);
return value;
}
return null;
}
#Override
public Enumeration<String> getKeys() {
return EMPTY_ENUMERATOR;
}
public Collection<String> getUsedKeys() {
return usedKeys;
}
private static EmptyEnumerator EMPTY_ENUMERATOR = new EmptyEnumerator();
private static class EmptyEnumerator implements Enumeration<String> {
EmptyEnumerator() {
}
public boolean hasMoreElements() {
return false;
}
public String nextElement() {
throw new NoSuchElementException("Empty Enumerator");
}
}
}
public static void main(String[] args) {
LoggingResourceBundle bundle = new LoggingResourceBundle(ResourceBundle.getBundle("test"));
bundle.getString("key1");
System.out.println("Used keys: " + bundle.getUsedKeys());
}
}
Considering that some of your keys are run-time generated, I don't think you'll ever be able to find a tool to validate which keys are in use and which ones are not.
Given the problem you posed, I would probably write an AOP aspect which wraps the MessageSource.getMessage() implementation and log all the requested codes that are being retrieved from the resource bundle. Given that MessageSource is an interface, you would need to know the implementation that you are using, but I suspect that you must know that already.
Given that you would be writing the aspect yourself, you can create a format that is easily correlated against your resource bundle and once you are confident that it contains all the keys required, it becomes a trivial task to compare the two files and eliminate any superfluous lines.
If you really want to be thorough about this, if you already have Spring configured for annotation scan, you could even package up your aspect as its own jar (or .class) and drop it in a production WEB-INF/lib (WEB-INF/classes) folder, restart the webapp and let it run for a while. The great thing about annotations is that it can all be self contained. Once you are sure that you have accumulated enough data you just delete the jar (.class) and you're good to go.
I know that at least two of the major java IDEs can offer this functionality.
IntelliJ IDEA has a (disabled, by default) Inspection that you can
use to do this:
go to Settings -> Inspections -> Properties files -> ... and enable
the 'Unused property'
..Only problem I had was that it didn't pick up some usages of the property from a custom tag library I had written, which I was using in a few JSPs.
Eclipse also has something like this ( http://help.eclipse.org/helios/index.jsp?topic=%2Forg.eclipse.jdt.doc.user%2Ftasks%2Ftasks-202.htm ) but I haven't really exhausted the how well it works.
I have an interface that extends the com.google.gwt.i18n.client.Messages class, which I use for retrieving i18n messages in my GWT application. It looks like this:
public interface MyMessages extends com.google.gwt.i18n.client.Messages {
#DefaultMessage("Hello world")
#Key("message1")
String message1();
#DefaultMessage("Hello again")
#Key("message2")
String message2();
//...
}
Normally, I create an instance of it using GWT.create() like so:
private MyMessages messages = GWT.create(MyMessages.class);
However, this does not work with server-side code, only client-side code (it throws an error saying that GWT.create() is only usable in client-side code).
The answer to a similar question points to a separate library that you can download which will let you access the i18n messages on the server, but I don't want to download any extra libraries (this seems like a simple problem, there must be a simple solution).
In summary: How can I access my i18n messages in server-side code? Thanks.
On the server side you can use the standard Java localization tools like ResourceBundle.
Look here for a tutorial how to use it.
// Create a ResourceBundle out of your property files
ResourceBundle labels =
ResourceBundle.getBundle("LabelsBundle", currentLocale);
// Get localized value
String value = labels.getString(key);
The GWT specific way of creating an interface out of your property files and providing implementations via deferred binding can not be used on sever side Java.
If you are fearless and willing to spend the time, you can implement a code generation step to read your property files and generate implementation classes for your message interface. That's exactly what the Google GWT compiler does behind the scene.
I agree with Michael.. I was having this problem of trying to "localize" messages generated on the server.... but I decided to instead just throw an Exception on the server (because it is an error message which should only happen exceptionally) which contains the message code, which the client code can then look up and show the correct localized message to the user.
There's a great library for GWT internationalization gwt-dmesg. It allows you to 'share' .properties files between clent and server. However, project looks to be abandoned by author and you must recompile it manually for use with GWT versio >= 2.1.0.
GWT.create() can only be used in client-side code.
The good thing to do is that you provide your own I18NProvider class/interface, from which then you can extend to server side I18N factory and client side I18N factory read the same resource bundle.
After that you can simply use it all over your system, unify your code.
Hope that helps.
Following vanje's answer, and considering the encoding used for the properties files (which can be troublesome as ResourceBundle uses by default "ISO-8859-1", here is the solution I came up with:
import java.io.UnsupportedEncodingException;
import java.util.Locale;
import java.util.ResourceBundle;
public class MyResourceBundle {
// feature variables
private ResourceBundle bundle;
private String fileEncoding;
public MyResourceBundle(Locale locale, String fileEncoding){
this.bundle = ResourceBundle.getBundle("com.app.Bundle", locale);
this.fileEncoding = fileEncoding;
}
public MyResourceBundle(Locale locale){
this(locale, "UTF-8");
}
public String getString(String key){
String value = bundle.getString(key);
try {
return new String(value.getBytes("ISO-8859-1"), fileEncoding);
} catch (UnsupportedEncodingException e) {
return value;
}
}
}
The way to use this would be very similar than the regular ResourceBundle usage:
private MyResourceBundle labels = new MyResourceBundle("es", "UTF-8");
String label = labels.getString(key)
Or you can use the alternate constructor which uses UTF-8 by default:
private MyResourceBundle labels = new MyResourceBundle("es");
I am trying to implement internationalization in Tomcat. There are going to be different resource text files. My idea is to load all the resources in to the memory while tomcat loads.
Below is the sample code to load multiple resource in to the memory.
public class ResourceBundleLoader {
private static ResourceBundle enResourceBundle;
private static ResourceBundle frResourceBundle;
public static void loadBundle(){
Locale enLocale = new Locale("en", "US");
enResourceBundle = ResourceBundle.getBundle("MessagesBundle",enLocale);
enLocale = new Locale("fr", "FR");
frResourceBundle = ResourceBundle.getBundle("MessagesBundle",enLocale);
}
public static ResourceBundle getEnResourceBundle(){
return enResourceBundle;
}
public static ResourceBundle getFrResourceBundle(){
return frResourceBundle;
}
}
The method loadBundle is called once thru startup servlet. And getEnResourceBundle() and getFrResourceBundle() is called accordingly. Is this right way to implement/maintain internationalization in tomcat? or is there any better way?
Thanks in advance.
You dont need to make this helper class, as per the java documentation the bundles are already cached for you in memory. This will just make your code more complicated to maintain. ie You would have to alter your code every time you add a new "bundle".
Just add code like this to your servlets and/or JSP's:
//request.getLocale() returns the web browsers locale
bundle = ResourceBundle.getBundle("MessagesBundle",request.getLocale())
Just make sure you have a default message bundle file with all your text. Then you can just add extra locales at will as things get translated.
UTF-8 support
I also strongly suggest you create a servlet filter that applies to all requests that ensures that UTF-8 is turned on for both the html that is output, and the parsing of the form responses that are posted back to your application:
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
I wouldn't optimize until I knew the i18n was too slow.
But if I proceeded down your path, instead of using scalar ResourceBundles, I'd put the ResouceBundles into a Map. Now your code can use any bundle knowing the locale - which you have to select the appropriate ResourceBundle anyway.
Your code won't have any if locale is this, use English. Instead, it will be myResourceBundle = bundleMap.get(myLocale);