/[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 905 by alfonx, Thu Jun 10 08:00:37 2010 UTC revision 1373 by alfonx, Wed Jan 19 12:59:51 2011 UTC
# Line 55  import skrueger.geotools.Copyable; Line 55  import skrueger.geotools.Copyable;
55    
56  /**  /**
57   * Represents a {@link HashMap} of translations. toString() returns the   * Represents a {@link HashMap} of translations. toString() returns the
58   * appropriate translation   * appropriate translation. This class is mutable.
59   *   *
60   * @author @author <a href="mailto:[email protected]">Stefan Alfons   * @author <a href="mailto:[email protected]">Stefan Alfons Tzeggai</a>
  *         Tzeggai</a>  
61   */   */
62    
63  public class Translation extends HashMap<String, String> implements  public class Translation extends HashMap<String, String> implements
64                  Copyable<Translation>, Serializable {                  Copyable<Translation>, Serializable, Cloneable {
65    
66          private static final long serialVersionUID = -347702744122305245L;          private static final long serialVersionUID = -347702744122305245L;
67    
68          public static final String LOCALECHANGE_PROPERTY = "localechange";          public static final String LOCALE_CHANGE_PROPERTY = "localechange";
69            public static final String ACTIVELANG_CHANGE_PROPERTY = "activelangchange";
70          public static final String NO_TRANSLATION = "NO TRANSLATION";          public static final String NO_TRANSLATION = "NO TRANSLATION";
71          public static final String DEFAULT_KEY = "default";          public static final String DEFAULT_KEY = "default";
72          static final Logger LOGGER = Logger.getLogger(Translation.class);          static final Logger LOGGER = Logger.getLogger(Translation.class);
73    
74            /** A static field defining which language should be served **/
75          static String activeLang = Locale.getDefault().getLanguage();          static String activeLang = Locale.getDefault().getLanguage();
76    
77          static protected WeakHashSet<PropertyChangeListener> listeners = new WeakHashSet<PropertyChangeListener>(          /**
78             * A {@link WeakHashSet} of {@link PropertyChangeListener} that will be
79             * informed if the acitveLang has been changed with a setActiveLang(..,true
80             * or false).
81             */
82            static protected WeakHashSet<PropertyChangeListener> listenersActiveLangChange = new WeakHashSet<PropertyChangeListener>(
83                          PropertyChangeListener.class);                          PropertyChangeListener.class);
84    
85          static {          /**
86             * A {@link WeakHashSet} of {@link PropertyChangeListener} that will be
87             * informed if the Locale has been changed due to a setActiveLang(..,true)
88             */
89            static protected WeakHashSet<PropertyChangeListener> listenersLocaleChange = new WeakHashSet<PropertyChangeListener>(
90                            PropertyChangeListener.class);
91    
92                  // TODO default aus Locale auslesen und mit möglichen vergleichen...          /**
93                  // mmm.. vor laden von atlasml immer DEFAULT_KEY, also hier nicht           * A {@link WeakHashSet} of {@link PropertyChangeListener} that will be
94             * informed if any of the translations changed. TODO: Should be registerable
95             * for specific languages
96             */
97            private final WeakHashSet<ActionListener> changeListeners = new WeakHashSet<ActionListener>(
98                            ActionListener.class);
99    
100            static {
101                  // Get default locale                  // Get default locale
102                  Locale locale = Locale.getDefault();                  Locale locale = Locale.getDefault();
103                  setActiveLang(locale.getLanguage());                  setActiveLang(locale.getLanguage());
104          }          }
105    
         private WeakHashSet<ActionListener> actionListeners = new WeakHashSet<ActionListener>(  
                         ActionListener.class);  
   
106          @Override          @Override
107          /*          /**
108           * @comment To make a copy of a translation see methods toOneLine() and           * implemented using #toOneLine and #fromOneLine
          * fromOneLine()  
109           */           */
110          public Translation clone() {          public Translation clone() {
111                  throw new RuntimeException("use copy()");                  Translation clone = new Translation();
112                  // return (Translation) super.clone();                  clone.fromOneLine(toOneLine());
113                    return clone;
114          }          }
115    
116          /**          /**
# Line 108  public class Translation extends HashMap Line 123  public class Translation extends HashMap
123          /**          /**
124           * Set up the {@link Translation}-system to use language. If a change is           * Set up the {@link Translation}-system to use language. If a change is
125           * performed, events are fired to listeners. Nothing is done if the new           * performed, events are fired to listeners. Nothing is done if the new
126           * language equals the old language. The system's default {@link Locale} is changed.           * language equals the old language. The system's default {@link Locale} is
127             * changed.
128           *           *
129           * @param newLang           * @param newLang
130           *            The ISO Code of the new active language           *            The ISO Code of the new active language
# Line 134  public class Translation extends HashMap Line 150  public class Translation extends HashMap
150                  }                  }
151    
152                  if (!I8NUtil.isValidISOLangCode(newLang)) {                  if (!I8NUtil.isValidISOLangCode(newLang)) {
                         throw new IllegalArgumentException("'" + newLang  
                                         + "' is not a valid ISO language code.");  
                 }  
153    
154                  Locale newLocale = new Locale(newLang);                          if (!I8NUtil.isPropertiesLanguage(newLang)) {
155                  if (setDefaultLocale)                                  throw new IllegalArgumentException(
156                          Locale.setDefault(newLocale);                                                  "'"
157                                                                    + newLang
158                                                                    + "' is not a valid ISO language code, nor is it a valid userdefined Properties code.");
159                            }
160    
161                  /**                  }
                  * Setting default locale for Swing JComponents to work around bug  
                  * http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4884480  
                  */  
                 JComponent.setDefaultLocale(newLocale);  
162    
163                  Translation.activeLang = newLang;                  Translation.activeLang = newLang;
164                    fireActiveLangChangeEvents();
165    
166                  fireLocaleChangeEvents();                  Locale newLocale = new Locale(newLang);
167                    if (setDefaultLocale) {
168    
169                            setDefaultLocale(newLocale);
170    
171                            LOGGER.info(Translation.class.getName()
172                                            + " switched ActiveLang and Locale to " + newLang);
173                    } else {
174                            LOGGER.info(Translation.class.getName()
175                                            + " switched ActiveLang to " + newLang);
176                    }
177    
                 LOGGER.info("skrueger.i8n.Translation switched ActiveLang to "  
                                 + newLang);  
178          }          }
179    
180          /**          /**
# Line 175  public class Translation extends HashMap Line 196  public class Translation extends HashMap
196    
197          /**          /**
198           * Initializes a new {@link Translation}, an uses the given String to           * Initializes a new {@link Translation}, an uses the given String to
199           * initialize the {@link Translation} for all languages codes passed.           * initialize the {@link Translation} for all languages codes passed. The
200             * translations can be changed later. This class is not immutable.
201             *
202             * @param languages
203             *            if empty or null, the given default {@link Translation} till
204             *            be stored under a special key {@link #DEFAULT_KEY}
205             *
206           *           *
          * The translations can be changed later  
207           */           */
208          public Translation(List<String> languages, String defaultTranslation) {          public Translation(List<String> languages, String defaultTranslation) {
209                  // put(DEFAULT_KEY, defaultTranslation);                  if (languages == null || languages.isEmpty()) {
                 if (languages == null) {  
210                          put(DEFAULT_KEY, defaultTranslation);                          put(DEFAULT_KEY, defaultTranslation);
211                  } else                  } else
212                          for (String code : languages) {                          for (String code : languages) {
                                 // if (code.equals(getActiveLang())) {  
213                                  put(code, defaultTranslation);                                  put(code, defaultTranslation);
                                 // }  
214                          }                          }
215          }          }
216    
# Line 254  public class Translation extends HashMap Line 277  public class Translation extends HashMap
277          }          }
278    
279          /**          /**
280           * Returns the right translation by using the {@link #activeLang} field. If           * Returns the correct translation by using the {@link #activeLang} field.
281           * no translation is set, an ugly String {@link #NO_TRANSLATION} will re           * If no translation is set, an ugly String {@link #NO_TRANSLATION} will re
282           * returned. This might be changed for the final release. If the correct           * returned. This might be changed for the final release. If the correct
283           * language was not found, any entry in the {@link Translation}           * language was not found, any entry in the {@link Translation}
284           * {@link HashMap} will be returned, that contains more than an empty           * {@link HashMap} will be returned, that contains more than an empty
# Line 263  public class Translation extends HashMap Line 286  public class Translation extends HashMap
286           */           */
287          @Override          @Override
288          public String toString() {          public String toString() {
289                  if (get(activeLang) != null) {                  final String string = get(activeLang);
290                    if (string != null) {
291                          return get(activeLang);                          return get(activeLang);
292                  }                  }
293                  // ****************************************************************************                  // ****************************************************************************
# Line 272  public class Translation extends HashMap Line 296  public class Translation extends HashMap
296                  // ****************************************************************************                  // ****************************************************************************
297                  // else return "";                  // else return "";
298                  // //****************************************************************************                  // //****************************************************************************
299                  // // The following is commented out.. the concept of the default lang                  // // ST: The following is commented out.. the concept of the default
300                    // lang
301                  // seems to be bad....                  // seems to be bad....
302                  // //****************************************************************************                  // //****************************************************************************
303                  // MS:                  // MS:
# Line 304  public class Translation extends HashMap Line 329  public class Translation extends HashMap
329           */           */
330          public static void addLocaleChangeListener(          public static void addLocaleChangeListener(
331                          PropertyChangeListener propertyChangeListener) {                          PropertyChangeListener propertyChangeListener) {
332                  listeners.add(propertyChangeListener);                  listenersLocaleChange.add(propertyChangeListener);
333          }          }
334    
335          /**          /**
# Line 319  public class Translation extends HashMap Line 344  public class Translation extends HashMap
344           */           */
345          public static boolean removeLocaleChangeListener(          public static boolean removeLocaleChangeListener(
346                          PropertyChangeListener propertyChangeListener) {                          PropertyChangeListener propertyChangeListener) {
347                  return listeners.remove(propertyChangeListener);                  return listenersLocaleChange.remove(propertyChangeListener);
348            }
349    
350            /**
351             * {@link PropertyChangeListener} can be registered to be informed when the
352             * {@link Locale} changed.<br>
353             * The listeners are kept in a {@link WeakHashMap}, so you have to keep a
354             * reference to the listener or it will be removed!
355             *
356             * @param propertyChangeListener
357             *            A {@link PropertyChangeListener} that will be called when
358             *            {@link #setActiveLang(String)} changes the language.
359             */
360            public static void addActiveLangChangeListener(
361                            PropertyChangeListener propertyChangeListener) {
362                    listenersActiveLangChange.add(propertyChangeListener);
363            }
364    
365            /**
366             * {@link PropertyChangeListener} can be registered to be informed when the
367             * {@link Locale} changed.<br>
368             * The listeners are kept in a {@link WeakHashMap}, so you have to keep a
369             * reference to the listener or it will be removed!
370             *
371             * @param propertyChangeListener
372             *            A {@link PropertyChangeListener} that will be called when
373             *            {@link #setActiveLang(String)} changes the language.
374             */
375            public static boolean removeActiveLangListener(
376                            PropertyChangeListener propertyChangeListener) {
377                    return listenersActiveLangChange.remove(propertyChangeListener);
378          }          }
379    
380          /**          /**
381           * Informs all registered {@link PropertyChangeListener}s about a change of           * Informs all registered {@link PropertyChangeListener}s about a change of
382           * the the {@link Locale}.           * type LOCALE_CHANGE_PROPERTY the the {@link Locale}.
383           */           */
384          public static void fireLocaleChangeEvents() {          public static void fireLocaleChangeEvents() {
385                  PropertyChangeEvent pce = new PropertyChangeEvent(new Translation(                  PropertyChangeEvent pce = new PropertyChangeEvent(new Translation(
386                                  new ArrayList<String>(), "fakeSource"), LOCALECHANGE_PROPERTY,                                  new ArrayList<String>(), "fakeSource"), LOCALE_CHANGE_PROPERTY,
387                                  null, getActiveLang());                                  null, getActiveLang());
388                  for (PropertyChangeListener pcl : listeners) {                  for (PropertyChangeListener pcl : listenersLocaleChange) {
389                            if (pcl != null)
390                                    pcl.propertyChange(pce);
391                    }
392            }
393    
394            /**
395             * Informs all registered {@link PropertyChangeListener}s about a change of
396             * type ACTIVELANG_CHANGE_PROPERTY the the {@link Locale}.
397             */
398            public static void fireActiveLangChangeEvents() {
399                    PropertyChangeEvent pce = new PropertyChangeEvent(new Translation(
400                                    new ArrayList<String>(), "fakeSource"),
401                                    ACTIVELANG_CHANGE_PROPERTY, null, getActiveLang());
402                    for (PropertyChangeListener pcl : listenersActiveLangChange) {
403                          if (pcl != null)                          if (pcl != null)
404                                  pcl.propertyChange(pce);                                  pcl.propertyChange(pce);
405                  }                  }
# Line 341  public class Translation extends HashMap Line 410  public class Translation extends HashMap
410           * reference as long as you need the listener.           * reference as long as you need the listener.
411           */           */
412          public void addTranslationChangeListener(ActionListener actionListener) {          public void addTranslationChangeListener(ActionListener actionListener) {
413                  if (actionListeners.add(actionListener)) {                  if (changeListeners.add(actionListener)) {
414                          // LOGGER                          // LOGGER
415                          // .debug("registering a new translationChangeActionListener in the WeakHashSet");                          // .debug("registering a new translationChangeActionListener in the WeakHashSet");
416                  }                  }
# Line 353  public class Translation extends HashMap Line 422  public class Translation extends HashMap
422           * listener.           * listener.
423           */           */
424          public boolean removeTranslationChangeListener(ActionListener actionListener) {          public boolean removeTranslationChangeListener(ActionListener actionListener) {
425                  return actionListeners.remove(actionListener);                  return changeListeners.remove(actionListener);
426          }          }
427    
428          public void fireTranslationChangedEvents(String lang) {          public void fireTranslationChangedEvents(String lang) {
429                  ActionEvent ae = new ActionEvent(this, new Random().nextInt(), lang);                  ActionEvent ae = new ActionEvent(this, new Random().nextInt(), lang);
430    
431                  final Iterator<ActionListener> iterator = actionListeners.iterator();                  final Iterator<ActionListener> iterator = changeListeners.iterator();
432                  while (iterator.hasNext()) {                  while (iterator.hasNext()) {
433                          ActionListener al = iterator.next();                          ActionListener al = iterator.next();
434                          al.actionPerformed(ae);                          al.actionPerformed(ae);
# Line 382  public class Translation extends HashMap Line 451  public class Translation extends HashMap
451    
452          /**          /**
453           * Copy this {@link Translation} to another {@link Translation} e.g. for           * Copy this {@link Translation} to another {@link Translation} e.g. for
454           * editing           * editing and return the target.
455           *           *
456           * @return the destination {@link Translation}           * @return the destination {@link Translation}
457           */           */
458          @Override          @Override
459          public Translation copyTo(Translation translation2) {          public Translation copyTo(Translation translation2) {
   
460                  if (translation2 == null)                  if (translation2 == null)
                         // throw new IllegalArgumentException(  
                         // "Target translation may not be null.");  
461                          return copy();                          return copy();
                 for (String s : keySet()) {  
                         translation2.put(s, get(s));  
                 }  
462    
463                    translation2.fromOneLine(toOneLine());
464                  return translation2;                  return translation2;
465          }          }
466    
# Line 424  public class Translation extends HashMap Line 488  public class Translation extends HashMap
488          }          }
489    
490          /**          /**
491           * Goes through the available languages of the FIRST registered {@link ResourceProvider} and set the active locale to the fist match.           * Goes through the available languages of the FIRST registered
492             * {@link ResourceProvider} and set the active locale to the fist match.
493             *
494             * @param fireChangeEvent
495             *            if <code>true</code>, a Translation.fireLocaleChangeEvents()
496             *            is issued.
497           *           *
          * @param fireChangeEvent if <code>true</code>, a Translation.fireLocaleChangeEvents() is issued.  
   
498           * @return           * @return
499           */           */
500          public static boolean setFirstmatchingLanguage(List<String> languages,          public static boolean setFirstmatchingLanguage(List<String> languages,
# Line 452  public class Translation extends HashMap Line 519  public class Translation extends HashMap
519                  return false;                  return false;
520    
521          }          }
522    
523            /**
524             * Returns the translation in a requested language
525             */
526            public String toString(String lang) {
527                    return get(lang);
528            }
529    
530            /**
531             * Will set the default Locale (if not already equal) and fire Locale change
532             * events.
533             *
534             * @param if <code>null</code> will do nothing.
535             */
536            public static void setDefaultLocale(Locale locale) {
537    
538                    if (locale == null)
539                            return;
540    
541                    if (I8NUtil.isPropertiesLanguage(locale.getLanguage())) {
542                            locale = I8NUtil.propLocales.get(locale.getLanguage())
543                                            .getParentLocale();
544                    }
545    
546                    if (Locale.getDefault().equals(locale))
547                            return;
548                    Locale.setDefault(locale);
549                    /**
550                     * Setting default locale for Swing JComponents to work around bug
551                     * http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4884480
552                     */
553                    JComponent.setDefaultLocale(locale);
554    
555                    fireLocaleChangeEvents();
556            }
557    
558  }  }

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

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26