/[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

branches/1.0-gt2-2.6/src/skrueger/i8n/Translation.java revision 486 by alfonx, Tue Oct 20 16:25:26 2009 UTC trunk/src/skrueger/i8n/Translation.java revision 1097 by alfonx, Sun Oct 10 21:14:05 2010 UTC
# Line 25  Line 25 
25   *   *
26   * Contributors:   * Contributors:
27   *     Martin O. J. Schmitz - initial API and implementation   *     Martin O. J. Schmitz - initial API and implementation
28   *     Stefan A. Krüger - additional utility classes   *     Stefan A. Tzeggai - additional utility classes
29   ******************************************************************************/   ******************************************************************************/
30  package skrueger.i8n;  package skrueger.i8n;
31    
# Line 33  import java.awt.event.ActionEvent; Line 33  import java.awt.event.ActionEvent;
33  import java.awt.event.ActionListener;  import java.awt.event.ActionListener;
34  import java.beans.PropertyChangeEvent;  import java.beans.PropertyChangeEvent;
35  import java.beans.PropertyChangeListener;  import java.beans.PropertyChangeListener;
36    import java.io.Serializable;
37  import java.util.ArrayList;  import java.util.ArrayList;
38  import java.util.HashMap;  import java.util.HashMap;
39  import java.util.Iterator;  import java.util.Iterator;
40  import java.util.List;  import java.util.List;
41  import java.util.Locale;  import java.util.Locale;
42  import java.util.Random;  import java.util.Random;
43    import java.util.Set;
44    import java.util.WeakHashMap;
45    
46  import javax.swing.JComponent;  import javax.swing.JComponent;
47    
# Line 46  import org.apache.log4j.Logger; Line 49  import org.apache.log4j.Logger;
49  import org.geotools.util.WeakHashSet;  import org.geotools.util.WeakHashSet;
50  import org.opengis.util.InternationalString;  import org.opengis.util.InternationalString;
51    
52    import schmitzm.lang.ResourceProvider;
53    import schmitzm.lang.SortableVector;
54  import skrueger.geotools.Copyable;  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>
  *         Kr&uuml;ger</a>  
61   */   */
62    
63  public class Translation extends HashMap<String, String> implements  public class Translation extends HashMap<String, String> implements
64                  Copyable<Translation> {                  Copyable<Translation>, Serializable, Cloneable {
65    
66            private static final long serialVersionUID = -347702744122305245L;
67    
68          public static final String LOCALECHANGE_PROPERTY = "localechange";          public static final String LOCALECHANGE_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 List<PropertyChangeListener> listeners = new ArrayList<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);
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 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 99  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 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 129  public class Translation extends HashMap Line 154  public class Translation extends HashMap
154                                          + "' is not a valid ISO language code.");                                          + "' is not a valid ISO language code.");
155                  }                  }
156    
                 Locale newLocale = new Locale(newLang);  
                 if (setDefaultLocale)  
                         Locale.setDefault(newLocale);  
   
                 /**  
                  * Setting default locale for Swing JComponents to work around bug  
                  * http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4884480  
                  */  
                 JComponent.setDefaultLocale(newLocale);  
   
157                  Translation.activeLang = newLang;                  Translation.activeLang = newLang;
158                    fireActiveLangChangeEvents();
159    
160                  fireLocaleChangeEvents();                  Locale newLocale = new Locale(newLang);
161                    if (setDefaultLocale) {
162    
163                            Locale.setDefault(newLocale);
164                            /**
165                             * Setting default locale for Swing JComponents to work around bug
166                             * http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4884480
167                             */
168                            JComponent.setDefaultLocale(newLocale);
169    
170                            fireLocaleChangeEvents();
171    
172                            LOGGER.info(Translation.class.getName()
173                                            + " switched ActiveLang and Locale to " + newLang);
174                    } else {
175                            LOGGER.info(Translation.class.getName()
176                                            + " switched ActiveLang to " + newLang);
177                    }
178    
                 LOGGER.info("skrueger.i8n.Translation switched ActiveLang to " + newLang);  
179          }          }
180    
181          /**          /**
# Line 165  public class Translation extends HashMap Line 197  public class Translation extends HashMap
197    
198          /**          /**
199           * Initializes a new {@link Translation}, an uses the given String to           * Initializes a new {@link Translation}, an uses the given String to
200           * initialize the {@link Translation} for all languages codes passed.           * initialize the {@link Translation} for all languages codes passed. The
201             * translations can be changed later. This class is not immutable.
202             *
203             * @param languages
204             *            if empty or null, the given default {@link Translation} till
205             *            be stored under a special key {@link #DEFAULT_KEY}
206             *
207           *           *
          * The translations can be changed later  
208           */           */
209          public Translation(List<String> languages, String defaultTranslation) {          public Translation(List<String> languages, String defaultTranslation) {
210                  // put(DEFAULT_KEY, defaultTranslation);                  if (languages == null || languages.isEmpty()) {
                 if (languages == null) {  
211                          put(DEFAULT_KEY, defaultTranslation);                          put(DEFAULT_KEY, defaultTranslation);
212                  } else                  } else
213                          for (String code : languages) {                          for (String code : languages) {
214                                  if (code.equals(getActiveLang())) {                                  put(code, defaultTranslation);
                                         put(code, defaultTranslation);  
                                 }  
215                          }                          }
216          }          }
217    
# Line 196  public class Translation extends HashMap Line 230  public class Translation extends HashMap
230           * <li>If format can't be recognized, the {@link String} is interpreted as           * <li>If format can't be recognized, the {@link String} is interpreted as
231           * the translation in the <code>{@value #DEFAULT_KEY}</code> language           * the translation in the <code>{@value #DEFAULT_KEY}</code> language
232           *           *
233           * @author Stefan Alfons Krüger           * @author Stefan Alfons Tzeggai
234           */           */
235          public void fromOneLine(final String oneLineCoded) {          public void fromOneLine(final String oneLineCoded) {
236    
# Line 237  public class Translation extends HashMap Line 271  public class Translation extends HashMap
271          /**          /**
272           * Exports the Translations to a String of the Format: "de{Baum}en{tree}"           * Exports the Translations to a String of the Format: "de{Baum}en{tree}"
273           *           *
274           * @author Stefan Alfons Krüger           * @author Stefan Alfons Tzeggai
275           */           */
276          public String toOneLine() {          public String toOneLine() {
277                  return I8NUtil.toOneLine(this);                  return I8NUtil.toOneLine(this);
278          }          }
279    
280          /**          /**
281           * Returns the right translation by using the {@link #activeLang} field. If           * Returns the correct translation by using the {@link #activeLang} field.
282           * 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
283           * returned. This might be changed for the final release. If the correct           * returned. This might be changed for the final release. If the correct
284           * language was not found, any entry in the {@link Translation}           * language was not found, any entry in the {@link Translation}
285           * {@link HashMap} will be returned, that contains more than an empty           * {@link HashMap} will be returned, that contains more than an empty
# Line 253  public class Translation extends HashMap Line 287  public class Translation extends HashMap
287           */           */
288          @Override          @Override
289          public String toString() {          public String toString() {
290                  if (get(activeLang) != null) {                  final String string = get(activeLang);
291                    if (string != null) {
292                          return get(activeLang);                          return get(activeLang);
293                  }                  }
294                  // ****************************************************************************                  // ****************************************************************************
# Line 262  public class Translation extends HashMap Line 297  public class Translation extends HashMap
297                  // ****************************************************************************                  // ****************************************************************************
298                  // else return "";                  // else return "";
299                  // //****************************************************************************                  // //****************************************************************************
300                  // // The following is commented out.. the concept of the default lang                  // // ST: The following is commented out.. the concept of the default
301                    // lang
302                  // seems to be bad....                  // seems to be bad....
303                  // //****************************************************************************                  // //****************************************************************************
304                  // MS:                  // MS:
# Line 284  public class Translation extends HashMap Line 320  public class Translation extends HashMap
320    
321          /**          /**
322           * {@link PropertyChangeListener} can be registered to be informed when the           * {@link PropertyChangeListener} can be registered to be informed when the
323           * {@link Locale} changed.           * {@link Locale} changed.<br>
324             * The listeners are kept in a {@link WeakHashMap}, so you have to keep a
325             * reference to the listener or it will be removed!
326           *           *
327           * @param propertyChangeListener           * @param propertyChangeListener
328             *            A {@link PropertyChangeListener} that will be called when
329             *            {@link #setActiveLang(String)} changes the language.
330           */           */
331          public static void addLocaleChangeListener(          public static void addLocaleChangeListener(
332                          PropertyChangeListener propertyChangeListener) {                          PropertyChangeListener propertyChangeListener) {
333                  listeners.add(propertyChangeListener);                  listenersLocaleChange.add(propertyChangeListener);
334            }
335    
336            /**
337             * {@link PropertyChangeListener} can be registered to be informed when the
338             * {@link Locale} changed.<br>
339             * The listeners are kept in a {@link WeakHashMap}, so you have to keep a
340             * reference to the listener or it will be removed!
341             *
342             * @param propertyChangeListener
343             *            A {@link PropertyChangeListener} that will be called when
344             *            {@link #setActiveLang(String)} changes the language.
345             */
346            public static boolean removeLocaleChangeListener(
347                            PropertyChangeListener propertyChangeListener) {
348                    return listenersLocaleChange.remove(propertyChangeListener);
349            }
350    
351            /**
352             * {@link PropertyChangeListener} can be registered to be informed when the
353             * {@link Locale} changed.<br>
354             * The listeners are kept in a {@link WeakHashMap}, so you have to keep a
355             * reference to the listener or it will be removed!
356             *
357             * @param propertyChangeListener
358             *            A {@link PropertyChangeListener} that will be called when
359             *            {@link #setActiveLang(String)} changes the language.
360             */
361            public static void addActiveLangChangeListener(
362                            PropertyChangeListener propertyChangeListener) {
363                    listenersActiveLangChange.add(propertyChangeListener);
364            }
365    
366            /**
367             * {@link PropertyChangeListener} can be registered to be informed when the
368             * {@link Locale} changed.<br>
369             * The listeners are kept in a {@link WeakHashMap}, so you have to keep a
370             * reference to the listener or it will be removed!
371             *
372             * @param propertyChangeListener
373             *            A {@link PropertyChangeListener} that will be called when
374             *            {@link #setActiveLang(String)} changes the language.
375             */
376            public static boolean removeActiveLangListener(
377                            PropertyChangeListener propertyChangeListener) {
378                    return listenersActiveLangChange.remove(propertyChangeListener);
379          }          }
380    
381          /**          /**
# Line 301  public class Translation extends HashMap Line 386  public class Translation extends HashMap
386                  PropertyChangeEvent pce = new PropertyChangeEvent(new Translation(                  PropertyChangeEvent pce = new PropertyChangeEvent(new Translation(
387                                  new ArrayList<String>(), "fakeSource"), LOCALECHANGE_PROPERTY,                                  new ArrayList<String>(), "fakeSource"), LOCALECHANGE_PROPERTY,
388                                  null, getActiveLang());                                  null, getActiveLang());
389                  for (PropertyChangeListener pcl : listeners) {                  for (PropertyChangeListener pcl : listenersLocaleChange) {
390                            if (pcl != null)
391                                    pcl.propertyChange(pce);
392                    }
393            }
394    
395            /**
396             * Informs all registered {@link PropertyChangeListener}s about a change of
397             * the the {@link Locale}.
398             */
399            public static void fireActiveLangChangeEvents() {
400                    PropertyChangeEvent pce = new PropertyChangeEvent(new Translation(
401                                    new ArrayList<String>(), "fakeSource"),
402                                    ACTIVELANG_CHANGE_PROPERTY, null, getActiveLang());
403                    for (PropertyChangeListener pcl : listenersActiveLangChange) {
404                          if (pcl != null)                          if (pcl != null)
405                                  pcl.propertyChange(pce);                                  pcl.propertyChange(pce);
406                  }                  }
# Line 312  public class Translation extends HashMap Line 411  public class Translation extends HashMap
411           * reference as long as you need the listener.           * reference as long as you need the listener.
412           */           */
413          public void addTranslationChangeListener(ActionListener actionListener) {          public void addTranslationChangeListener(ActionListener actionListener) {
414                  if (actionListeners.add(actionListener)) {                  if (changeListeners.add(actionListener)) {
415                          LOGGER.debug("registering a new translationChangeActionListener in the WeakHashSet");                          // LOGGER
416                            // .debug("registering a new translationChangeActionListener in the WeakHashSet");
417                  }                  }
418          }          }
419    
# Line 323  public class Translation extends HashMap Line 423  public class Translation extends HashMap
423           * listener.           * listener.
424           */           */
425          public boolean removeTranslationChangeListener(ActionListener actionListener) {          public boolean removeTranslationChangeListener(ActionListener actionListener) {
426                  return actionListeners.remove(actionListener);                  return changeListeners.remove(actionListener);
427          }          }
428    
429          public void fireTranslationChangedEvents(String lang) {          public void fireTranslationChangedEvents(String lang) {
430                  ActionEvent ae = new ActionEvent(this, new Random().nextInt(), lang);                  ActionEvent ae = new ActionEvent(this, new Random().nextInt(), lang);
431    
432                  final Iterator<ActionListener> iterator = actionListeners.iterator();                  final Iterator<ActionListener> iterator = changeListeners.iterator();
433                  while (iterator.hasNext()) {                  while (iterator.hasNext()) {
434                          ActionListener al = iterator.next();                          ActionListener al = iterator.next();
435                          al.actionPerformed(ae);                          al.actionPerformed(ae);
# Line 352  public class Translation extends HashMap Line 452  public class Translation extends HashMap
452    
453          /**          /**
454           * Copy this {@link Translation} to another {@link Translation} e.g. for           * Copy this {@link Translation} to another {@link Translation} e.g. for
455           * editing           * editing and return the target.
456           *           *
457           * @return the destination {@link Translation}           * @return the destination {@link Translation}
458           */           */
459          @Override          @Override
460          public Translation copyTo(Translation translation2) {          public Translation copyTo(Translation translation2) {
   
461                  if (translation2 == null)                  if (translation2 == null)
                         // throw new IllegalArgumentException(  
                         // "Target translation may not be null.");  
462                          return copy();                          return copy();
                 for (String s : keySet()) {  
                         translation2.put(s, get(s));  
                 }  
463    
464                    translation2.fromOneLine(toOneLine());
465                  return translation2;                  return translation2;
466          }          }
467    
# Line 393  public class Translation extends HashMap Line 488  public class Translation extends HashMap
488                  return true;                  return true;
489          }          }
490    
491            /**
492             * Goes through the available languages of the FIRST registered
493             * {@link ResourceProvider} and set the active locale to the fist match.
494             *
495             * @param fireChangeEvent
496             *            if <code>true</code>, a Translation.fireLocaleChangeEvents()
497             *            is issued.
498             *
499             * @return
500             */
501            public static boolean setFirstmatchingLanguage(List<String> languages,
502                            boolean fireChangeEvent) {
503    
504                    SortableVector<ResourceProvider> registeredResourceProvider = ResourceProvider
505                                    .getRegisteredResourceProvider();
506                    Set<Locale> available = ResourceProvider.getAvailableLocales(
507                                    registeredResourceProvider.get(0), true);
508    
509                    for (String l : languages) {
510                            for (Locale loc : available) {
511                                    if (loc.getLanguage().equals(l)) {
512                                            Translation.setActiveLang(l);
513                                            if (fireChangeEvent)
514                                                    Translation.fireLocaleChangeEvents();
515                                            return true;
516                                    }
517                            }
518                    }
519    
520                    return false;
521    
522            }
523    
524            /**
525             * Returns the translation in a requested language
526             */
527            public String toString(String lang) {
528                    return get(lang);
529            }
530  }  }

Legend:
Removed from v.486  
changed lines
  Added in v.1097

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26