/[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 888 by alfonx, Thu Jun 3 10:48:43 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.WeakHashMap;
44           * @comment To make a copy of a translation see methods toOneLine() and  
45           * fromOneLine()  import javax.swing.JComponent;
46           */  
47          public Translation clone() {  import org.apache.log4j.Logger;
48                  return (Translation) super.clone();  import org.geotools.util.WeakHashSet;
49          }  import org.opengis.util.InternationalString;
50    
51          /**  import skrueger.geotools.Copyable;
52           * Get the two-letter language sting that is active  
53           */  /**
54          public static String getActiveLang() {   * Represents a {@link HashMap} of translations. toString() returns the
55                  return activeLang;   * appropriate translation
56          }   *
57     * @author @author <a href="mailto:[email protected]">Stefan Alfons
58          /**   *         Tzeggai</a>
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  
61           * language equals the old language. The system's default locale is changed.  public class Translation extends HashMap<String, String> implements
62           *                  Copyable<Translation>, Serializable {
63           * @param newLang          
64           *            The ISO Code of the new active language          private static final long serialVersionUID = -347702744122305245L;
65           */          
66          public static void setActiveLang(String newLang) {          public static final String LOCALECHANGE_PROPERTY = "localechange";
67                  setActiveLang(newLang, true);          public static final String NO_TRANSLATION = "NO TRANSLATION";
68          }          public static final String DEFAULT_KEY = "default";
69            static final Logger LOGGER = Logger.getLogger(Translation.class);
70          /**          static String activeLang = Locale.getDefault().getLanguage();
71           * Set up the {@link Translation}-system to use language. If a change is  
72           * performed, events are fired to listeners. Nothing is done if the new          static protected WeakHashSet<PropertyChangeListener> listeners = new WeakHashSet<PropertyChangeListener>(
73           * language equals the old language.                          PropertyChangeListener.class);
74           *  
75           * @param newLang          static {
76           *            The ISO Code of the new active language  
77           *                  // TODO default aus Locale auslesen und mit möglichen vergleichen...
78           * @param setDefaultLocale                  // mmm.. vor laden von atlasml immer DEFAULT_KEY, also hier nicht
79           *            Shall the system's default locale be changed?  
80           */                  // Get default locale
81          public static void setActiveLang(String newLang, boolean setDefaultLocale) {                  Locale locale = Locale.getDefault();
82                  if (getActiveLang().equals(newLang)) {                  setActiveLang(locale.getLanguage());
83                          return;          }
84                  }          
85            
86                  if (!I8NUtil.isValidISOLangCode(newLang)) {  
87                          throw new IllegalArgumentException("'" + newLang          private WeakHashSet<ActionListener> actionListeners = new WeakHashSet<ActionListener>(
88                                          + "' is not a valid ISO language code.");                          ActionListener.class);
89                  }  
90            @Override
91                  Locale newLocale = new Locale(newLang);          /*
92                  if (setDefaultLocale)           * @comment To make a copy of a translation see methods toOneLine() and
93                          Locale.setDefault(newLocale);           * fromOneLine()
94             */
95                  /**          public Translation clone() {
96                   * Setting default locale for Swing JComponents to work around bug                  throw new RuntimeException("use copy()");
97                   * http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4884480                  // return (Translation) super.clone();
98                   */          }
99                  JComponent.setDefaultLocale(newLocale);  
100            /**
101                  Translation.activeLang = newLang;           * Get the two-letter language sting that is active
102             */
103                  fireChangeEvents();          public static String getActiveLang() {
104                    return activeLang;
105                  log.info("skrueger.i8n.Translation switched ActiveLang to " + newLang);          }
106          }  
107            /**
108          /**           * Set up the {@link Translation}-system to use language. If a change is
109           * Initializes a new {@link Translation} with a default translation if a           * performed, events are fired to listeners. Nothing is done if the new
110           * simple text is passed. If a "oneLine" text is parsed, it is interpreted.           * language equals the old language. The system's default locale is changed.
111           * Other translations may be added later - this is a HashMap<br/>           *
112           *           * @param newLang
113           * @param defaultTranslation           *            The ISO Code of the new active language
114           *           */
115           * @see public Translation(List<String> languages, String          public static void setActiveLang(String newLang) {
116           *      defaultTranslation) {                  setActiveLang(newLang, true);
117           *          }
118           */  
119          public Translation(String defaultTranslation) {          /**
120             * Set up the {@link Translation}-system to use language. If a change is
121                  fromOneLine(defaultTranslation);           * performed, events are fired to listeners. Nothing is done if the new
122             * language equals the old language.
123          }           *
124             * @param newLang
125          /**           *            The ISO Code of the new active language
126           * Initializes a new {@link Translation}, an uses the given String to           *
127           * initialize the {@link Translation} for all languages codes passed.           * @param setDefaultLocale
128           *           *            Shall the system's default locale be changed?
129           * The translations can be changed later           */
130           */          public static void setActiveLang(String newLang, boolean setDefaultLocale) {
131          public Translation(List<String> languages, String defaultTranslation) {                  if (getActiveLang().equals(newLang)) {
132                  // put(DEFAULT_KEY, defaultTranslation);                          return;
133                  if (languages == null) {                  }
134                          put(DEFAULT_KEY, defaultTranslation);  
135                  } else                  if (!I8NUtil.isValidISOLangCode(newLang)) {
136                          for (String code : languages) {                          throw new IllegalArgumentException("'" + newLang
137                                  if (code.equals(getActiveLang())) {                                          + "' is not a valid ISO language code.");
138                                          put(code, defaultTranslation);                  }
139                                  }  
140                          }                  Locale newLocale = new Locale(newLang);
141          }                  if (setDefaultLocale)
142                            Locale.setDefault(newLocale);
143          /**  
144           * Sometimes Translations are optional, like for keywords.                  /**
145           */                   * Setting default locale for Swing JComponents to work around bug
146          public Translation() {                   * http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4884480
147          }                   */
148                    JComponent.setDefaultLocale(newLocale);
149          /**  
150           * Fills the {@link Translation} with the values coded into the String                  Translation.activeLang = newLang;
151           * Format of {@link String} is: "de{Baum}en{tree}"  
152           * <p>                  fireLocaleChangeEvents();
153           * <ul>  
154           * <li>If <code>oneLineCoded</code> is empty or null, NO TRANSLATION is set.                  LOGGER.info("skrueger.i8n.Translation switched ActiveLang to "
155           * <li>If format can't be recognized, the {@link String} is interpreted as                                  + newLang);
156           * the translation in the <code>{@value #DEFAULT_KEY}</code> language          }
157           *  
158           * @author Stefan Alfons Krüger          /**
159           */           * Initializes a new {@link Translation} with a default translation if a
160          public void fromOneLine(final String oneLineCoded) {           * simple text is passed. If a "oneLine" text is parsed, it is interpreted.
161                  clear();           * Other translations may be added later - this is a HashMap<br/>
162                  if ((oneLineCoded == null) || (oneLineCoded.equals(""))) {           *
163                          put(DEFAULT_KEY, "");           * @param defaultTranslation
164                          return;           *
165                  }           * @see public Translation(List<String> languages, String
166             *      defaultTranslation) {
167                  if (oneLineCoded.indexOf("}") == -1) {           *
168                          // log.warn("The String '"+oneLineCoded+"' is not in oneLine coded => put(DEFAULT_KEY,oneLineCoded);");           */
169                          put(DEFAULT_KEY, oneLineCoded);          public Translation(String defaultTranslation) {
170                  }  
171                    fromOneLine(defaultTranslation);
172                  String eatUp = oneLineCoded;  
173                  while (eatUp.indexOf("}") != -1) {          }
174                          String substring = eatUp.substring(0, eatUp.indexOf("}"));  
175            /**
176                          // log.debug("substring = "+substring);           * Initializes a new {@link Translation}, an uses the given String to
177                          String key = substring.substring(0, substring.indexOf("{"));           * initialize the {@link Translation} for all languages codes passed.
178                          String value = substring.substring(substring.indexOf("{") + 1,           *
179                                          substring.length());           * The translations can be changed later
180                          // log.debug("key="+key);           */
181                          // log.debug("value="+value);          public Translation(List<String> languages, String defaultTranslation) {
182                          put(key, value);                  // put(DEFAULT_KEY, defaultTranslation);
183                          eatUp = eatUp.substring(eatUp.indexOf("}") + 1);                  if (languages == null) {
184                  }                          put(DEFAULT_KEY, defaultTranslation);
185          }                  } else
186                            for (String code : languages) {
187          /**  //                              if (code.equals(getActiveLang())) {
188           * Exports the Translations to a String of the Format: "de{Baum}en{tree}"                                          put(code, defaultTranslation);
189           *  //                              }
190           * @author Stefan Alfons Krüger                          }
191           */          }
192          public String toOneLine() {  
193                  return I8NUtil.toOneLine(this);          /**
194          }           * Sometimes Translations are optional, like for keywords.
195             */
196          /**          public Translation() {
197           * Returns the right translation by using the {@link #activeLang} field. If          }
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}           * Fills the {@link Translation} with the values coded into the String
201           * {@link HashMap} will be returned, that contains more than an empty           * Format of {@link String} is: "de{Baum}en{tree}"
202           * string.           * <p>
203           */           * <ul>
204          @Override           * <li>If <code>oneLineCoded</code> is empty or null, NO TRANSLATION is set.
205          public String toString() {           * <li>If format can't be recognized, the {@link String} is interpreted as
206                  if (get(activeLang) != null) {           * the translation in the <code>{@value #DEFAULT_KEY}</code> language
207                          return get(activeLang);           *
208                  }           * @author Stefan Alfons Tzeggai
209                  // ****************************************************************************           */
210                  // MS: The ISDSS needs the concept of the default lang!! So I took the          public void fromOneLine(final String oneLineCoded) {
211                  // following in again!!  
212                  // ****************************************************************************                  clear();
213                  // else return "";  
214                  // //****************************************************************************                  try {
215                  // // The following is commented out.. the concept of the default lang  
216                  // seems to be bad....                          if ((oneLineCoded == null) || (oneLineCoded.equals(""))) {
217                  // //****************************************************************************                                  put(DEFAULT_KEY, "");
218                  // MS:                                  return;
219                  else {                          }
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.");                          if (oneLineCoded.indexOf("}") == -1) {
222                                  return get(DEFAULT_KEY);                                  // log.warn("The String '"+oneLineCoded+"' is not in oneLine coded => put(DEFAULT_KEY,oneLineCoded);");
223                          }                                  put(DEFAULT_KEY, oneLineCoded);
224                            }
225                          // log.debug("return first best <> '' ");  
226                          if (size() > 0)                          String eatUp = oneLineCoded;
227                                  for (String s : values()) {                          while (eatUp.indexOf("}") != -1) {
228                                          if ((s != null) && (s.trim().length() > 0))                                  String substring = eatUp.substring(0, eatUp.indexOf("}"));
229                                                  return s;  
230                                  }                                  // log.debug("substring = "+substring);
231                  }                                  String key = substring.substring(0, substring.indexOf("{"));
232                  log.warn("No translation found!");                                  String value = substring.substring(substring.indexOf("{") + 1,
233                  return NO_TRANSLATION;                                                  substring.length());
234          }                                  // log.debug("key="+key);
235                                    // log.debug("value="+value);
236          /**                                  put(key, value);
237           * Copy this {@link Translation} to another {@link Translation} e.g. for                                  eatUp = eatUp.substring(eatUp.indexOf("}") + 1);
238           * editing                          }
239           *                  } catch (Exception e) {
240           * @return the destination {@link Translation}                          LOGGER.warn("Error while reading the oneLineCode '" + oneLineCoded
241           */                                          + "'", e);
242          public Translation copy(Translation backup) {                          LOGGER.warn("Translation will be empty!");
243                  if (backup == null)                  }
244                          throw new IllegalArgumentException(          }
245                                          "Target translation may not be null.");  
246                  for (String s : keySet()) {          /**
247                          backup.put(s, get(s));           * Exports the Translations to a String of the Format: "de{Baum}en{tree}"
248                  }           *
249                  return backup;           * @author Stefan Alfons Tzeggai
250          }           */
251            public String toOneLine() {
252          /**                  return I8NUtil.toOneLine(this);
253           * {@link PropertyChangeListener} can be registered to be informed when the          }
254           * {@link Locale} changed.  
255           *          /**
256           * @param propertyChangeListener           * Returns the right translation by using the {@link #activeLang} field. If
257           */           * no translation is set, an ugly String {@link #NO_TRANSLATION} will re
258          public static void addLocaleChangeListener(           * returned. This might be changed for the final release. If the correct
259                          PropertyChangeListener propertyChangeListener) {           * language was not found, any entry in the {@link Translation}
260                  listeners.add(propertyChangeListener);           * {@link HashMap} will be returned, that contains more than an empty
261          }           * string.
262             */
263          /**          @Override
264           * Informs all registered {@link PropertyChangeListener}s about a change of          public String toString() {
265           * the the {@link Locale}.                  if (get(activeLang) != null) {
266           */                          return get(activeLang);
267          public static void fireChangeEvents() {                  }
268                  PropertyChangeEvent pce = new PropertyChangeEvent(new Translation(                  // ****************************************************************************
269                                  new ArrayList<String>(), "fakeSource"), LOCALECHANGE_PROPERTY,                  // MS: The ISDSS needs the concept of the default lang!! So I took the
270                                  null, getActiveLang());                  // following in again!!
271                  for (PropertyChangeListener pcl : listeners) {                  // ****************************************************************************
272                          if (pcl != null)                  // else return "";
273                                  pcl.propertyChange(pce);                  // //****************************************************************************
274                  }                  // // The following is commented out.. the concept of the default lang
275          }                  // seems to be bad....
276                    // //****************************************************************************
277  }                  // MS:
278                    else {
279                            if (get(DEFAULT_KEY) != null) {
280                                    return get(DEFAULT_KEY);
281                            }
282    
283                            // log.debug("return first best <> '' ");
284                            if (size() > 0)
285                                    for (String s : values()) {
286                                            if ((s != null) && (s.trim().length() > 0))
287                                                    return s;
288                                    }
289                    }
290                    // log.warn("No translation found!");
291                    return NO_TRANSLATION;
292            }
293    
294            /**
295             * {@link PropertyChangeListener} can be registered to be informed when the
296             * {@link Locale} changed.<br>
297             * The listeners are kept in a {@link WeakHashMap}, so you have to keep a
298             * reference to the listener or it will be removed!
299             *
300             * @param propertyChangeListener
301             *            A {@link PropertyChangeListener} that will be called when
302             *            {@link #setActiveLang(String)} changes the language.
303             */
304            public static void addLocaleChangeListener(
305                            PropertyChangeListener propertyChangeListener) {
306                    listeners.add(propertyChangeListener);
307            }
308    
309            /**
310             * {@link PropertyChangeListener} can be registered to be informed when the
311             * {@link Locale} changed.<br>
312             * The listeners are kept in a {@link WeakHashMap}, so you have to keep a
313             * reference to the listener or it will be removed!
314             *
315             * @param propertyChangeListener
316             *            A {@link PropertyChangeListener} that will be called when
317             *            {@link #setActiveLang(String)} changes the language.
318             */
319            public static boolean removeLocaleChangeListener(
320                            PropertyChangeListener propertyChangeListener) {
321                    return listeners.remove(propertyChangeListener);
322            }
323    
324            /**
325             * Informs all registered {@link PropertyChangeListener}s about a change of
326             * the the {@link Locale}.
327             */
328            public static void fireLocaleChangeEvents() {
329                    PropertyChangeEvent pce = new PropertyChangeEvent(new Translation(
330                                    new ArrayList<String>(), "fakeSource"), LOCALECHANGE_PROPERTY,
331                                    null, getActiveLang());
332                    for (PropertyChangeListener pcl : listeners) {
333                            if (pcl != null)
334                                    pcl.propertyChange(pce);
335                    }
336            }
337    
338            /**
339             * The listeneras are stored in a {@link WeakHashSet}! So you HAVE TO KEEP a
340             * reference as long as you need the listener.
341             */
342            public void addTranslationChangeListener(ActionListener actionListener) {
343                    if (actionListeners.add(actionListener)) {
344    //                      LOGGER
345    //                                      .debug("registering a new translationChangeActionListener in the WeakHashSet");
346                    }
347            }
348    
349            /**
350             * The listeneras are stored in a {@link WeakHashSet}! You don't have to
351             * remove the listener, as long as you throw away the reference to the
352             * listener.
353             */
354            public boolean removeTranslationChangeListener(ActionListener actionListener) {
355                    return actionListeners.remove(actionListener);
356            }
357    
358            public void fireTranslationChangedEvents(String lang) {
359                    ActionEvent ae = new ActionEvent(this, new Random().nextInt(), lang);
360    
361                    final Iterator<ActionListener> iterator = actionListeners.iterator();
362                    while (iterator.hasNext()) {
363                            ActionListener al = iterator.next();
364                            al.actionPerformed(ae);
365                    }
366            }
367    
368            @Override
369            public String put(String lang, String value) {
370                    String result = super.put(lang, value);
371                    fireTranslationChangedEvents(lang);
372                    return result;
373            }
374    
375            public void fromOneLine(InternationalString iString) {
376                    if (iString != null)
377                            fromOneLine(iString.toString());
378                    else
379                            fromOneLine((String) null);
380            }
381    
382            /**
383             * Copy this {@link Translation} to another {@link Translation} e.g. for
384             * editing
385             *
386             * @return the destination {@link Translation}
387             */
388            @Override
389            public Translation copyTo(Translation translation2) {
390    
391                    if (translation2 == null)
392                            // throw new IllegalArgumentException(
393                            // "Target translation may not be null.");
394                            return copy();
395                    for (String s : keySet()) {
396                            translation2.put(s, get(s));
397                    }
398    
399                    return translation2;
400            }
401    
402            @Override
403            public Translation copy() {
404                    return copyTo(new Translation());
405            }
406    
407            /**
408             * Checks if the {@link String}s stored in the {@link Translation} are all
409             * valid.
410             *
411             * @return <code>true</code> if all good
412             */
413            public static boolean checkValid(Translation translationToCheck) {
414    
415                    for (String l : translationToCheck.values()) {
416    
417                            if (l.contains("{") || l.contains("}")) {
418    
419                                    return false;
420                            }
421                    }
422                    return true;
423            }
424    
425    }

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

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26