/[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 39 by alfonx, Mon Apr 6 19:14:55 2009 UTC branches/1.0-gt2-2.6/src/skrueger/i8n/Translation.java revision 482 by alfonx, Tue Oct 20 13:51:11 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     * This program is free software; you can redistribute it and/or
12  import org.apache.log4j.Logger;   * modify it under the terms of the GNU Lesser General Public License
13     * as published by the Free Software Foundation; either version 3
14  /**   * of the License, or (at your option) any later version.
15   * Represents a {@link HashMap} of translations. toString() returns the   *
16   * appropriate translation   * This program is distributed in the hope that it will be useful,
17   *   * but WITHOUT ANY WARRANTY; without even the implied warranty of
18   * @author @author <a href="mailto:[email protected]">Stefan Alfons   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19   *         Kr&uuml;ger</a>   * GNU General Public License for more details.
20   */   *
21     * You should have received a copy of the GNU Lesser General Public License (license.txt)
22  public class Translation extends HashMap<String, String> {   * along with this program; if not, write to the Free Software
23          public static final String LOCALECHANGE_PROPERTY = "localechange";   * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
24          public static final String NO_TRANSLATION = "NO TRANSLATION";   * or try this link: http://www.gnu.org/licenses/lgpl.html
25          public static final String DEFAULT_KEY = "default";   *
26          static final Logger log = Logger.getLogger(Translation.class);   * Contributors:
27          static String activeLang = "fr";   *     Martin O. J. Schmitz - initial API and implementation
28     *     Stefan A. Krüger - additional utility classes
29          static protected List<PropertyChangeListener> listeners = new ArrayList<PropertyChangeListener>();   ******************************************************************************/
30    package skrueger.i8n;
31          static {  
32    import java.awt.event.ActionEvent;
33                  // TODO default aus Locale auslesen und mit möglichen vergleichen...  import java.awt.event.ActionListener;
34                  // mmm.. vor laden von atlasml immer DEFAULT_KEY, also hier nicht  import java.beans.PropertyChangeEvent;
35    import java.beans.PropertyChangeListener;
36                  // Get default locale  import java.util.ArrayList;
37                  Locale locale = Locale.getDefault();  import java.util.HashMap;
38                  setActiveLang(locale.getLanguage());  import java.util.Iterator;
39          }  import java.util.List;
40    import java.util.Locale;
41          @Override  import java.util.Random;
42          /*  
43           * @comment To make a copy of a translation see methods toOneLine() and  import javax.swing.JComponent;
44           * fromOneLine()  
45           */  import org.apache.log4j.Logger;
46          public Translation clone() {  import org.geotools.util.WeakHashSet;
47                  return (Translation) super.clone();  import org.opengis.util.InternationalString;
48          }  
49    import skrueger.geotools.Copyable;
50          /**  
51           * Get the two-letter language sting that is active  /**
52           */   * Represents a {@link HashMap} of translations. toString() returns the
53          public static String getActiveLang() {   * appropriate translation
54                  return activeLang;   *
55          }   * @author @author <a href="mailto:[email protected]">Stefan Alfons
56     *         Kr&uuml;ger</a>
57          /**   */
58           * Set up the {@link Translation}-system to use language. If a change is  
59           * performed, events are fired to listeners. Nothing is done if the new  public class Translation extends HashMap<String, String> implements
60           * language equals the old language.                  Copyable<Translation> {
61           *          public static final String LOCALECHANGE_PROPERTY = "localechange";
62           * @param newLang          public static final String NO_TRANSLATION = "NO TRANSLATION";
63           *            The ISO Code of the new active language          public static final String DEFAULT_KEY = "default";
64           */          static final Logger log = Logger.getLogger(Translation.class);
65          public static void setActiveLang(String newLang) {          static String activeLang = Locale.getDefault().getLanguage();
66                  if (getActiveLang().equals(newLang)) {  
67                          return;          static protected List<PropertyChangeListener> listeners = new ArrayList<PropertyChangeListener>();
68                  }  
69            static {
70                  if (!I8NUtil.isValidISOLangCode(newLang)) {  
71                          throw new IllegalArgumentException("'" + newLang                  // TODO default aus Locale auslesen und mit möglichen vergleichen...
72                                          + "' is not a valid ISO language code.");                  // mmm.. vor laden von atlasml immer DEFAULT_KEY, also hier nicht
73                  }  
74                    // Get default locale
75                  Locale newLocale = new Locale(newLang);                  Locale locale = Locale.getDefault();
76                  Locale.setDefault(newLocale);                  setActiveLang(locale.getLanguage());
77            }
78                  /**  
79                   * Setting default locale for Swing JComponents to work around bug          private WeakHashSet<ActionListener> actionListeners = new WeakHashSet<ActionListener>(
80                   * http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4884480                          ActionListener.class);
81                   */  
82                  JComponent.setDefaultLocale(newLocale);          @Override
83            /*
84                  Translation.activeLang = newLang;           * @comment To make a copy of a translation see methods toOneLine() and
85             * fromOneLine()
86                  fireChangeEvents();           */
87            public Translation clone() {
88                  log.info("skrueger.i8n.Translation switched ActiveLang to " + newLang);                  throw new RuntimeException("use copy()");
89          }                  // return (Translation) super.clone();
90            }
91          /**  
92           * Initializes a new {@link Translation} with a default translation. Other          /**
93           * translations may be added later.           * Get the two-letter language sting that is active
94           *           */
95           * @param defaultTranslation          public static String getActiveLang() {
96           *                  return activeLang;
97           * @deprecated SK: The concept of the default translation doesn't seem so          }
98           *             nice to me anymore.. I would prefer the default translation  
99           *             to be set for all valid languages.          /**
100           *           * Set up the {@link Translation}-system to use language. If a change is
101           * @see public Translation(List<String> languages, String           * performed, events are fired to listeners. Nothing is done if the new
102           *      defaultTranslation) {           * language equals the old language. The system's default locale is changed.
103           *           *
104           */           * @param newLang
105          public Translation(String defaultTranslation) {           *            The ISO Code of the new active language
106                  put(DEFAULT_KEY, defaultTranslation);           */
107          }          public static void setActiveLang(String newLang) {
108                    setActiveLang(newLang, true);
109          /**          }
110           * Initializes a new {@link Translation}, an uses the given String to  
111           * initialize the {@link Translation} for all languages codes passed.          /**
112           *           * Set up the {@link Translation}-system to use language. If a change is
113           * The translations can be changed later           * performed, events are fired to listeners. Nothing is done if the new
114           */           * language equals the old language.
115          public Translation(List<String> languages, String defaultTranslation) {           *
116                  // put(DEFAULT_KEY, defaultTranslation);           * @param newLang
117                  if (languages == null) {           *            The ISO Code of the new active language
118                          put(DEFAULT_KEY, defaultTranslation);           *
119                  } else           * @param setDefaultLocale
120                          for (String code : languages) {           *            Shall the system's default locale be changed?
121                                  if (code.equals(getActiveLang())) {           */
122                                          put(code, defaultTranslation);          public static void setActiveLang(String newLang, boolean setDefaultLocale) {
123                                  }                  if (getActiveLang().equals(newLang)) {
124                          }                          return;
125          }                  }
126    
127          /**                  if (!I8NUtil.isValidISOLangCode(newLang)) {
128           * Sometimes Translations are optional, like for keywords.                          throw new IllegalArgumentException("'" + newLang
129           */                                          + "' is not a valid ISO language code.");
130          public Translation() {                  }
131                  super();  
132          }                  Locale newLocale = new Locale(newLang);
133                    if (setDefaultLocale)
134          /**                          Locale.setDefault(newLocale);
135           * Fills the {@link Translation} with the values coded into the String  
136           * Format of {@link String} is: "de{Baum}en{tree}"                  /**
137           * <p>                   * Setting default locale for Swing JComponents to work around bug
138           * <ul>                   * http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4884480
139           * <li>If <code>oneLineCoded</code> is empty or null, NO TRANSLATION is set.                   */
140           * <li>If format can't be recognized, the {@link String} is interpreted as                  JComponent.setDefaultLocale(newLocale);
141           * the translation in the <code>{@value #DEFAULT_KEY}</code> language  
142           *                  Translation.activeLang = newLang;
143           * @author Stefan Alfons Krüger  
144           */                  fireLocaleChangeEvents();
145          public void fromOneLine(final String oneLineCoded) {  
146                  clear();                  log.info("skrueger.i8n.Translation switched ActiveLang to " + newLang);
147                  if ((oneLineCoded == null) || (oneLineCoded.equals(""))) {          }
148                          put(DEFAULT_KEY, NO_TRANSLATION);  
149                          return;          /**
150                  }           * Initializes a new {@link Translation} with a default translation if a
151             * simple text is passed. If a "oneLine" text is parsed, it is interpreted.
152                  if (oneLineCoded.indexOf("}") == -1) {           * Other translations may be added later - this is a HashMap<br/>
153                          // log.warn("The String '"+oneLineCoded+"' is not in oneLine coded => put(DEFAULT_KEY,oneLineCoded);");           *
154                          put(DEFAULT_KEY, oneLineCoded);           * @param defaultTranslation
155                  }           *
156             * @see public Translation(List<String> languages, String
157                  String eatUp = oneLineCoded;           *      defaultTranslation) {
158                  while (eatUp.indexOf("}") != -1) {           *
159                          String substring = eatUp.substring(0, eatUp.indexOf("}"));           */
160            public Translation(String defaultTranslation) {
161                          // log.debug("substring = "+substring);  
162                          String key = substring.substring(0, substring.indexOf("{"));                  fromOneLine(defaultTranslation);
163                          String value = substring.substring(substring.indexOf("{") + 1,  
164                                          substring.length());          }
165                          // log.debug("key="+key);  
166                          // log.debug("value="+value);          /**
167                          put(key, value);           * Initializes a new {@link Translation}, an uses the given String to
168                          eatUp = eatUp.substring(eatUp.indexOf("}") + 1);           * initialize the {@link Translation} for all languages codes passed.
169                  }           *
170          }           * The translations can be changed later
171             */
172          /**          public Translation(List<String> languages, String defaultTranslation) {
173           * Exports the Translations to a String of the Format: "de{Baum}en{tree}"                  // put(DEFAULT_KEY, defaultTranslation);
174           *                  if (languages == null) {
175           * @author Stefan Alfons Krüger                          put(DEFAULT_KEY, defaultTranslation);
176           */                  } else
177          public String toOneLine() {                          for (String code : languages) {
178                  StringBuffer oneLine = new StringBuffer();                                  if (code.equals(getActiveLang())) {
179                  for (String key : keySet()) {                                          put(code, defaultTranslation);
180                          oneLine.append(key + "{" + get(key) + "}");                                  }
181                  }                          }
182                  return oneLine.toString();          }
183          }  
184            /**
185          /**           * Sometimes Translations are optional, like for keywords.
186           * Returns the right translation by using the {@link #activeLang} field. If           */
187           * no translation is set, an ugly String {@link #NO_TRANSLATION} will re          public Translation() {
188           * returned. This might be changed for the final release. If the correct          }
189           * language was not found, any entry in the {@link Translation}  
190           * {@link HashMap} will be returned, that contains more than an empty          /**
191           * string.           * Fills the {@link Translation} with the values coded into the String
192           */           * Format of {@link String} is: "de{Baum}en{tree}"
193          @Override           * <p>
194          public String toString() {           * <ul>
195                  if (get(activeLang) != null) {           * <li>If <code>oneLineCoded</code> is empty or null, NO TRANSLATION is set.
196                          return get(activeLang);           * <li>If format can't be recognized, the {@link String} is interpreted as
197                  }           * the translation in the <code>{@value #DEFAULT_KEY}</code> language
198                  // ****************************************************************************           *
199                  // MS: The ISDSS needs the concept of the default lang!! So I took the           * @author Stefan Alfons Krüger
200                  // following in again!!           */
201                  // ****************************************************************************          public void fromOneLine(final String oneLineCoded) {
202                  // else return "";  
203                  // //****************************************************************************                  clear();
204                  // // The following is commented out.. the concept of the default lang  
205                  // seems to be bad....                  try {
206                  // //****************************************************************************  
207                  // MS:                          if ((oneLineCoded == null) || (oneLineCoded.equals(""))) {
208                  else {                                  put(DEFAULT_KEY, "");
209                          if (get(DEFAULT_KEY) != null) {                                  return;
210                                  // log.debug("default lng returned, cuz the translation to "+activeLang+" was not found. Schmeiss raus martin, wenn du das mit der default trans geklärt hast.");                          }
211                                  return get(DEFAULT_KEY);  
212                          }                          if (oneLineCoded.indexOf("}") == -1) {
213                                    // log.warn("The String '"+oneLineCoded+"' is not in oneLine coded => put(DEFAULT_KEY,oneLineCoded);");
214                          // log.debug("return first best <> '' ");                                  put(DEFAULT_KEY, oneLineCoded);
215                          if (size() > 0)                          }
216                                  for (String s : values()) {  
217                                          if ((s != null) && (s.trim().length() > 0))                          String eatUp = oneLineCoded;
218                                                  return s;                          while (eatUp.indexOf("}") != -1) {
219                                  }                                  String substring = eatUp.substring(0, eatUp.indexOf("}"));
220                  }  
221                  log.warn("No translation found!");                                  // log.debug("substring = "+substring);
222                  return NO_TRANSLATION;                                  String key = substring.substring(0, substring.indexOf("{"));
223          }                                  String value = substring.substring(substring.indexOf("{") + 1,
224                                                    substring.length());
225          /**                                  // log.debug("key="+key);
226           * Copy this {@link Translation} to another {@link Translation} e.g. for                                  // log.debug("value="+value);
227           * editing                                  put(key, value);
228           *                                  eatUp = eatUp.substring(eatUp.indexOf("}") + 1);
229           * @return the destination {@link Translation}                          }
230           */                  } catch (Exception e) {
231          public Translation copy(Translation backup) {                          log.warn("Error while reading the oneLineCode '" + oneLineCoded
232                  if (backup == null)                                          + "'", e);
233                          throw new IllegalArgumentException(                          log.warn("Translation will be empty!");
234                                          "Target translation may not be null.");                  }
235                  for (String s : keySet()) {          }
236                          backup.put(s, get(s));  
237                  }          /**
238                  return backup;           * Exports the Translations to a String of the Format: "de{Baum}en{tree}"
239          }           *
240             * @author Stefan Alfons Krüger
241          /**           */
242           * {@link PropertyChangeListener} can be registered to be informed when the          public String toOneLine() {
243           * {@link Locale} changed.                  return I8NUtil.toOneLine(this);
244           *          }
245           * @param propertyChangeListener  
246           */          /**
247          public static void addLocaleChangeListener(           * Returns the right translation by using the {@link #activeLang} field. If
248                          PropertyChangeListener propertyChangeListener) {           * no translation is set, an ugly String {@link #NO_TRANSLATION} will re
249                  listeners.add(propertyChangeListener);           * 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           * Informs all registered {@link PropertyChangeListener}s about a change of           */
254           * the the {@link Locale}.          @Override
255           */          public String toString() {
256          public static void fireChangeEvents() {                  if (get(activeLang) != null) {
257                  PropertyChangeEvent pce = new PropertyChangeEvent(new Translation(                          return get(activeLang);
258                                  new ArrayList<String>(), "fakeSource"), LOCALECHANGE_PROPERTY,                  }
259                                  null, getActiveLang());                  // ****************************************************************************
260                  for (PropertyChangeListener pcl : listeners) {                  // MS: The ISDSS needs the concept of the default lang!! So I took the
261                          if (pcl != null)                  // following in again!!
262                                  pcl.propertyChange(pce);                  // ****************************************************************************
263                  }                  // else return "";
264          }                  // //****************************************************************************
265                    // // The following is commented out.. the concept of the default lang
266                    // seems to be bad....
267  }                  // //****************************************************************************
268                    // MS:
269                    else {
270                            if (get(DEFAULT_KEY) != null) {
271                                    return get(DEFAULT_KEY);
272                            }
273    
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                    actionListeners.add(actionListener);
316            }
317    
318            /**
319             * The listeneras are stored in a {@link WeakHashSet}! You don't have to
320             * remove the listener, as long as you throw away the reference to the
321             * listener.
322             */
323            public boolean removeTranslationChangeListener(ActionListener actionListener) {
324                    return actionListeners.remove(actionListener);
325            }
326    
327            public void fireTranslationChangedEvents(String lang) {
328                    ActionEvent ae = new ActionEvent(this, new Random().nextInt(), lang);
329    
330                    final Iterator<ActionListener> iterator = actionListeners.iterator();
331                    while (iterator.hasNext()) {
332                            ActionListener al = iterator.next();
333                            al.actionPerformed(ae);
334                    }
335            }
336    
337            @Override
338            public String put(String lang, String value) {
339                    String result = super.put(lang, value);
340                    fireTranslationChangedEvents(lang);
341                    return result;
342            }
343    
344            public void fromOneLine(InternationalString iString) {
345                    if (iString != null)
346                            fromOneLine(iString.toString());
347                    else
348                            fromOneLine((String) null);
349            }
350    
351            /**
352             * Copy this {@link Translation} to another {@link Translation} e.g. for
353             * editing
354             *
355             * @return the destination {@link Translation}
356             */
357            @Override
358            public Translation copyTo(Translation translation2) {
359    
360                    if (translation2 == null)
361                            // throw new IllegalArgumentException(
362                            // "Target translation may not be null.");
363                            return copy();
364                    for (String s : keySet()) {
365                            translation2.put(s, get(s));
366                    }
367    
368                    return translation2;
369            }
370    
371            @Override
372            public Translation copy() {
373                    return copyTo(new Translation());
374            }
375    
376            /**
377             * Checks if the {@link String}s stored in the {@link Translation} are all
378             * valid.
379             *
380             * @return <code>true</code> if all good
381             */
382            public static boolean checkValid(Translation translationToCheck) {
383    
384                    for (String l : translationToCheck.values()) {
385    
386                            if (l.contains("{") || l.contains("}")) {
387    
388                                    return false;
389                            }
390                    }
391                    return true;
392            }
393    
394    }

Legend:
Removed from v.39  
changed lines
  Added in v.482

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26