KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > opencms > i18n > CmsMessages


1 /*
2  * File : $Source: /usr/local/cvs/opencms/src/org/opencms/i18n/CmsMessages.java,v $
3  * Date : $Date: 2006/03/27 14:53:01 $
4  * Version: $Revision: 1.23 $
5  *
6  * This library is part of OpenCms -
7  * the Open Source Content Mananagement System
8  *
9  * Copyright (c) 2005 Alkacon Software GmbH (http://www.alkacon.com)
10  *
11  * This library is free software; you can redistribute it and/or
12  * modify it under the terms of the GNU Lesser General Public
13  * License as published by the Free Software Foundation; either
14  * version 2.1 of the License, or (at your option) any later version.
15  *
16  * This library is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19  * Lesser General Public License for more details.
20  *
21  * For further information about Alkacon Software GmbH, please see the
22  * company website: http://www.alkacon.com
23  *
24  * For further information about OpenCms, please see the
25  * project website: http://www.opencms.org
26  *
27  * You should have received a copy of the GNU Lesser General Public
28  * License along with this library; if not, write to the Free Software
29  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
30  */

31
32 package org.opencms.i18n;
33
34 import org.opencms.util.CmsDateUtil;
35 import org.opencms.util.CmsStringUtil;
36
37 import java.text.DateFormat JavaDoc;
38 import java.text.MessageFormat JavaDoc;
39 import java.util.Date JavaDoc;
40 import java.util.Locale JavaDoc;
41 import java.util.MissingResourceException JavaDoc;
42 import java.util.ResourceBundle JavaDoc;
43
44 /**
45  * Reads localized resource Strings from a <code>java.util.ResourceBundle</code>
46  * and provides convenience methods to access the Strings from a template.<p>
47  *
48  * This class is frequently used from JSP templates. Because of that, throwing of
49  * exceptions related to the access of the resource bundle are suppressed
50  * so that a template always execute. The class provides an {@link #isInitialized()} method
51  * that can be checked to see if the instance was properly initialized.<p>
52  *
53  * @author Alexander Kandzior
54  *
55  * @version $Revision: 1.23 $
56  *
57  * @since 6.0.0
58  */

59 public class CmsMessages {
60
61     /** The suffix of a "short" localized key name. */
62     public static final String JavaDoc KEY_SHORT_SUFFIX = ".short";
63
64     /** Prefix / Suffix for unknown keys. */
65     public static final String JavaDoc UNKNOWN_KEY_EXTENSION = "???";
66
67     /** The resource bundle base name this object was initialized with. */
68     private String JavaDoc m_bundleName;
69
70     /** The locale to use for looking up the messages from the bundle. */
71     private Locale JavaDoc m_locale;
72
73     /** The resource bundle this message object was initialized with. */
74     private ResourceBundle JavaDoc m_resourceBundle;
75
76     /**
77      * Constructor for the messages with an initialized <code>java.util.Locale</code>.
78      *
79      * @param bundleName the base ResourceBundle name
80      * @param locale the m_locale to use, eg. "de", "en" etc.
81      */

82     public CmsMessages(String JavaDoc bundleName, Locale JavaDoc locale) {
83
84         try {
85             m_locale = locale;
86             m_bundleName = bundleName;
87             m_resourceBundle = CmsResourceBundleLoader.getBundle(bundleName, m_locale);
88         } catch (MissingResourceException JavaDoc e) {
89             m_resourceBundle = null;
90         }
91     }
92
93     /**
94      * Constructor for the messages with a language string.<p>
95      *
96      * The <code>language</code> is a 2 letter language ISO code, e.g. <code>"EN"</code>.<p>
97      *
98      * The Locale for the messages will be created like this:<br>
99      * <code>new Locale(language, "", "")</code>.<p>
100      *
101      * @param bundleName the base ResourceBundle name
102      * @param language ISO language indentificator for the m_locale of the bundle
103      */

104     public CmsMessages(String JavaDoc bundleName, String JavaDoc language) {
105
106         this(bundleName, language, "", "");
107     }
108
109     /**
110      * Constructor for the messages with language and country code strings.<p>
111      *
112      * The <code>language</code> is a 2 letter language ISO code, e.g. <code>"EN"</code>.
113      * The <code>country</code> is a 2 letter country ISO code, e.g. <code>"us"</code>.<p>
114      *
115      * The Locale for the messages will be created like this:<br>
116      * <code>new Locale(language, country, "")</code>.
117      *
118      * @param bundleName the base ResourceBundle name
119      * @param language ISO language indentificator for the m_locale of the bundle
120      * @param country ISO 2 letter country code for the m_locale of the bundle
121      */

122     public CmsMessages(String JavaDoc bundleName, String JavaDoc language, String JavaDoc country) {
123
124         this(bundleName, language, country, "");
125     }
126
127     /**
128      * Constructor for the messages with language, country code and variant strings.<p>
129      *
130      * The <code>language</code> is a 2 letter language ISO code, e.g. <code>"EN"</code>.
131      * The <code>country</code> is a 2 letter country ISO code, e.g. <code>"us"</code>.
132      * The <code>variant</code> is a vendor or browser-specific code, e.g. <code>"POSIX"</code>.<p>
133      *
134      * The Locale for the messages will be created like this:<br>
135      * <code>new Locale(language, country, variant)</code>.
136      *
137      * @param bundleName the base ResourceBundle name
138      * @param language language indentificator for the m_locale of the bundle
139      * @param country 2 letter country code for the m_locale of the bundle
140      * @param variant a vendor or browser-specific variant code
141      */

142     public CmsMessages(String JavaDoc bundleName, String JavaDoc language, String JavaDoc country, String JavaDoc variant) {
143
144         this(bundleName, new Locale JavaDoc(language, country, variant));
145     }
146
147     /**
148      * Empty constructor for subclassing.<p>
149      */

150     protected CmsMessages() {
151
152         // empty constructor for subclassing
153
}
154
155     /**
156      * Formats an unknown key.<p>
157      *
158      * @param keyName the key to format
159      * @return the formatted unknown key
160      *
161      * @see #isUnknownKey(String)
162      */

163     public static String JavaDoc formatUnknownKey(String JavaDoc keyName) {
164
165         StringBuffer JavaDoc buf = new StringBuffer JavaDoc(64);
166         buf.append(UNKNOWN_KEY_EXTENSION);
167         buf.append(" ");
168         buf.append(keyName);
169         buf.append(" ");
170         buf.append(UNKNOWN_KEY_EXTENSION);
171         return buf.toString();
172     }
173
174     /**
175      * Returns <code>true</code> if the provided value matches the scheme
176      * <code>"??? " + keyName + " ???"</code>, that is the value appears to be an unknown key.<p>
177      *
178      * Also returns <code>true</code> if the given value is <code>null</code>.<p>
179      *
180      * @param value the value to check
181      * @return true if the value is matches the scheme for unknown keys
182      *
183      * @see #formatUnknownKey(String)
184      */

185     public static boolean isUnknownKey(String JavaDoc value) {
186
187         return (value == null) || (value.startsWith(UNKNOWN_KEY_EXTENSION));
188     }
189
190     /**
191      * @see java.lang.Object#equals(java.lang.Object)
192      */

193     public boolean equals(Object JavaDoc obj) {
194
195         if (obj == this) {
196             return true;
197         }
198         if (obj instanceof CmsMultiMessages) {
199             return false;
200         }
201         if (obj instanceof CmsMessages) {
202             CmsMessages other = (CmsMessages)obj;
203             return other.getBundleName().equals(m_bundleName) && other.getLocale().equals(m_locale);
204         }
205         return false;
206     }
207
208     /**
209      * Returns the resource bundle this message object was initialized with.<p>
210      *
211      * @return the resource bundle this message object was initialized with or null if initialization was not successful
212      */

213     public ResourceBundle JavaDoc getResourceBundle() {
214
215         return m_resourceBundle;
216     }
217
218     /**
219      * Returns a formated date String from a Date value,
220      * the format being {@link DateFormat#SHORT} and the locale
221      * based on this instance.<p>
222      *
223      * @param date the Date object to format as String
224      * @return the formatted date
225      */

226     public String JavaDoc getDate(Date JavaDoc date) {
227
228         return CmsDateUtil.getDate(date, DateFormat.SHORT, m_locale);
229     }
230
231     /**
232      * Returns a formated date String from a Date value,
233      * the formatting based on the provided option and the locale
234      * based on this instance.<p>
235      *
236      * @param date the Date object to format as String
237      * @param format the format to use, see {@link CmsMessages} for possible values
238      * @return the formatted date
239      */

240     public String JavaDoc getDate(Date JavaDoc date, int format) {
241
242         return CmsDateUtil.getDate(date, format, m_locale);
243     }
244
245     /**
246      * Returns a formated date String from a timestamp value,
247      * the format being {@link DateFormat#SHORT} and the locale
248      * based on this instance.<p>
249      *
250      * @param time the time value to format as date
251      * @return the formatted date
252      */

253     public String JavaDoc getDate(long time) {
254
255         return CmsDateUtil.getDate(new Date JavaDoc(time), DateFormat.SHORT, m_locale);
256     }
257
258     /**
259      * Returns a formated date and time String from a Date value,
260      * the format being {@link DateFormat#SHORT} and the locale
261      * based on this instance.<p>
262      *
263      * @param date the Date object to format as String
264      * @return the formatted date and time
265      */

266     public String JavaDoc getDateTime(Date JavaDoc date) {
267
268         return CmsDateUtil.getDateTime(date, DateFormat.SHORT, m_locale);
269     }
270
271     /**
272      * Returns a formated date and time String from a Date value,
273      * the formatting based on the provided option and the locale
274      * based on this instance.<p>
275      *
276      * @param date the Date object to format as String
277      * @param format the format to use, see {@link CmsMessages} for possible values
278      * @return the formatted date and time
279      */

280     public String JavaDoc getDateTime(Date JavaDoc date, int format) {
281
282         return CmsDateUtil.getDateTime(date, format, m_locale);
283     }
284
285     /**
286      * Returns a formated date and time String from a timestamp value,
287      * the format being {@link DateFormat#SHORT} and the locale
288      * based on this instance.<p>
289      *
290      * @param time the time value to format as date
291      * @return the formatted date and time
292      */

293     public String JavaDoc getDateTime(long time) {
294
295         return CmsDateUtil.getDateTime(new Date JavaDoc(time), DateFormat.SHORT, m_locale);
296     }
297
298     /**
299      * Returns the locale to use for looking up this messages.<p>
300      *
301      * @return the locale to use for looking up this messages
302      */

303     public Locale JavaDoc getLocale() {
304
305         return m_locale;
306     }
307
308     /**
309      * Directly calls the getString(String) method of the wrapped ResourceBundle.<p>
310      *
311      * If you use this this class on a template, you should consider using
312      * the {@link #key(String)} method to get the value from the ResourceBundle because it
313      * handles the exception for you in a convenient way.
314      *
315      * @param keyName the key
316      * @return the resource string for the given key
317      *
318      * @throws CmsMessageException in case the key is not found or the bundle is not initialized
319      */

320     public String JavaDoc getString(String JavaDoc keyName) throws CmsMessageException {
321
322         if (m_resourceBundle != null) {
323             try {
324                 return m_resourceBundle.getString(keyName);
325             } catch (MissingResourceException JavaDoc e) {
326                 throw new CmsMessageException(Messages.get().container(
327                     Messages.ERR_CANT_FIND_RESOURCE_FOR_BUNDLE_2,
328                     keyName,
329                     m_bundleName));
330             }
331         } else {
332             throw new CmsMessageException(Messages.get().container(
333                 Messages.ERR_MESSAGE_BUNDLE_NOT_INITIALIZED_1,
334                 m_bundleName));
335         }
336     }
337
338     /**
339      * @see java.lang.Object#hashCode()
340      */

341     public int hashCode() {
342
343         return m_locale.hashCode() + (m_bundleName == null ? 0 : m_bundleName.hashCode());
344     }
345
346     /**
347      * Checks if the bundle was properly initialized.
348      *
349      * @return <code>true</code> if bundle was initialized, <code>false</code> otherwise
350      */

351     public boolean isInitialized() {
352
353         return (m_resourceBundle != null);
354     }
355
356     /**
357      * Returns the localized resource string for a given message key.<p>
358      *
359      * If the key was not found in the bundle, the return value is
360      * <code>"??? " + keyName + " ???"</code>. This will also be returned
361      * if the bundle was not properly initialized first.
362      *
363      * @param keyName the key for the desired string
364      * @return the resource string for the given key
365      */

366     public String JavaDoc key(String JavaDoc keyName) {
367
368         return key(keyName, false);
369     }
370
371     /**
372      * Returns the localized resource string for a given message key.<p>
373      *
374      * If the key was not found in the bundle, the return value
375      * depends on the setting of the allowNull parameter. If set to false,
376      * the return value is always a String in the format
377      * <code>"??? " + keyName + " ???"</code>.
378      * If set to true, null is returned if the key is not found.
379      * This will also be returned
380      * if the bundle was not properly initialized first.
381      *
382      * @param keyName the key for the desired string
383      * @param allowNull if true, 'null' is an allowed return value
384      * @return the resource string for the given key
385      */

386     public String JavaDoc key(String JavaDoc keyName, boolean allowNull) {
387
388         try {
389             if (m_resourceBundle != null) {
390                 return m_resourceBundle.getString(keyName);
391             }
392         } catch (MissingResourceException JavaDoc e) {
393             // not found, return warning
394
if (allowNull) {
395                 return null;
396             }
397         }
398         return formatUnknownKey(keyName);
399     }
400
401     /**
402      * Returns the selected localized message for the initialized resource bundle and locale.<p>
403      *
404      * Convenience method for messages with one argument.<p>
405      *
406      * @param key the message key
407      * @param arg0 the message argument
408      *
409      * @return the selected localized message for the initialized resource bundle and locale
410      */

411     public String JavaDoc key(String JavaDoc key, Object JavaDoc arg0) {
412
413         return key(key, new Object JavaDoc[] {arg0});
414     }
415
416     /**
417      * Returns the selected localized message for the initialized resource bundle and locale.<p>
418      *
419      * Convenience method for messages with two arguments.<p>
420      *
421      * @param key the message key
422      * @param arg0 the first message argument
423      * @param arg1 the second message argument
424      *
425      * @return the selected localized message for the initialized resource bundle and locale
426      */

427     public String JavaDoc key(String JavaDoc key, Object JavaDoc arg0, Object JavaDoc arg1) {
428
429         return key(key, new Object JavaDoc[] {arg0, arg1});
430     }
431
432     /**
433      * Returns the selected localized message for the initialized resource bundle and locale.<p>
434      *
435      * Convenience method for messages with three arguments.<p>
436      *
437      * @param key the message key
438      * @param arg0 the first message argument
439      * @param arg1 the second message argument
440      * @param arg2 the third message argument
441      *
442      * @return the selected localized message for the initialized resource bundle and locale
443      */

444     public String JavaDoc key(String JavaDoc key, Object JavaDoc arg0, Object JavaDoc arg1, Object JavaDoc arg2) {
445
446         return key(key, new Object JavaDoc[] {arg0, arg1, arg2});
447     }
448
449     /**
450      * Returns the selected localized message for the initialized resource bundle and locale.<p>
451      *
452      * If the key was found in the bundle, it will be formatted using
453      * a <code>{@link MessageFormat}</code> using the provided parameters.<p>
454      *
455      * If the key was not found in the bundle, the return value is
456      * <code>"??? " + keyName + " ???"</code>. This will also be returned
457      * if the bundle was not properly initialized first.
458      *
459      * @param key the message key
460      * @param args the message arguments
461      *
462      * @return the selected localized message for the initialized resource bundle and locale
463      */

464     public String JavaDoc key(String JavaDoc key, Object JavaDoc[] args) {
465
466         if ((args == null) || (args.length == 0)) {
467             // no parameters available, use simple key method
468
return key(key);
469         }
470
471         String JavaDoc result = key(key, true);
472         if (result == null) {
473             // key was not found
474
result = formatUnknownKey(key);
475         } else {
476             // key was found in the bundle - create and apply the formatter
477
MessageFormat JavaDoc formatter = new MessageFormat JavaDoc(result, m_locale);
478             result = formatter.format(args);
479         }
480         // return the result
481
return result;
482     }
483
484     /**
485      * Returns the localized resource string for a given message key.<p>
486      *
487      * If the key was not found in the bundle, the provided default value
488      * is returned.<p>
489      *
490      * @param keyName the key for the desired string
491      * @param defaultValue the default value in case the key does not exist in the bundle
492      * @return the resource string for the given key it it exists, or the given default if not
493      */

494     public String JavaDoc keyDefault(String JavaDoc keyName, String JavaDoc defaultValue) {
495
496         String JavaDoc result = key(keyName, true);
497         return (result == null) ? defaultValue : result;
498     }
499
500     /**
501      * Returns the localized resource string for a given message key,
502      * treating all values appended with "|" as replacement parameters.<p>
503      *
504      * If the key was found in the bundle, it will be formatted using
505      * a <code>{@link MessageFormat}</code> using the provided parameters.
506      * The parameters have to be appended to the key separated by a "|".
507      * For example, the keyName <code>error.message|First|Second</code>
508      * would use the key <code>error.message</code> with the parameters
509      * <code>First</code> and <code>Second</code>. This would be the same as calling
510      * <code>{@link CmsMessages#key(String, Object[])}</code>.<p>
511      *
512      * If no parameters are appended with "|", this is the same as calling
513      * <code>{@link CmsMessages#key(String)}</code>.<p>
514      *
515      * If the key was not found in the bundle, the return value is
516      * <code>"??? " + keyName + " ???"</code>. This will also be returned
517      * if the bundle was not properly initialized first.
518      *
519      * @param keyName the key for the desired string, optinally containing parameters appended with a "|"
520      * @return the resource string for the given key
521      *
522      * @see #key(String, Object[])
523      * @see #key(String)
524      */

525     public String JavaDoc keyWithParams(String JavaDoc keyName) {
526
527         if (keyName.indexOf('|') == -1) {
528             // no separator found, key has no parameters
529
return key(keyName, false);
530         } else {
531             // this key contains parameters
532
String JavaDoc[] values = CmsStringUtil.splitAsArray(keyName, '|');
533             String JavaDoc cutKeyName = values[0];
534             String JavaDoc[] params = new String JavaDoc[values.length - 1];
535             System.arraycopy(values, 1, params, 0, params.length);
536             return key(cutKeyName, params);
537         }
538     }
539
540     /**
541      * @see java.lang.Object#toString()
542      */

543     public String JavaDoc toString() {
544
545         StringBuffer JavaDoc result = new StringBuffer JavaDoc();
546
547         result.append('[');
548         result.append(this.getClass().getName());
549         result.append(", baseName: ");
550         result.append(m_bundleName);
551         result.append(", locale: ");
552         result.append(getLocale());
553         result.append(']');
554
555         return result.toString();
556     }
557
558     /**
559      * Returns the name of the resource bundle this object was initialized with.<p>
560      *
561      * @return the name of the resource bundle this object was initialized with
562      */

563     protected String JavaDoc getBundleName() {
564
565         return m_bundleName;
566     }
567
568     /**
569      * Sets the bundleName.<p>
570      *
571      * @param bundleName the bundleName to set
572      */

573     protected void setBundleName(String JavaDoc bundleName) {
574
575         m_bundleName = bundleName;
576     }
577
578     /**
579      * Sets the locale.<p>
580      *
581      * @param locale the locale to set
582      */

583     protected void setLocale(Locale JavaDoc locale) {
584
585         m_locale = locale;
586     }
587
588     /**
589      * Sets the resource bundle.<p>
590      *
591      * @param resourceBundle the resource bundle to set
592      */

593     protected void setResourceBundle(ResourceBundle JavaDoc resourceBundle) {
594
595         m_resourceBundle = resourceBundle;
596     }
597 }
Popular Tags