/[schmitzm]/trunk/src/skrueger/i8n/Translation.java
ViewVC logotype

Diff of /trunk/src/skrueger/i8n/Translation.java

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 186 by alfonx, Fri Jul 3 14:40:10 2009 UTC revision 905 by alfonx, Thu Jun 10 08:00:37 2010 UTC
# Line 1  Line 1 
1  package skrueger.i8n;  /*******************************************************************************
2     * Copyright (c) 2009 Martin O. J. Schmitz.
3  import java.beans.PropertyChangeEvent;   *
4  import java.beans.PropertyChangeListener;   * This file is part of the SCHMITZM library - a collection of utility
5  import java.util.ArrayList;   * classes based on Java 1.6, focusing (not only) on Java Swing
6  import java.util.HashMap;   * and the Geotools library.
7  import java.util.List;   *
8  import java.util.Locale;   * The SCHMITZM project is hosted at:
9     * http://wald.intevation.org/projects/schmitzm/
10  import javax.swing.JComponent;   *
11  import javax.swing.JTable;   * This program is free software; you can redistribute it and/or
12     * modify it under the terms of the GNU Lesser General Public License
13  import org.apache.log4j.Logger;   * as published by the Free Software Foundation; either version 3
14     * of the License, or (at your option) any later version.
15  /**   *
16   * Represents a {@link HashMap} of translations. toString() returns the   * This program is distributed in the hope that it will be useful,
17   * appropriate translation   * but WITHOUT ANY WARRANTY; without even the implied warranty of
18   *   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19   * @author @author <a href="mailto:[email protected]">Stefan Alfons   * GNU General Public License for more details.
20   *         Kr&uuml;ger</a>   *
21   */   * You should have received a copy of the GNU Lesser General Public License (license.txt)
22     * along with this program; if not, write to the Free Software
23  public class Translation extends HashMap<String, String> {   * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
24          public static final String LOCALECHANGE_PROPERTY = "localechange";   * or try this link: http://www.gnu.org/licenses/lgpl.html
25          public static final String NO_TRANSLATION = "NO TRANSLATION";   *
26          public static final String DEFAULT_KEY = "default";   * Contributors:
27          static final Logger log = Logger.getLogger(Translation.class);   *     Martin O. J. Schmitz - initial API and implementation
28          static String activeLang = "fr";   *     Stefan A. Tzeggai - additional utility classes
29     ******************************************************************************/
30          static protected List<PropertyChangeListener> listeners = new ArrayList<PropertyChangeListener>();  package skrueger.i8n;
31    
32          static {  import java.awt.event.ActionEvent;
33    import java.awt.event.ActionListener;
34                  // TODO default aus Locale auslesen und mit möglichen vergleichen...  import java.beans.PropertyChangeEvent;
35                  // mmm.. vor laden von atlasml immer DEFAULT_KEY, also hier nicht  import java.beans.PropertyChangeListener;
36    import java.io.Serializable;
37                  // Get default locale  import java.util.ArrayList;
38                  Locale locale = Locale.getDefault();  import java.util.HashMap;
39                  setActiveLang(locale.getLanguage());  import java.util.Iterator;
40          }  import java.util.List;
41    import java.util.Locale;
42          @Override  import java.util.Random;
43          /*  import java.util.Set;
44           * @comment To make a copy of a translation see methods toOneLine() and  import java.util.WeakHashMap;
45           * fromOneLine()  
46           */  import javax.swing.JComponent;
47          public Translation clone() {  
48                  return (Translation) super.clone();  import org.apache.log4j.Logger;
49          }  import org.geotools.util.WeakHashSet;
50    import org.opengis.util.InternationalString;
51          /**  
52           * Get the two-letter language sting that is active  import schmitzm.lang.ResourceProvider;
53           */  import schmitzm.lang.SortableVector;
54          public static String getActiveLang() {  import skrueger.geotools.Copyable;
55                  return activeLang;  
56          }  /**
57     * Represents a {@link HashMap} of translations. toString() returns the
58          /**   * appropriate translation
59           * Set up the {@link Translation}-system to use language. If a change is   *
60           * performed, events are fired to listeners. Nothing is done if the new   * @author @author <a href="mailto:[email protected]">Stefan Alfons
61           * language equals the old language. The system's default locale is changed.   *         Tzeggai</a>
62           *   */
63           * @param newLang  
64           *            The ISO Code of the new active language  public class Translation extends HashMap<String, String> implements
65           */                  Copyable<Translation>, Serializable {
66          public static void setActiveLang(String newLang) {  
67                  setActiveLang(newLang, true);          private static final long serialVersionUID = -347702744122305245L;
68          }  
69            public static final String LOCALECHANGE_PROPERTY = "localechange";
70          /**          public static final String NO_TRANSLATION = "NO TRANSLATION";
71           * Set up the {@link Translation}-system to use language. If a change is          public static final String DEFAULT_KEY = "default";
72           * performed, events are fired to listeners. Nothing is done if the new          static final Logger LOGGER = Logger.getLogger(Translation.class);
73           * language equals the old language.          static String activeLang = Locale.getDefault().getLanguage();
74           *  
75           * @param newLang          static protected WeakHashSet<PropertyChangeListener> listeners = new WeakHashSet<PropertyChangeListener>(
76           *            The ISO Code of the new active language                          PropertyChangeListener.class);
77           *  
78           * @param setDefaultLocale          static {
79           *            Shall the system's default locale be changed?  
80           */                  // TODO default aus Locale auslesen und mit möglichen vergleichen...
81          public static void setActiveLang(String newLang, boolean setDefaultLocale) {                  // mmm.. vor laden von atlasml immer DEFAULT_KEY, also hier nicht
82                  if (getActiveLang().equals(newLang)) {  
83                          return;                  // Get default locale
84                  }                  Locale locale = Locale.getDefault();
85                    setActiveLang(locale.getLanguage());
86                  if (!I8NUtil.isValidISOLangCode(newLang)) {          }
87                          throw new IllegalArgumentException("'" + newLang  
88                                          + "' is not a valid ISO language code.");          private WeakHashSet<ActionListener> actionListeners = new WeakHashSet<ActionListener>(
89                  }                          ActionListener.class);
90    
91                  Locale newLocale = new Locale(newLang);          @Override
92                  if (setDefaultLocale)          /*
93                          Locale.setDefault(newLocale);           * @comment To make a copy of a translation see methods toOneLine() and
94             * fromOneLine()
95                  /**           */
96                   * Setting default locale for Swing JComponents to work around bug          public Translation clone() {
97                   * http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4884480                  throw new RuntimeException("use copy()");
98                   */                  // return (Translation) super.clone();
99                  JComponent.setDefaultLocale(newLocale);          }
100    
101                  Translation.activeLang = newLang;          /**
102             * Get the two-letter language sting that is active
103                  fireChangeEvents();           */
104            public static String getActiveLang() {
105                  log.info("skrueger.i8n.Translation switched ActiveLang to " + newLang);                  return activeLang;
106          }          }
107    
108          /**          /**
109           * Initializes a new {@link Translation} with a default translation if a           * Set up the {@link Translation}-system to use language. If a change is
110           * simple text is passed. If a "oneLine" text is parsed, it is interpreted.           * performed, events are fired to listeners. Nothing is done if the new
111           * Other translations may be added later - this is a HashMap<br/>           * language equals the old language. The system's default {@link Locale} is changed.
112           *           *
113           * @param defaultTranslation           * @param newLang
114           *           *            The ISO Code of the new active language
115           * @see public Translation(List<String> languages, String           */
116           *      defaultTranslation) {          public static void setActiveLang(String newLang) {
117           *                  setActiveLang(newLang, true);
118           */          }
119          public Translation(String defaultTranslation) {  
120            /**
121                  fromOneLine(defaultTranslation);           * Set up the {@link Translation}-system to use language. If a change is
122             * performed, events are fired to listeners. Nothing is done if the new
123          }           * language equals the old language.
124             *
125          /**           * @param newLang
126           * Initializes a new {@link Translation}, an uses the given String to           *            The ISO Code of the new active language
127           * initialize the {@link Translation} for all languages codes passed.           *
128           *           * @param setDefaultLocale
129           * The translations can be changed later           *            Shall the system's default locale be changed?
130           */           */
131          public Translation(List<String> languages, String defaultTranslation) {          public static void setActiveLang(String newLang, boolean setDefaultLocale) {
132                  // put(DEFAULT_KEY, defaultTranslation);                  if (getActiveLang().equals(newLang)) {
133                  if (languages == null) {                          return;
134                          put(DEFAULT_KEY, defaultTranslation);                  }
135                  } else  
136                          for (String code : languages) {                  if (!I8NUtil.isValidISOLangCode(newLang)) {
137                                  if (code.equals(getActiveLang())) {                          throw new IllegalArgumentException("'" + newLang
138                                          put(code, defaultTranslation);                                          + "' is not a valid ISO language code.");
139                                  }                  }
140                          }  
141          }                  Locale newLocale = new Locale(newLang);
142                    if (setDefaultLocale)
143          /**                          Locale.setDefault(newLocale);
144           * Sometimes Translations are optional, like for keywords.  
145           */                  /**
146          public Translation() {                   * Setting default locale for Swing JComponents to work around bug
147          }                   * http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4884480
148                     */
149          /**                  JComponent.setDefaultLocale(newLocale);
150           * Fills the {@link Translation} with the values coded into the String  
151           * Format of {@link String} is: "de{Baum}en{tree}"                  Translation.activeLang = newLang;
152           * <p>  
153           * <ul>                  fireLocaleChangeEvents();
154           * <li>If <code>oneLineCoded</code> is empty or null, NO TRANSLATION is set.  
155           * <li>If format can't be recognized, the {@link String} is interpreted as                  LOGGER.info("skrueger.i8n.Translation switched ActiveLang to "
156           * the translation in the <code>{@value #DEFAULT_KEY}</code> language                                  + newLang);
157           *          }
158           * @author Stefan Alfons Krüger  
159           */          /**
160          public void fromOneLine(final String oneLineCoded) {           * Initializes a new {@link Translation} with a default translation if a
161                  clear();           * simple text is passed. If a "oneLine" text is parsed, it is interpreted.
162                  if ((oneLineCoded == null) || (oneLineCoded.equals(""))) {           * Other translations may be added later - this is a HashMap<br/>
163                          put(DEFAULT_KEY, "");           *
164                          return;           * @param defaultTranslation
165                  }           *
166             * @see public Translation(List<String> languages, String
167                  if (oneLineCoded.indexOf("}") == -1) {           *      defaultTranslation) {
168                          // log.warn("The String '"+oneLineCoded+"' is not in oneLine coded => put(DEFAULT_KEY,oneLineCoded);");           *
169                          put(DEFAULT_KEY, oneLineCoded);           */
170                  }          public Translation(String defaultTranslation) {
171    
172                  String eatUp = oneLineCoded;                  fromOneLine(defaultTranslation);
173                  while (eatUp.indexOf("}") != -1) {  
174                          String substring = eatUp.substring(0, eatUp.indexOf("}"));          }
175    
176                          // log.debug("substring = "+substring);          /**
177                          String key = substring.substring(0, substring.indexOf("{"));           * Initializes a new {@link Translation}, an uses the given String to
178                          String value = substring.substring(substring.indexOf("{") + 1,           * initialize the {@link Translation} for all languages codes passed.
179                                          substring.length());           *
180                          // log.debug("key="+key);           * The translations can be changed later
181                          // log.debug("value="+value);           */
182                          put(key, value);          public Translation(List<String> languages, String defaultTranslation) {
183                          eatUp = eatUp.substring(eatUp.indexOf("}") + 1);                  // put(DEFAULT_KEY, defaultTranslation);
184                  }                  if (languages == null) {
185          }                          put(DEFAULT_KEY, defaultTranslation);
186                    } else
187          /**                          for (String code : languages) {
188           * Exports the Translations to a String of the Format: "de{Baum}en{tree}"                                  // if (code.equals(getActiveLang())) {
189           *                                  put(code, defaultTranslation);
190           * @author Stefan Alfons Krüger                                  // }
191           */                          }
192          public String toOneLine() {          }
193                  return I8NUtil.toOneLine(this);  
194          }          /**
195             * Sometimes Translations are optional, like for keywords.
196          /**           */
197           * Returns the right translation by using the {@link #activeLang} field. If          public Translation() {
198           * no translation is set, an ugly String {@link #NO_TRANSLATION} will re          }
199           * returned. This might be changed for the final release. If the correct  
200           * language was not found, any entry in the {@link Translation}          /**
201           * {@link HashMap} will be returned, that contains more than an empty           * Fills the {@link Translation} with the values coded into the String
202           * string.           * Format of {@link String} is: "de{Baum}en{tree}"
203           */           * <p>
204          @Override           * <ul>
205          public String toString() {           * <li>If <code>oneLineCoded</code> is empty or null, NO TRANSLATION is set.
206                  if (get(activeLang) != null) {           * <li>If format can't be recognized, the {@link String} is interpreted as
207                          return get(activeLang);           * the translation in the <code>{@value #DEFAULT_KEY}</code> language
208                  }           *
209                  // ****************************************************************************           * @author Stefan Alfons Tzeggai
210                  // MS: The ISDSS needs the concept of the default lang!! So I took the           */
211                  // following in again!!          public void fromOneLine(final String oneLineCoded) {
212                  // ****************************************************************************  
213                  // else return "";                  clear();
214                  // //****************************************************************************  
215                  // // The following is commented out.. the concept of the default lang                  try {
216                  // seems to be bad....  
217                  // //****************************************************************************                          if ((oneLineCoded == null) || (oneLineCoded.equals(""))) {
218                  // MS:                                  put(DEFAULT_KEY, "");
219                  else {                                  return;
220                          if (get(DEFAULT_KEY) != null) {                          }
221                                  // log.debug("default lang returned, cuz the translation to "+activeLang+" was not found. Schmeiss raus martin, wenn du das mit der default trans geklärt hast.");  
222                                  return get(DEFAULT_KEY);                          if (oneLineCoded.indexOf("}") == -1) {
223                          }                                  // log.warn("The String '"+oneLineCoded+"' is not in oneLine coded => put(DEFAULT_KEY,oneLineCoded);");
224                                    put(DEFAULT_KEY, oneLineCoded);
225                          // log.debug("return first best <> '' ");                          }
226                          if (size() > 0)  
227                                  for (String s : values()) {                          String eatUp = oneLineCoded;
228                                          if ((s != null) && (s.trim().length() > 0))                          while (eatUp.indexOf("}") != -1) {
229                                                  return s;                                  String substring = eatUp.substring(0, eatUp.indexOf("}"));
230                                  }  
231                  }                                  // log.debug("substring = "+substring);
232                  log.warn("No translation found!");                                  String key = substring.substring(0, substring.indexOf("{"));
233                  return NO_TRANSLATION;                                  String value = substring.substring(substring.indexOf("{") + 1,
234          }                                                  substring.length());
235                                    // log.debug("key="+key);
236          /**                                  // log.debug("value="+value);
237           * Copy this {@link Translation} to another {@link Translation} e.g. for                                  put(key, value);
238           * editing                                  eatUp = eatUp.substring(eatUp.indexOf("}") + 1);
239           *                          }
240           * @return the destination {@link Translation}                  } catch (Exception e) {
241           */                          LOGGER.warn("Error while reading the oneLineCode '" + oneLineCoded
242          public Translation copy(Translation backup) {                                          + "'", e);
243                  if (backup == null)                          LOGGER.warn("Translation will be empty!");
244                          throw new IllegalArgumentException(                  }
245                                          "Target translation may not be null.");          }
246                  for (String s : keySet()) {  
247                          backup.put(s, get(s));          /**
248                  }           * Exports the Translations to a String of the Format: "de{Baum}en{tree}"
249                  return backup;           *
250          }           * @author Stefan Alfons Tzeggai
251             */
252          /**          public String toOneLine() {
253           * {@link PropertyChangeListener} can be registered to be informed when the                  return I8NUtil.toOneLine(this);
254           * {@link Locale} changed.          }
255           *  
256           * @param propertyChangeListener          /**
257           */           * Returns the right translation by using the {@link #activeLang} field. If
258          public static void addLocaleChangeListener(           * no translation is set, an ugly String {@link #NO_TRANSLATION} will re
259                          PropertyChangeListener propertyChangeListener) {           * returned. This might be changed for the final release. If the correct
260                  listeners.add(propertyChangeListener);           * language was not found, any entry in the {@link Translation}
261          }           * {@link HashMap} will be returned, that contains more than an empty
262             * string.
263          /**           */
264           * Informs all registered {@link PropertyChangeListener}s about a change of          @Override
265           * the the {@link Locale}.          public String toString() {
266           */                  if (get(activeLang) != null) {
267          public static void fireChangeEvents() {                          return get(activeLang);
268                  PropertyChangeEvent pce = new PropertyChangeEvent(new Translation(                  }
269                                  new ArrayList<String>(), "fakeSource"), LOCALECHANGE_PROPERTY,                  // ****************************************************************************
270                                  null, getActiveLang());                  // MS: The ISDSS needs the concept of the default lang!! So I took the
271                  for (PropertyChangeListener pcl : listeners) {                  // following in again!!
272                          if (pcl != null)                  // ****************************************************************************
273                                  pcl.propertyChange(pce);                  // else return "";
274                  }                  // //****************************************************************************
275          }                  // // The following is commented out.. the concept of the default lang
276                    // seems to be bad....
277  }                  // //****************************************************************************
278                    // MS:
279                    else {
280                            if (get(DEFAULT_KEY) != null) {
281                                    return get(DEFAULT_KEY);
282                            }
283    
284                            // log.debug("return first best <> '' ");
285                            if (size() > 0)
286                                    for (String s : values()) {
287                                            if ((s != null) && (s.trim().length() > 0))
288                                                    return s;
289                                    }
290                    }
291                    // log.warn("No translation found!");
292                    return NO_TRANSLATION;
293            }
294    
295            /**
296             * {@link PropertyChangeListener} can be registered to be informed when the
297             * {@link Locale} changed.<br>
298             * The listeners are kept in a {@link WeakHashMap}, so you have to keep a
299             * reference to the listener or it will be removed!
300             *
301             * @param propertyChangeListener
302             *            A {@link PropertyChangeListener} that will be called when
303             *            {@link #setActiveLang(String)} changes the language.
304             */
305            public static void addLocaleChangeListener(
306                            PropertyChangeListener propertyChangeListener) {
307                    listeners.add(propertyChangeListener);
308            }
309    
310            /**
311             * {@link PropertyChangeListener} can be registered to be informed when the
312             * {@link Locale} changed.<br>
313             * The listeners are kept in a {@link WeakHashMap}, so you have to keep a
314             * reference to the listener or it will be removed!
315             *
316             * @param propertyChangeListener
317             *            A {@link PropertyChangeListener} that will be called when
318             *            {@link #setActiveLang(String)} changes the language.
319             */
320            public static boolean removeLocaleChangeListener(
321                            PropertyChangeListener propertyChangeListener) {
322                    return listeners.remove(propertyChangeListener);
323            }
324    
325            /**
326             * Informs all registered {@link PropertyChangeListener}s about a change of
327             * the the {@link Locale}.
328             */
329            public static void fireLocaleChangeEvents() {
330                    PropertyChangeEvent pce = new PropertyChangeEvent(new Translation(
331                                    new ArrayList<String>(), "fakeSource"), LOCALECHANGE_PROPERTY,
332                                    null, getActiveLang());
333                    for (PropertyChangeListener pcl : listeners) {
334                            if (pcl != null)
335                                    pcl.propertyChange(pce);
336                    }
337            }
338    
339            /**
340             * The listeneras are stored in a {@link WeakHashSet}! So you HAVE TO KEEP a
341             * reference as long as you need the listener.
342             */
343            public void addTranslationChangeListener(ActionListener actionListener) {
344                    if (actionListeners.add(actionListener)) {
345                            // LOGGER
346                            // .debug("registering a new translationChangeActionListener in the WeakHashSet");
347                    }
348            }
349    
350            /**
351             * The listeneras are stored in a {@link WeakHashSet}! You don't have to
352             * remove the listener, as long as you throw away the reference to the
353             * listener.
354             */
355            public boolean removeTranslationChangeListener(ActionListener actionListener) {
356                    return actionListeners.remove(actionListener);
357            }
358    
359            public void fireTranslationChangedEvents(String lang) {
360                    ActionEvent ae = new ActionEvent(this, new Random().nextInt(), lang);
361    
362                    final Iterator<ActionListener> iterator = actionListeners.iterator();
363                    while (iterator.hasNext()) {
364                            ActionListener al = iterator.next();
365                            al.actionPerformed(ae);
366                    }
367            }
368    
369            @Override
370            public String put(String lang, String value) {
371                    String result = super.put(lang, value);
372                    fireTranslationChangedEvents(lang);
373                    return result;
374            }
375    
376            public void fromOneLine(InternationalString iString) {
377                    if (iString != null)
378                            fromOneLine(iString.toString());
379                    else
380                            fromOneLine((String) null);
381            }
382    
383            /**
384             * Copy this {@link Translation} to another {@link Translation} e.g. for
385             * editing
386             *
387             * @return the destination {@link Translation}
388             */
389            @Override
390            public Translation copyTo(Translation translation2) {
391    
392                    if (translation2 == null)
393                            // throw new IllegalArgumentException(
394                            // "Target translation may not be null.");
395                            return copy();
396                    for (String s : keySet()) {
397                            translation2.put(s, get(s));
398                    }
399    
400                    return translation2;
401            }
402    
403            @Override
404            public Translation copy() {
405                    return copyTo(new Translation());
406            }
407    
408            /**
409             * Checks if the {@link String}s stored in the {@link Translation} are all
410             * valid.
411             *
412             * @return <code>true</code> if all good
413             */
414            public static boolean checkValid(Translation translationToCheck) {
415    
416                    for (String l : translationToCheck.values()) {
417    
418                            if (l.contains("{") || l.contains("}")) {
419    
420                                    return false;
421                            }
422                    }
423                    return true;
424            }
425    
426            /**
427             * Goes through the available languages of the FIRST registered {@link ResourceProvider} and set the active locale to the fist match.
428             *
429             * @param fireChangeEvent if <code>true</code>, a Translation.fireLocaleChangeEvents() is issued.
430    
431             * @return
432             */
433            public static boolean setFirstmatchingLanguage(List<String> languages,
434                            boolean fireChangeEvent) {
435    
436                    SortableVector<ResourceProvider> registeredResourceProvider = ResourceProvider
437                                    .getRegisteredResourceProvider();
438                    Set<Locale> available = ResourceProvider.getAvailableLocales(
439                                    registeredResourceProvider.get(0), true);
440    
441                    for (String l : languages) {
442                            for (Locale loc : available) {
443                                    if (loc.getLanguage().equals(l)) {
444                                            Translation.setActiveLang(l);
445                                            if (fireChangeEvent)
446                                                    Translation.fireLocaleChangeEvents();
447                                            return true;
448                                    }
449                            }
450                    }
451    
452                    return false;
453    
454            }
455    }

Legend:
Removed from v.186  
changed lines
  Added in v.905

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26