KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > derby > shared > common > i18n > MessageUtil


1 /*
2    Derby - Class org.apache.derby.common.i18n.MessageUtil
3  
4    Licensed to the Apache Software Foundation (ASF) under one or more
5    contributor license agreements. See the NOTICE file distributed with
6    this work for additional information regarding copyright ownership.
7    The ASF licenses this file to you under the Apache License, Version 2.0
8    (the "License"); you may not use this file except in compliance with
9    the License. You may obtain a copy of the License at
10  
11       http://www.apache.org/licenses/LICENSE-2.0
12  
13    Unless required by applicable law or agreed to in writing, software
14    distributed under the License is distributed on an "AS IS" BASIS,
15    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16    See the License for the specific language governing permissions and
17    limitations under the License.
18  
19  */

20 package org.apache.derby.shared.common.i18n;
21
22 import org.apache.derby.shared.common.error.ExceptionSeverity;
23 import org.apache.derby.shared.common.sanity.SanityManager;
24 import java.util.Locale JavaDoc;
25 import java.util.ResourceBundle JavaDoc;
26 import java.util.MissingResourceException JavaDoc;
27 import java.text.MessageFormat JavaDoc;
28
29 /**
30  * Class comments here
31  */

32 public class MessageUtil
33 {
34     public static final Locale JavaDoc US = new Locale JavaDoc("en", "US");
35             
36     /**
37      * The name of the resource bundle we are using to load
38      * messages
39      */

40     private String JavaDoc resourceBundleName;
41     
42     /**
43      * Create an instance of MessageUtil with a specific resource
44      * bundle. This assumes the default locale, which is just fine for
45      * users of this class other than the engine (which potentially has
46      * a different locale and a different resource bundle for each
47      * invocation of getCompleteMessage().
48      *
49      * @param resourceBundleName
50      * The base name of the resource bundle to use.
51      */

52     public MessageUtil(String JavaDoc resourceBundleName)
53     {
54         this.resourceBundleName = resourceBundleName;
55     }
56     
57     /** Get a message with default locale - no arguments */
58        public String JavaDoc getTextMessage(String JavaDoc messageID)
59     {
60         return getCompleteMessage(messageID, (Object JavaDoc[]) null);
61     }
62     
63     /** Get a message with default locale - one argument */
64     public String JavaDoc getTextMessage(String JavaDoc messageID, Object JavaDoc a1)
65     {
66         return getCompleteMessage(messageID, new Object JavaDoc[]{a1});
67     }
68     
69     /** Get a message with default locale - two arguments */
70     public String JavaDoc getTextMessage(String JavaDoc messageID, Object JavaDoc a1, Object JavaDoc a2)
71     {
72         return getCompleteMessage(messageID, new Object JavaDoc[]{a1, a2});
73     }
74     
75     /** Get a message with default locale - three arguments */
76     public String JavaDoc getTextMessage(String JavaDoc messageID, Object JavaDoc a1, Object JavaDoc a2,
77         Object JavaDoc a3)
78     {
79         return getCompleteMessage(messageID, new Object JavaDoc[]{a1, a2, a3});
80     }
81     
82     /** Get a message with default locale - four arguments */
83     public String JavaDoc getTextMessage(String JavaDoc messageID, Object JavaDoc a1, Object JavaDoc a2,
84         Object JavaDoc a3, Object JavaDoc a4)
85     {
86         return getCompleteMessage(messageID, new Object JavaDoc[]{a1, a2, a3, a4});
87     }
88     
89     /**
90      * Instance method to get the complete message, using the
91      * provided resource bundle name as specified when this
92      * instance was constructed
93      *
94      * If for some reason the message could not be found, we return a
95      * default message using the message arguments
96      */

97     public String JavaDoc getCompleteMessage(String JavaDoc messageID, Object JavaDoc[] args)
98     {
99         return getCompleteMessage(messageID, resourceBundleName, args);
100     }
101     
102     /**
103      * Generic routine to get a message with any number of arguments.
104      *
105      * Looks in the provided resource bundle for the message, using the
106      * specified locale and then the US locale.
107      *
108      * @param locale
109      * The locale to use when looking for the message. If the message
110      * is not found using this locale, we attempt to find it using the
111      * US locale (our default).
112      *
113      * @param resourceBundleName
114      * The base name for the resource bundle to use.
115      *
116      * @param messageId
117      * The message identifier for this message
118      *
119      * @param arguments
120      * The arguments for the message
121      *
122      * @param composeDefault
123      * If this is true, this method will compose a default message if
124      * the message could not be found in the
125      * provided resource bundles. If it is false, this method will
126      * throw a MissingResourceException if the message could not be
127      * found.
128      *
129      * @return
130      * The message for the given message id, with arguments
131      * substituted.
132      *
133      * @throws MissingResourceException
134      * If the message could not be found and the
135      * <code>composeDefault</code> parameter was set to false.
136      */

137     public static String JavaDoc getCompleteMessage(Locale JavaDoc locale,
138         String JavaDoc resourceBundleName, String JavaDoc messageId, Object JavaDoc[] arguments,
139         boolean composeDefault) throws MissingResourceException JavaDoc
140     {
141         try
142         {
143             return formatMessage(
144                 ResourceBundle.getBundle(resourceBundleName, locale), messageId,
145                 arguments, false);
146         }
147         catch ( MissingResourceException JavaDoc mre )
148         {
149             // Try the US locale. Use composeDefault to indicate whether
150
// we should compose a default message or throw an exception if
151
// the message still is not found.
152
return formatMessage(
153                     ResourceBundle.getBundle(resourceBundleName, US),
154                     messageId, arguments, composeDefault);
155         }
156     }
157     
158     /**
159      * This is a wrapper for the getCompleteMessage workhorse routine
160      * using some obvious defaults, particularly for non-engine subsystems
161      * that only ever use the default locale.
162      *
163      * Get a message using the default locale. If the message is not found
164      * with the default locale, use the US locale. Do this both for the
165      * common bundle and the parent bundle.
166      *
167      * If the message is not found in common or in the parent resource
168      * bundle, return a default message composed of the message arguments.
169      *
170      * @param messageId
171      * The id to use to look up the message
172      *
173      * @param resourceBundleName
174      * The base name of the resource bundle to use.
175      *
176      * @param arguments
177      * The arguments to the message
178      */

179     public static String JavaDoc getCompleteMessage(String JavaDoc messageId,
180         String JavaDoc resourceBundleName, Object JavaDoc[] arguments)
181         throws MissingResourceException JavaDoc
182     {
183         return getCompleteMessage(Locale.getDefault(), resourceBundleName,
184             messageId, arguments, true);
185     }
186     
187     /**
188      * Format a message given a resource bundle and a message id.
189      * <p>
190      * The arguments to the messages are passed via an object array. The objects
191      * in the array WILL be changed by this class. The caller should NOT get the
192      * object back from this array.
193      *
194      * @param bundle
195      * The resource bundle to use to look for the message
196      *
197      * @param messageId
198      * The message id to use for the message
199      *
200      * @param arguments
201      * The arguments for the message
202      *
203      * @param composeDefault
204      * Indicates whether a default message should be composed if
205      * the message can't be found in the resource bundle.
206      * <p>
207      * If composeDefault is false, this method will
208      * throw a MissingResourceException if the message could not be
209      * found.
210      * <p>
211      * If composeDefault is true, then if the message id is not found in
212      * the given bundle, this method composes and returns as helpful a
213      * message as possible in the format "UNKNOWN : [arg1], [arg2], ..."
214      */

215     public static String JavaDoc formatMessage(ResourceBundle JavaDoc bundle, String JavaDoc messageId,
216         Object JavaDoc[] arguments, boolean composeDefault) {
217
218         String JavaDoc message = null;
219         String JavaDoc badArgsMessage = null;
220         
221         if (arguments == null)
222             arguments = new Object JavaDoc[0];
223
224         if (bundle != null) {
225
226             try {
227                 message = bundle.getString(messageId);
228                 
229                 
230                 // Ensure that the right number of arguments are passed in.
231
if ( SanityManager.DEBUG )
232                 {
233                     int numExpected = countParams(message);
234                     SanityManager.ASSERT(numExpected == arguments.length,
235                         "Number of parameters expected for message id " +
236                         messageId + " (" + numExpected +
237                         ") does not match number of arguments received (" +
238                         arguments.length + ")");
239                 }
240
241                 try {
242                     return MessageFormat.format(message, arguments);
243                 }
244                 catch (IllegalArgumentException JavaDoc iae) {
245                     if ( !composeDefault || SanityManager.DEBUG )
246                         throw iae;
247                 }
248                 catch (NullPointerException JavaDoc npe) {
249                     //
250
//null arguments cause a NullPointerException.
251
//This improves reporting.
252
if ( !composeDefault || SanityManager.DEBUG )
253                         throw npe;
254                 }
255
256             } catch (MissingResourceException JavaDoc mre) {
257                 // caller will try and handle the last chance
258
if (!composeDefault )
259                     throw mre;
260             }
261         }
262
263         return composeDefaultMessage("UNKNOWN MESSAGE, id " + messageId, arguments);
264     }
265     
266     /**
267      * Count the number of substituation parameters in the message
268      */

269     private static int countParams(String JavaDoc message)
270     {
271         boolean openFound = false;
272         int numparams = 0;
273         
274         for ( int i = 0 ; i < message.length() ; i++ )
275         {
276             char ch = message.charAt(i);
277             if ( ch == '{' ) {
278                 openFound = true;
279             }
280             
281             if ( ch == '}' && openFound )
282             {
283                 numparams++;
284                 openFound = false;
285             }
286         }
287         
288         return numparams;
289     }
290
291     /**
292      * Compose a default message so that the user at least gets
293      * *something* useful rather than just a MissingResourceException,
294      * which is particularly unhelpful
295      *
296      * @param message
297      * The message to start with, which often is null
298      *
299      * @param arguments
300      * The arguments to the message.
301      */

302     public static String JavaDoc composeDefaultMessage(String JavaDoc message, Object JavaDoc[] arguments)
303     {
304         if (message == null)
305         {
306             message = "UNKNOWN";
307         }
308         
309         StringBuffer JavaDoc sb = new StringBuffer JavaDoc(message);
310         
311         if ( arguments == null )
312         {
313             return sb.toString();
314         }
315
316         sb.append(" : ");
317         int len = arguments.length;
318
319         for (int i=0; i < len; i++) {
320             // prepend a comma to all but the first
321
if (i > 0)
322                 sb.append(", ");
323
324             sb.append('[');
325             sb.append(i);
326             sb.append("] ");
327             if (arguments[i] == null)
328                 sb.append("null");
329             else
330                 sb.append(arguments[i].toString());
331         }
332
333         return sb.toString();
334     }
335 }
336
Popular Tags