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

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

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

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26