Statistics
| Revision:

svn-gvsig-desktop / tags / v10_RC2c / libraries / libInternationalization / src / org / gvsig / i18n / Messages.java @ 8745

History | View | Annotate | Download (22.1 KB)

1
/* gvSIG. Sistema de Informaci?n Geogr?fica de la Generalitat Valenciana
2
*
3
* Copyright (C) 2006 IVER T.I. and Generalitat Valenciana.
4
*
5
* This program is free software; you can redistribute it and/or
6
* modify it under the terms of the GNU General Public License
7
* as published by the Free Software Foundation; either version 2
8
* of the License, or (at your option) any later version.
9
*
10
* This program is distributed in the hope that it will be useful,
11
* but WITHOUT ANY WARRANTY; without even the implied warranty of
12
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
* GNU General Public License for more details.
14
*
15
* You should have received a copy of the GNU General Public License
16
* along with this program; if not, write to the Free Software
17
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307,USA.
18
*
19
* For more information, contact:
20
*
21
*  Generalitat Valenciana
22
*   Conselleria d'Infraestructures i Transport
23
*   Av. Blasco Ib??ez, 50
24
*   46010 VALENCIA
25
*   SPAIN
26
*
27
*      +34 963862235
28
*   gvsig@gva.es
29
*      www.gvsig.gva.es
30
*
31
*    or
32
*
33
*   IVER T.I. S.A
34
*   Salamanca 50
35
*   46005 Valencia
36
*   Spain
37
*
38
*   +34 963163400
39
*   dac@iver.es
40
*/
41

    
42
package org.gvsig.i18n;
43

    
44
import java.io.File;
45
import java.net.MalformedURLException;
46
import java.net.URL;
47
import java.net.URLClassLoader;
48
import java.util.ArrayList;
49
import java.util.Enumeration;
50
import java.util.HashMap;
51
import java.util.List;
52
import java.util.Locale;
53
import java.util.MissingResourceException;
54
import java.util.ResourceBundle;
55
import java.util.StringTokenizer;
56

    
57
import org.apache.log4j.Logger;
58

    
59
/**
60
 * <p>This class offers some methods to provide internationalization services
61
 * to other projects. All the methods are static.</p>
62
 * 
63
 * <p>The most useful method is {@link #getText(String) getText(key)} (and family),
64
 * which returns the translation associated
65
 * with the provided key. The class must be initialized before getText can be
66
 * used.</p>
67
 * 
68
 * <p>The typical usage sequence would be:</p>
69
 * <ul>
70
 * <li>Add some locale to the prefered locales list: <code>Messages.addLocale(new Locale("es"))</code></li>
71
 * <li>Add some resource file containing translations: <code>Messages.addResourceFamily("text", new File("."))</code></li>
72
 * <li>And finaly getText can be used: <code>Messages.getText("aceptar")</code></li>
73
 * </ul>
74
 * 
75
 * <p>The resource files are Java properties files, which contain <code>key=translation</code>
76
 * pairs, one
77
 * pair per line. These files must be encoded using iso-8859-1 encoding, and unicode escaped
78
 * sequences must be used to include characters outside the former encoding.
79
 * There are several ways to specify the property file to load, see the different
80
 * addResourceFamily methods for details.</p> 
81
 * 
82
 * @author Cesar Martinez Izquierdo (cesar.martinez@iver.es)
83
 *
84
 */
85
public class Messages {
86
    private static Logger logger = Logger.getLogger("Messages");
87
    private static String _CLASSNAME = "org.gvsig.i18n.Messages";
88
    private static int _INITIALSIZE = 3700; // I try to set an initial capacity similar to the amount of strings in gvSIG
89
    
90
    /* Each entry will contain a hashmap with translations. Each hasmap
91
     * contains the translations for one language, indexed by the
92
     * translation key. The translations for language (i) in the preferred locales
93
     * list are contained in the position (i) of the localeResources list */
94
    private static ArrayList localeResources = new ArrayList(); 
95
        private static ArrayList preferredLocales = new ArrayList(); // contains the ordered list of prefered languages/locales (class Locale)
96
        
97
        /**
98
         * <p>Gets the localized message associated with the provided key.
99
         * If the key is not in the dictionary, return the key and register
100
         * the failure in the log.</p>
101
         * 
102
         * <p>The <code>callerName</code> parameter is only
103
         * used as a label when logging, so any String can be used. However, a
104
         * meaningful String should be used, such as the name of the class requiring
105
         * the translation services, in order to identify the source of the failure
106
         * in the log.</p>    
107
         * 
108
         * @param key         An String which identifies the translation that we want to get. 
109
         * @param callerName  A symbolic name given to the caller of this method, to
110
         *                    show it in the log if the key was not found
111
         * @return            an String with the message associated with the provided key.
112
         *                    If the key is not in the dictionary, return the key. If the key
113
         *                    is null, return null.
114
         */
115
        public static String getText(String key, String callerName) {
116
                if (key==null) return null;
117
                for (int numLocale=0; numLocale<localeResources.size(); numLocale++) {
118
                        // try to get the translation for any of the languagues in the preferred languages list
119
                        String translation = (String) ((HashMap)localeResources.get(numLocale)).get(key);
120
                        if (translation!=null && !translation.equals(""))
121
                                return translation;
122
                }
123
                logger.warn(callerName+" "+Messages.getText("Messages._no_se_encontro_la_traduccion_para", _CLASSNAME ,false)+" "+key);
124
                return key;
125
        }
126
        
127
        /**
128
         * <p>Gets the localized message associated with the provided key.
129
         * If the key is not in the dictionary or the translation is empty,
130
         * return the key and register the failure in the log.</p>
131
         * 
132
         * @param key     An String which identifies the translation that we want to get.
133
         * @return        an String with the message associated with the provided key.
134
         *                If the key is not in the dictionary or the translation is empty,
135
         *                return the key. If the key is null, return null.
136
         */
137
        public static String getText(String key) {
138
                return getText(key, _CLASSNAME);
139
        }
140
        
141
        /**
142
         * <p>Gets the localized message associated with the provided key.
143
         * If the key is not in the dictionary or the translation is empty,
144
         * it returns null and the failure is only registered in the log if
145
         * the param log is true.</p>
146
         * 
147
         * @param key        An String which identifies the translation that we want
148
         *                                 to get.
149
         * @param log        Determines whether log a key failure or not
150
         * @return                an String with the message associated with the provided key,
151
         *                                 or null if the key is not in the dictionary or the
152
         *                                 translation is empty.
153
         */
154
        public static String getText(String key, boolean log) {
155
                return getText(key, _CLASSNAME, log);
156
        }
157
        
158
        /**
159
         * <p>Gets the localized message associated with the provided key.
160
         * If the key is not in the dictionary, it returns null and the failure
161
         * is only registered in the log if the param log is true.</p>
162
         * 
163
         * @param key         An String which identifies the translation that we want to get.
164
         * @param callerName  A symbolic name given to the caller of this method, to
165
         *                    show it in the log if the key was not found
166
         * @param log         Determines whether log a key failure or not
167
         * @return            an String with the message associated with the provided key,
168
         *                    or null if the key is not in the dictionary.
169
         */
170
        public static String getText(String key, String callerName, boolean log) {
171
                if (key==null) return null;
172
                for (int numLocale=0; numLocale<localeResources.size(); numLocale++) {
173
                        // try to get the translation for any of the languagues in the preferred languages list
174
                        String translation = (String) ((HashMap)localeResources.get(numLocale)).get(key);
175
                        if (translation!=null && !translation.equals(""))
176
                                return translation;
177
                }
178
                if (log) {
179
                        logger.warn(callerName+" "+Messages.getText("Messages._no_se_encontro_la_traduccion_para", _CLASSNAME ,false)+" "+key);
180
                }
181
                return null;
182
        }
183

    
184
        /**
185
         * <p>Adds an additional family of resource files containing some translations.
186
         * A family is a group of files with a common baseName.
187
         * The file must be an iso-8859-1 encoded file, which can contain any unicode
188
         * character using unicode escaped sequences, and following the syntax:
189
         * <code>key1=value1
190
         * key2=value2</code>
191
         * where 'key1' is the key used to identify the string and must not
192
         * contain the '=' symbol, and 'value1' is the associated translation.</p>
193
         * <p<For example:</p>
194
         * <code>cancel=Cancelar
195
         * accept=Aceptar</code>
196
         * <p>Only one pair key-value is allowed per line.</p>
197
         * 
198
         * <p>The actual name of the resource file to load is determined using the rules
199
         * explained in the class java.util.ResourceBundle. Summarizing, for each language
200
         * in the specified preferred locales list it will try to load a file with
201
         *  the following structure: <code>family_locale.properties</code></p>
202
         *
203
         * <p>For example, if the preferred locales list contains {"fr", "es", "en"}, and
204
         * the family name is "text", it will try to load the files "text_fr.properties",
205
         * "text_es.properties" and finally "text_en.properties".</p>
206
         * 
207
         * <p>Locales might be more specific, such us "es_AR"  (meaning Spanish from Argentina)
208
         * or "es_AR_linux" (meaning Linux system preferring Spanish from Argentina). In the
209
         * later case, it will try to load "text_es_AR_linux.properties", then
210
         * "text_es_AR.properties" if the former fails, and finally "text_es.properties".</p>
211
         * 
212
         * <p>The directory used to locate the resource file is determining by using the
213
         * getResource method from the provided ClassLoader.</p>
214
         *  
215
         * @param family    The family name (or base name) which is used to search
216
         *                  actual properties files.
217
         * @param loader    A ClassLoader which is able to find a property file matching
218
         *                                         the specified family name and the preferred locales
219
         * @see             <a href="http://java.sun.com/j2se/1.4.2/docs/api/java/util/ResourceBundle.html">ResourceBundle</a>
220
         */
221
        public static void addResourceFamily(String family, ClassLoader loader) {
222
                addResourceFamily(family, loader, "");
223
        }
224
        
225
        /**
226
         * <p>Adds an additional family of resource files containing some translations.
227
         * The search path to locate the files is provided by the dirList parameter.</p>
228
         * 
229
         * <p>See {@link addResourceFamily(String, ClassLoader)} for a discussion about the
230
         * format of the property files and the way to determine the candidat files
231
         * to load. Note that those methods are different in the way to locate the 
232
         * candidat files. This method searches in the provided paths (<code>dirList</code>
233
         * parameter), while the referred method searches using the getResource method
234
         * of the provided ClassLoader.</p>
235
         *  
236
         * @param family    The family name (or base name) which is used to search
237
         *                  actual properties files.
238
         * @param dirList   A list of search paths to locate the property files
239
         * @throws MalformedURLException
240
         * @see             <a href="http://java.sun.com/j2se/1.4.2/docs/api/java/util/ResourceBundle.html">ResourceBundle</a>
241
         */
242
        public static void addResourceFamily(String family, File[] dirList) throws MalformedURLException{
243
                // use our own classloader
244
                URL[] urls = new URL[dirList.length];                
245
        
246
                        int i;
247
                        for (i=0; i<urls.length; i++) {
248
                                urls[i] = dirList[i].toURL();
249
                        }
250
        
251
                ClassLoader loader = new MessagesClassLoader(urls);
252
                addResourceFamily(family, loader, "");
253
        }
254

    
255
        /**
256
         * <p>Adds an additional family of resource files containing some translations.
257
         * The search path to locate the files is provided by the dir parameter.</p>
258
         * 
259
         * <p>See {@link addResourceFamily(String, ClassLoader)} for a discussion about the
260
         * format of the property files and the way to determine the candidat files
261
         * to load. Note that those methods are different in the way to locate the 
262
         * candidat files. This method searches in the provided path (<code>dir</code>
263
         * parameter), while the referred method searches using the getResource method
264
         * of the provided ClassLoader.</p>
265
         *  
266
         * @param family    The family name (or base name) which is used to search
267
         *                  actual properties files.
268
         * @param dir       The search path to locate the property files
269
         * @throws MalformedURLException
270
         * @see             <a href="http://java.sun.com/j2se/1.4.2/docs/api/java/util/ResourceBundle.html">ResourceBundle</a>
271
         */
272
        public static void addResourceFamily(String family, File dir) throws MalformedURLException{
273
                // use our own classloader
274
                URL[] urls = new URL[1];                
275
                urls[0] = dir.toURL();
276
                ClassLoader loader = new MessagesClassLoader(urls);
277
                addResourceFamily(family, loader, "");
278
        }
279

    
280

    
281
        /**
282
         * <p>Adds an additional family of resource files containing some translations.
283
         * The search path is determined by the getResource method from the
284
         * provided ClassLoader.</p>
285
         * 
286
         * <p>This method is identical to {@link addResourceFamily(String, ClassLoader)},
287
         * except that it adds a <pode>callerName</code> parameter to show in the log.</p>
288
         * 
289
         * <p>See {@link addResourceFamily(String, ClassLoader)} for a discussion about the
290
         * format of the property files andthe way to determine the candidat files
291
         * to load.</p>
292
         *  
293
         * @param family      The family name (or base name) which is used to search
294
         *                    actual properties files.
295
         * @param loader      A ClassLoader which is able to find a property file matching
296
         *                                           the specified family name and the preferred locales
297
         * @param callerName  A symbolic name given to the caller of this method, to
298
         *                    show it in the log if there is an error
299
         * @see               <a href="http://java.sun.com/j2se/1.4.2/docs/api/java/util/ResourceBundle.html">ResourceBundle</a>
300
         */
301
        public static void addResourceFamily(String family, ClassLoader loader, String callerName) {
302
                String currentKey;
303
                Enumeration properties;
304
                int totalLocales = preferredLocales.size();
305

    
306
                if (totalLocales == 0) {
307
                        // if it's empty, warn about that
308
                        logger.warn(Messages.getText("Messages.no.hay.lista.de.idiomas.preferidos.quiza.olvido.inicializar.clase", _CLASSNAME, false));
309
                }
310
                Locale lang;                
311
                ResourceBundle bundle = null;
312
                
313
                for (int numLocale=0; numLocale<totalLocales; numLocale++) { // for each language
314
                        lang = (Locale) preferredLocales.get(numLocale);
315
                        try {
316
                                /**
317
                                 * Here we are doing a pervert use of getBundle method. Normally, it is call it in in this way:
318
                                 * getBundle("text", "en", loader), in order to get the file 'text_en.properties'. However, in
319
                                 * this way the default file ('text.properties') is also loaded, and we want to avoid this
320
                                 * (because 'text.properties contains the Spanish translation).
321
                                 * So we use the method in this non-standard way:
322
                                 * getBundle("text_en", "en", loader), ensuring that we are just loading the file 'text_en.properties'
323
                                 **/
324
                                if (!lang.getLanguage().equals("es"))
325
                                        bundle = ResourceBundle.getBundle(family+"_"+lang.getLanguage(), lang, loader);
326
                                else // we allow 'text.properties' to be loaded for Spanish
327
                                        bundle = ResourceBundle.getBundle(family, lang, loader);
328
                                
329
                                properties = bundle.getKeys();
330
                                while (properties.hasMoreElements()) {
331
                                        currentKey = (String) properties.nextElement();
332
                                        if (! ((HashMap)localeResources.get(numLocale)).containsKey(currentKey)) {
333
                                                ((HashMap)localeResources.get(numLocale)).put(currentKey, bundle.getString(currentKey));
334
                                        }
335
                                }
336
                        }
337
                        catch (MissingResourceException ex) {
338
                                logger.warn(Messages.getText("Messages.las_traducciones_no_pudieron_ser_cargadas", false)+" -- "+callerName+" -- "+lang.getLanguage());
339
                        }
340
                }
341
        }
342
        
343
        /**
344
         * <p>Adds an additional family of resource files containing some translations.</p>
345
         * 
346
         * <p>This method is identical to {@link addResourceFamily(String, ClassLoader, String)},
347
         * except that it uses the caller's class loader.</p>
348
         * 
349
         * <p>See {@link addResourceFamily(String, ClassLoader)} for a discussion about the
350
         * format of the property files and the way to determine the candidat files
351
         * to load.</p>
352
         *  
353
         * @param family      The family name (or base name) which is used to search
354
         *                    actual properties files.
355
         * @param callerName  A symbolic name given to the caller of this method, to
356
         *                    show it in the log if there is an error. This is only used
357
         *                    to show
358
         *                    something meaningful in the log, so you can use any string
359
         * @see               <a href="http://java.sun.com/j2se/1.4.2/docs/api/java/util/ResourceBundle.html">ResourceBundle</a>
360
         */
361
        public static void addResourceFamily(String family, String callerName) {
362
                String currentKey;
363
                Enumeration properties;
364
                int totalLocales = preferredLocales.size();
365

    
366
                if (totalLocales == 0) {
367
                        // if it's empty, warn about that
368
                        logger.warn(Messages.getText("Messages.no.hay.lista.de.idiomas.preferidos.quiza.olvido.inicializar.clase", _CLASSNAME, false));
369
                }
370
                Locale lang;                
371
                ResourceBundle bundle = null;
372
                
373
                for (int numLocale=0; numLocale<totalLocales; numLocale++) { // for each language
374
                        try {
375
                                lang = (Locale) preferredLocales.get(numLocale);
376
                                if (!lang.getLanguage().equals("es"))
377
                                        bundle = ResourceBundle.getBundle(family+"_"+lang.getLanguage(), lang);
378
                                else // we allow 'text.properties' to be loaded for Spanish
379
                                        bundle = ResourceBundle.getBundle(family, lang);
380
                                //bundle = ResourceBundle.getBundle(family, lang);
381
                                //if (bundle.getLocale().getLanguage().equals(lang.getLanguage()) || lang.getLanguage().equals("es")) {
382
                                        // we ensure we didn't get a fallback
383
                                        // (except if lang == "es" -- spanish is the default language, so we accept a the main translation file for it)
384
        
385
                                        properties = bundle.getKeys();
386
                                        while (properties.hasMoreElements()) {
387
                                                currentKey = (String) properties.nextElement();
388
                                                if (! ((HashMap)localeResources.get(numLocale)).containsKey(currentKey)) {
389
                                                        ((HashMap)localeResources.get(numLocale)).put(currentKey, bundle.getString(currentKey));
390
                                                }
391
                                        }
392
                                //}
393
                                /*else {
394
                                        logger.warn(Messages.getText("Messages.las_traducciones_no_pudieron_ser_cargadas", false)+" -- "+callerName+" -- "+lang.getLanguage());
395
                                }*/
396
                        }
397
                        catch (MissingResourceException ex) {
398
                                logger.warn(callerName+" " + ex.getLocalizedMessage());
399
                        }
400
                }
401
        }
402
        
403
        
404
        /**
405
         * Returns an ArrayList containing the ordered list of prefered Locales
406
         * Each element of the ArrayList is a Locale object.
407
         * 
408
         * @return an ArrayList containing the ordered list of prefered Locales
409
         * Each element of the ArrayList is a Locale object.
410
         */
411
        public static ArrayList getPreferredLocales() {
412
                return preferredLocales;
413
        }
414
        
415
        /**
416
         * <p>Sets the ordered list of preferred locales.
417
         * Each element of the ArrayList is a Locale object.</p>
418
         * 
419
         * <p>Note that calling this method does not load any translation, it just
420
         * adds the language to the preferred locales list, so this method must
421
         * be always called before the translations are loaded using
422
         * the addResourceFamily() methods.</p>
423
         * 
424
         * @param preferredLocales an ArrayList containing Locale objects.
425
         * The ArrayList represents an ordered list of preferred locales
426
         */
427
        public static void setPreferredLocales(ArrayList preferredLocalesList) {
428
                for (int numLocale=0; numLocale < preferredLocalesList.size(); numLocale++) {
429
                        addLocale((Locale) preferredLocalesList.get(numLocale));
430
                }
431
        }
432

    
433
        /**
434
         * Adds a Locale at the end of the ordered list of preferred locales.
435
         * Note that calling this method does not load any translation, it just
436
         * adds the language to the preferred locales list, so this method must
437
         * be always called before the translations are loaded using
438
         * the addResourceFamily() methods.
439
         * 
440
         * @param lang   A Locale object specifying the locale to add
441
         */
442
        public static void addLocale(Locale lang) {
443
                if (!preferredLocales.contains(lang)) { // avoid duplicates
444
                                preferredLocales.add(lang); // add the lang to the ordered list of preferred locales
445
                                localeResources.add(new HashMap(_INITIALSIZE)); // add a hashmap which will contain the translation for this language
446
                }
447
        }
448

    
449
        /**
450
         * Removes the specified Locale from the list of preferred locales and the
451
         * translations associated with this locale.
452
         * 
453
         * @param lang   A Locale object specifying the locale to remove
454
         * @return       True if the locale was in the preferred locales list, false otherwise
455
         */
456
        public static boolean removeLocale(Locale lang) {
457
                int numLocale = preferredLocales.indexOf(lang);
458
                if (numLocale!=-1) { // we found the locale in the list
459
                        try {
460
                                preferredLocales.remove(numLocale);
461
                                localeResources.remove(numLocale);
462
                        }
463
                        catch (IndexOutOfBoundsException ex) {
464
                                logger.warn(_CLASSNAME + "." + "removeLocale: " + ex.getLocalizedMessage());
465
                        }
466
                        return true;
467
                }
468
                return false;
469
        }
470

    
471
        /**
472
         * Cleans the translation tables (removes all the translations from memory).
473
         */
474
        public static void removeResources() {
475
                for (int numLocale=0; numLocale<localeResources.size(); numLocale++) {
476
                        ((HashMap)localeResources.get(numLocale)).clear();
477
                }
478
        }
479

    
480
        /**
481
         * The number of translation keys which have been loaded till now  
482
         * (In other words: the number of available translation strings).
483
         * 
484
         * @param lang The language for which we want to know the number of translation keys
485
         * return The number of translation keys for the provided language.
486
         */
487
        protected static int size(Locale lang) {
488
                int numLocale = preferredLocales.indexOf(lang);
489
                if (numLocale!=-1) {
490
                        return ((HashMap)localeResources.get(numLocale)).size();
491
                };
492
                return 0;
493
        }
494
        
495
        /**
496
         * Checks if some locale has been added to the preferred locales
497
         * list, which is necessary before loading any translation because
498
         * only the translations for the preferred locales are loaded.
499
         * 
500
         * @return
501
         */
502
        public static boolean hasLocales() {
503
                return preferredLocales.size()>0;
504
        }
505
        
506
        /**
507
         * Searches the subdirectories of the provided directory, finding
508
         * all the translation files, and constructing a list of available translations.
509
         * It reports different country codes or variants, if available.
510
         * For example, if there is an en_US translation and an en_GB translation, both
511
         * locales will be present in the Vector.
512
         * 
513
         * @return
514
         */
515
        
516
        /**
517
         * 
518
         * @return A Vector containing the available locales. Each element is a Locale object
519
         */
520
        /*public static Vector getAvailableLocales() {
521
                return _availableLocales;
522
        }*/
523
        
524
        /**
525
         * 
526
         * @return A Vector containing the available languages. Each element is an String object
527
         */
528
        /*public static Vector getAvailableLanguages() {
529
                Vector availableLanguages = new Vector();
530
                Locale lang;
531
                Enumeration locales = _availableLocales.elements();
532
                while (locales.hasMoreElements()) {
533
                        lang = (Locale) locales.nextElement();
534
                        availableLanguages.add(lang.getLanguage());
535
                }
536
                return availableLanguages;
537
        }*/
538
}