KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > ibm > icu > text > MessageFormat


1 /*
2 **********************************************************************
3 * Copyright (c) 2004-2006, International Business Machines
4 * Corporation and others. All Rights Reserved.
5 **********************************************************************
6 * Author: Alan Liu
7 * Created: April 6, 2004
8 * Since: ICU 3.0
9 **********************************************************************
10 */

11 package com.ibm.icu.text;
12
13 import java.io.IOException JavaDoc;
14 import java.io.InvalidObjectException JavaDoc;
15 import java.io.ObjectInputStream JavaDoc;
16 import java.text.ChoiceFormat JavaDoc;
17 import java.text.FieldPosition JavaDoc;
18 import java.text.Format JavaDoc;
19 import java.text.ParseException JavaDoc;
20 import java.text.ParsePosition JavaDoc;
21 import java.util.Date JavaDoc;
22 import java.util.Locale JavaDoc;
23
24 import com.ibm.icu.impl.Utility;
25 import com.ibm.icu.text.RuleBasedNumberFormat;
26 import com.ibm.icu.util.ULocale;
27
28 /**
29  * <code>MessageFormat</code> provides a means to produce concatenated
30  * messages in language-neutral way. Use this to construct messages
31  * displayed for end users.
32  *
33  * <p>
34  * <code>MessageFormat</code> takes a set of objects, formats them, then
35  * inserts the formatted strings into the pattern at the appropriate places.
36  *
37  * <p>
38  * <strong>Note:</strong>
39  * <code>MessageFormat</code> differs from the other <code>Format</code>
40  * classes in that you create a <code>MessageFormat</code> object with one
41  * of its constructors (not with a <code>getInstance</code> style factory
42  * method). The factory methods aren't necessary because <code>MessageFormat</code>
43  * itself doesn't implement locale specific behavior. Any locale specific
44  * behavior is defined by the pattern that you provide as well as the
45  * subformats used for inserted arguments.
46  *
47  * <h4><a name="patterns">Patterns and Their Interpretation</a></h4>
48  *
49  * <code>MessageFormat</code> uses patterns of the following form:
50  * <blockquote><pre>
51  * <i>MessageFormatPattern:</i>
52  * <i>String</i>
53  * <i>MessageFormatPattern</i> <i>FormatElement</i> <i>String</i>
54  *
55  * <i>FormatElement:</i>
56  * { <i>ArgumentIndex</i> }
57  * { <i>ArgumentIndex</i> , <i>FormatType</i> }
58  * { <i>ArgumentIndex</i> , <i>FormatType</i> , <i>FormatStyle</i> }
59  *
60  * <i>FormatType: one of </i>
61  * number date time choice
62  *
63  * <i>FormatStyle:</i>
64  * short
65  * medium
66  * long
67  * full
68  * integer
69  * currency
70  * percent
71  * <i>SubformatPattern</i>
72  *
73  * <i>String:</i>
74  * <i>StringPart<sub>opt</sub></i>
75  * <i>String</i> <i>StringPart</i>
76  *
77  * <i>StringPart:</i>
78  * ''
79  * ' <i>QuotedString</i> '
80  * <i>UnquotedString</i>
81  *
82  * <i>SubformatPattern:</i>
83  * <i>SubformatPatternPart<sub>opt</sub></i>
84  * <i>SubformatPattern</i> <i>SubformatPatternPart</i>
85  *
86  * <i>SubFormatPatternPart:</i>
87  * ' <i>QuotedPattern</i> '
88  * <i>UnquotedPattern</i>
89  * </pre></blockquote>
90  *
91  * <p>
92  * Within a <i>String</i>, <code>"''"</code> represents a single
93  * quote. A <i>QuotedString</i> can contain arbitrary characters
94  * except single quotes; the surrounding single quotes are removed.
95  * An <i>UnquotedString</i> can contain arbitrary characters
96  * except single quotes and left curly brackets. Thus, a string that
97  * should result in the formatted message "'{0}'" can be written as
98  * <code>"'''{'0}''"</code> or <code>"'''{0}'''"</code>.
99  * <p>
100  * Within a <i>SubformatPattern</i>, different rules apply.
101  * A <i>QuotedPattern</i> can contain arbitrary characters
102  * except single quotes; but the surrounding single quotes are
103  * <strong>not</strong> removed, so they may be interpreted by the
104  * subformat. For example, <code>"{1,number,$'#',##}"</code> will
105  * produce a number format with the pound-sign quoted, with a result
106  * such as: "$#31,45".
107  * An <i>UnquotedPattern</i> can contain arbitrary characters
108  * except single quotes, but curly braces within it must be balanced.
109  * For example, <code>"ab {0} de"</code> and <code>"ab '}' de"</code>
110  * are valid subformat patterns, but <code>"ab {0'}' de"</code> and
111  * <code>"ab } de"</code> are not.
112  * <p>
113  * <dl><dt><b>Warning:</b><dd>The rules for using quotes within message
114  * format patterns unfortunately have shown to be somewhat confusing.
115  * In particular, it isn't always obvious to localizers whether single
116  * quotes need to be doubled or not. Make sure to inform localizers about
117  * the rules, and tell them (for example, by using comments in resource
118  * bundle source files) which strings will be processed by MessageFormat.
119  * Note that localizers may need to use single quotes in translated
120  * strings where the original version doesn't have them.
121  * <br>Note also that the simplest way to avoid the problem is to
122  * use the real apostrophe (single quote) character ’ (') for
123  * human-readable text, and to use the ASCII apostrophe (' ' )
124  * only in program syntax, like quoting in MessageFormat.
125  * See the annotations for U+0027 Apostrophe in The Unicode Standard.</p>
126  * </dl>
127  * <p>
128  * The <i>ArgumentIndex</i> value is a non-negative integer written
129  * using the digits '0' through '9', and represents an index into the
130  * <code>arguments</code> array passed to the <code>format</code> methods
131  * or the result array returned by the <code>parse</code> methods.
132  * <p>
133  * The <i>FormatType</i> and <i>FormatStyle</i> values are used to create
134  * a <code>Format</code> instance for the format element. The following
135  * table shows how the values map to Format instances. Combinations not
136  * shown in the table are illegal. A <i>SubformatPattern</i> must
137  * be a valid pattern string for the Format subclass used.
138  * <p>
139  * <table border=1>
140  * <tr>
141  * <th>Format Type
142  * <th>Format Style
143  * <th>Subformat Created
144  * <tr>
145  * <td colspan=2><i>(none)</i>
146  * <td><code>null</code>
147  * <tr>
148  * <td rowspan=5><code>number</code>
149  * <td><i>(none)</i>
150  * <td><code>NumberFormat.getInstance(getLocale())</code>
151  * <tr>
152  * <td><code>integer</code>
153  * <td><code>NumberFormat.getIntegerInstance(getLocale())</code>
154  * <tr>
155  * <td><code>currency</code>
156  * <td><code>NumberFormat.getCurrencyInstance(getLocale())</code>
157  * <tr>
158  * <td><code>percent</code>
159  * <td><code>NumberFormat.getPercentInstance(getLocale())</code>
160  * <tr>
161  * <td><i>SubformatPattern</i>
162  * <td><code>new DecimalFormat(subformatPattern, new DecimalFormatSymbols(getLocale()))</code>
163  * <tr>
164  * <td rowspan=6><code>date</code>
165  * <td><i>(none)</i>
166  * <td><code>DateFormat.getDateInstance(DateFormat.DEFAULT, getLocale())</code>
167  * <tr>
168  * <td><code>short</code>
169  * <td><code>DateFormat.getDateInstance(DateFormat.SHORT, getLocale())</code>
170  * <tr>
171  * <td><code>medium</code>
172  * <td><code>DateFormat.getDateInstance(DateFormat.DEFAULT, getLocale())</code>
173  * <tr>
174  * <td><code>long</code>
175  * <td><code>DateFormat.getDateInstance(DateFormat.LONG, getLocale())</code>
176  * <tr>
177  * <td><code>full</code>
178  * <td><code>DateFormat.getDateInstance(DateFormat.FULL, getLocale())</code>
179  * <tr>
180  * <td><i>SubformatPattern</i>
181  * <td><code>new SimpleDateFormat(subformatPattern, getLocale())
182  * <tr>
183  * <td rowspan=6><code>time</code>
184  * <td><i>(none)</i>
185  * <td><code>DateFormat.getTimeInstance(DateFormat.DEFAULT, getLocale())</code>
186  * <tr>
187  * <td><code>short</code>
188  * <td><code>DateFormat.getTimeInstance(DateFormat.SHORT, getLocale())</code>
189  * <tr>
190  * <td><code>medium</code>
191  * <td><code>DateFormat.getTimeInstance(DateFormat.DEFAULT, getLocale())</code>
192  * <tr>
193  * <td><code>long</code>
194  * <td><code>DateFormat.getTimeInstance(DateFormat.LONG, getLocale())</code>
195  * <tr>
196  * <td><code>full</code>
197  * <td><code>DateFormat.getTimeInstance(DateFormat.FULL, getLocale())</code>
198  * <tr>
199  * <td><i>SubformatPattern</i>
200  * <td><code>new SimpleDateFormat(subformatPattern, getLocale())
201  * <tr>
202  * <td><code>choice</code>
203  * <td><i>SubformatPattern</i>
204  * <td><code>new ChoiceFormat(subformatPattern)</code>
205  * </table>
206  * <p>
207  *
208  * <h4>Usage Information</h4>
209  *
210  * <p>
211  * Here are some examples of usage:
212  * <blockquote>
213  * <pre>
214  * Object[] arguments = {
215  * new Integer(7),
216  * new Date(System.currentTimeMillis()),
217  * "a disturbance in the Force"
218  * };
219  *
220  * String result = MessageFormat.format(
221  * "At {1,time} on {1,date}, there was {2} on planet {0,number,integer}.",
222  * arguments);
223  *
224  * <em>output</em>: At 12:30 PM on Jul 3, 2053, there was a disturbance
225  * in the Force on planet 7.
226  *
227  * </pre>
228  * </blockquote>
229  * Typically, the message format will come from resources, and the
230  * arguments will be dynamically set at runtime.
231  *
232  * <p>
233  * Example 2:
234  * <blockquote>
235  * <pre>
236  * Object[] testArgs = {new Long(3), "MyDisk"};
237  *
238  * MessageFormat form = new MessageFormat(
239  * "The disk \"{1}\" contains {0} file(s).");
240  *
241  * System.out.println(form.format(testArgs));
242  *
243  * // output, with different testArgs
244  * <em>output</em>: The disk "MyDisk" contains 0 file(s).
245  * <em>output</em>: The disk "MyDisk" contains 1 file(s).
246  * <em>output</em>: The disk "MyDisk" contains 1,273 file(s).
247  * </pre>
248  * </blockquote>
249  *
250  * <p>
251  * For more sophisticated patterns, you can use a <code>ChoiceFormat</code> to get
252  * output such as:
253  * <blockquote>
254  * <pre>
255  * MessageFormat form = new MessageFormat("The disk \"{1}\" contains {0}.");
256  * double[] filelimits = {0,1,2};
257  * String[] filepart = {"no files","one file","{0,number} files"};
258  * ChoiceFormat fileform = new ChoiceFormat(filelimits, filepart);
259  * form.setFormatByArgumentIndex(0, fileform);
260  *
261  * Object[] testArgs = {new Long(12373), "MyDisk"};
262  *
263  * System.out.println(form.format(testArgs));
264  *
265  * // output, with different testArgs
266  * output: The disk "MyDisk" contains no files.
267  * output: The disk "MyDisk" contains one file.
268  * output: The disk "MyDisk" contains 1,273 files.
269  * </pre>
270  * </blockquote>
271  * You can either do this programmatically, as in the above example,
272  * or by using a pattern (see
273  * {@link ChoiceFormat}
274  * for more information) as in:
275  * <blockquote>
276  * <pre>
277  * form.applyPattern(
278  * "There {0,choice,0#are no files|1#is one file|1&lt;are {0,number,integer} files}.");
279  * </pre>
280  * </blockquote>
281  * <p>
282  * <strong>Note:</strong> As we see above, the string produced
283  * by a <code>ChoiceFormat</code> in <code>MessageFormat</code> is treated specially;
284  * occurances of '{' are used to indicated subformats, and cause recursion.
285  * If you create both a <code>MessageFormat</code> and <code>ChoiceFormat</code>
286  * programmatically (instead of using the string patterns), then be careful not to
287  * produce a format that recurses on itself, which will cause an infinite loop.
288  * <p>
289  * When a single argument is parsed more than once in the string, the last match
290  * will be the final result of the parsing. For example,
291  * <pre>
292  * MessageFormat mf = new MessageFormat("{0,number,#.##}, {0,number,#.#}");
293  * Object[] objs = {new Double(3.1415)};
294  * String result = mf.format( objs );
295  * // result now equals "3.14, 3.1"
296  * objs = null;
297  * objs = mf.parse(result, new ParsePosition(0));
298  * // objs now equals {new Double(3.1)}
299  * </pre>
300  * <p>
301  * Likewise, parsing with a MessageFormat object using patterns containing
302  * multiple occurances of the same argument would return the last match. For
303  * example,
304  * <pre>
305  * MessageFormat mf = new MessageFormat("{0}, {0}, {0}");
306  * String forParsing = "x, y, z";
307  * Object[] objs = mf.parse(forParsing, new ParsePosition(0));
308  * // result now equals {new String("z")}
309  * </pre>
310  *
311  * <h4><a name="synchronization">Synchronization</a></h4>
312  *
313  * <p>
314  * Message formats are not synchronized.
315  * It is recommended to create separate format instances for each thread.
316  * If multiple threads access a format concurrently, it must be synchronized
317  * externally.
318  *
319  * @see java.util.Locale
320  * @see Format
321  * @see NumberFormat
322  * @see DecimalFormat
323  * @see ChoiceFormat
324  * @author Mark Davis
325  * @stable ICU 3.0
326  */

327 public class MessageFormat extends UFormat {
328
329     // Generated by serialver from JDK 1.4.1_01
330
static final long serialVersionUID = 7136212545847378651L;
331
332     /**
333      * Constructs a MessageFormat for the default locale and the
334      * specified pattern.
335      * The constructor first sets the locale, then parses the pattern and
336      * creates a list of subformats for the format elements contained in it.
337      * Patterns and their interpretation are specified in the
338      * <a HREF="#patterns">class description</a>.
339      *
340      * @param pattern the pattern for this message format
341      * @exception IllegalArgumentException if the pattern is invalid
342      * @stable ICU 3.0
343      */

344     public MessageFormat(String JavaDoc pattern) {
345         this.ulocale = ULocale.getDefault();
346         applyPattern(pattern);
347     }
348
349     /**
350      * Constructs a MessageFormat for the specified locale and
351      * pattern.
352      * The constructor first sets the locale, then parses the pattern and
353      * creates a list of subformats for the format elements contained in it.
354      * Patterns and their interpretation are specified in the
355      * <a HREF="#patterns">class description</a>.
356      *
357      * @param pattern the pattern for this message format
358      * @param locale the locale for this message format
359      * @exception IllegalArgumentException if the pattern is invalid
360      * @stable ICU 3.0
361      */

362     public MessageFormat(String JavaDoc pattern, Locale JavaDoc locale) {
363         this(pattern, ULocale.forLocale(locale));
364     }
365
366     /**
367      * Constructs a MessageFormat for the specified locale and
368      * pattern.
369      * The constructor first sets the locale, then parses the pattern and
370      * creates a list of subformats for the format elements contained in it.
371      * Patterns and their interpretation are specified in the
372      * <a HREF="#patterns">class description</a>.
373      *
374      * @param pattern the pattern for this message format
375      * @param locale the locale for this message format
376      * @exception IllegalArgumentException if the pattern is invalid
377      * @stable ICU 3.2
378      */

379     public MessageFormat(String JavaDoc pattern, ULocale locale) {
380         this.ulocale = locale;
381         applyPattern(pattern);
382     }
383
384     /**
385      * Sets the locale to be used when creating or comparing subformats.
386      * This affects subsequent calls to the {@link #applyPattern applyPattern}
387      * and {@link #toPattern toPattern} methods as well as to the
388      * <code>format</code> and
389      * {@link #formatToCharacterIterator formatToCharacterIterator} methods.
390      *
391      * @param locale the locale to be used when creating or comparing subformats
392      * @stable ICU 3.0
393      */

394     public void setLocale(Locale JavaDoc locale) {
395         setLocale(ULocale.forLocale(locale));
396     }
397
398     /**
399      * Sets the locale to be used when creating or comparing subformats.
400      * This affects subsequent calls to the {@link #applyPattern applyPattern}
401      * and {@link #toPattern toPattern} methods as well as to the
402      * <code>format</code> and
403      * {@link #formatToCharacterIterator formatToCharacterIterator} methods.
404      *
405      * @param locale the locale to be used when creating or comparing subformats
406      * @stable ICU 3.2
407      */

408     public void setLocale(ULocale locale) {
409         /* Save the pattern, and then reapply so that */
410         /* we pick up any changes in locale specific */
411         /* elements */
412         String JavaDoc existingPattern = toPattern(); /*ibm.3550*/
413         this.ulocale = locale;
414         applyPattern(existingPattern); /*ibm.3550*/
415     }
416
417     /**
418      * Gets the locale that's used when creating or comparing subformats.
419      *
420      * @return the locale used when creating or comparing subformats
421      * @stable ICU 3.0
422      */

423     public Locale JavaDoc getLocale() {
424         return ulocale.toLocale();
425     }
426
427     /**
428      * Gets the locale that's used when creating or comparing subformats.
429      *
430      * @return the locale used when creating or comparing subformats
431      * @stable ICU 3.2
432      */

433     public ULocale getULocale() {
434         return ulocale;
435     }
436
437     /**
438      * Sets the pattern used by this message format.
439      * The method parses the pattern and creates a list of subformats
440      * for the format elements contained in it.
441      * Patterns and their interpretation are specified in the
442      * <a HREF="#patterns">class description</a>.
443      *
444      * @param pattern the pattern for this message format
445      * @exception IllegalArgumentException if the pattern is invalid
446      * @stable ICU 3.0
447      */

448     public void applyPattern(String JavaDoc pattern) {
449             StringBuffer JavaDoc[] segments = new StringBuffer JavaDoc[4];
450             for (int i = 0; i < segments.length; ++i) {
451                 segments[i] = new StringBuffer JavaDoc();
452             }
453             int part = 0;
454             int formatNumber = 0;
455             boolean inQuote = false;
456             int braceStack = 0;
457             maxOffset = -1;
458             for (int i = 0; i < pattern.length(); ++i) {
459                 char ch = pattern.charAt(i);
460                 if (part == 0) {
461                     if (ch == '\'') {
462                         if (i + 1 < pattern.length()
463                             && pattern.charAt(i+1) == '\'') {
464                             segments[part].append(ch); // handle doubles
465
++i;
466                         } else {
467                             inQuote = !inQuote;
468                         }
469                     } else if (ch == '{' && !inQuote) {
470                         part = 1;
471                     } else {
472                         segments[part].append(ch);
473                     }
474                 } else if (inQuote) { // just copy quotes in parts
475
segments[part].append(ch);
476                     if (ch == '\'') {
477                         inQuote = false;
478                     }
479                 } else {
480                     switch (ch) {
481                     case ',':
482                         if (part < 3)
483                             part += 1;
484                         else
485                             segments[part].append(ch);
486                         break;
487                     case '{':
488                         ++braceStack;
489                         segments[part].append(ch);
490                         break;
491                     case '}':
492                         if (braceStack == 0) {
493                             part = 0;
494                             makeFormat(i, formatNumber, segments);
495                             formatNumber++;
496                         } else {
497                             --braceStack;
498                             segments[part].append(ch);
499                         }
500                         break;
501                     case '\'':
502                         inQuote = true;
503                         // fall through, so we keep quotes in other parts
504
default:
505                         segments[part].append(ch);
506                         break;
507                     }
508                 }
509             }
510             if (braceStack == 0 && part != 0) {
511                 maxOffset = -1;
512                 throw new IllegalArgumentException JavaDoc("Unmatched braces in the pattern.");
513             }
514             this.pattern = segments[0].toString();
515     }
516
517
518     /**
519      * Returns a pattern representing the current state of the message format.
520      * The string is constructed from internal information and therefore
521      * does not necessarily equal the previously applied pattern.
522      *
523      * @return a pattern representing the current state of the message format
524      * @stable ICU 3.0
525      */

526     public String JavaDoc toPattern() {
527         // later, make this more extensible
528
int lastOffset = 0;
529         StringBuffer JavaDoc result = new StringBuffer JavaDoc();
530         for (int i = 0; i <= maxOffset; ++i) {
531             copyAndFixQuotes(pattern, lastOffset, offsets[i],result);
532             lastOffset = offsets[i];
533             result.append('{');
534             result.append(argumentNumbers[i]);
535             if (formats[i] == null) {
536                 // do nothing, string format
537
} else if (formats[i] instanceof DecimalFormat) {
538                 if (formats[i].equals(NumberFormat.getInstance(ulocale))) {
539                     result.append(",number");
540                 } else if (formats[i].equals(NumberFormat.getCurrencyInstance(ulocale))) {
541                     result.append(",number,currency");
542                 } else if (formats[i].equals(NumberFormat.getPercentInstance(ulocale))) {
543                     result.append(",number,percent");
544                 } else if (formats[i].equals(NumberFormat.getIntegerInstance(ulocale))) {
545                     result.append(",number,integer");
546                 } else {
547                     result.append(",number," +
548                                   ((DecimalFormat)formats[i]).toPattern());
549                 }
550             } else if (formats[i] instanceof SimpleDateFormat) {
551                 if (formats[i].equals(DateFormat.getDateInstance(DateFormat.DEFAULT,ulocale))) {
552                     result.append(",date");
553                 } else if (formats[i].equals(DateFormat.getDateInstance(DateFormat.SHORT,ulocale))) {
554                     result.append(",date,short");
555 // This code will never be executed [alan]
556
// } else if (formats[i].equals(DateFormat.getDateInstance(DateFormat.DEFAULT,ulocale))) {
557
// result.append(",date,medium");
558
} else if (formats[i].equals(DateFormat.getDateInstance(DateFormat.LONG,ulocale))) {
559                     result.append(",date,long");
560                 } else if (formats[i].equals(DateFormat.getDateInstance(DateFormat.FULL,ulocale))) {
561                     result.append(",date,full");
562                 } else if (formats[i].equals(DateFormat.getTimeInstance(DateFormat.DEFAULT,ulocale))) {
563                     result.append(",time");
564                 } else if (formats[i].equals(DateFormat.getTimeInstance(DateFormat.SHORT,ulocale))) {
565                     result.append(",time,short");
566 // This code will never be executed [alan]
567
// } else if (formats[i].equals(DateFormat.getTimeInstance(DateFormat.DEFAULT,ulocale))) {
568
// result.append(",time,medium");
569
} else if (formats[i].equals(DateFormat.getTimeInstance(DateFormat.LONG,ulocale))) {
570                     result.append(",time,long");
571                 } else if (formats[i].equals(DateFormat.getTimeInstance(DateFormat.FULL,ulocale))) {
572                     result.append(",time,full");
573                 } else {
574                     result.append(",date," + ((SimpleDateFormat)formats[i]).toPattern());
575                 }
576             } else if (formats[i] instanceof ChoiceFormat JavaDoc) {
577                 result.append(",choice," + ((ChoiceFormat JavaDoc)formats[i]).toPattern());
578             } else {
579                 //result.append(", unknown");
580
}
581             result.append('}');
582         }
583         copyAndFixQuotes(pattern, lastOffset, pattern.length(), result);
584         return result.toString();
585     }
586
587     /**
588      * Sets the formats to use for the values passed into
589      * <code>format</code> methods or returned from <code>parse</code>
590      * methods. The indices of elements in <code>newFormats</code>
591      * correspond to the argument indices used in the previously set
592      * pattern string.
593      * The order of formats in <code>newFormats</code> thus corresponds to
594      * the order of elements in the <code>arguments</code> array passed
595      * to the <code>format</code> methods or the result array returned
596      * by the <code>parse</code> methods.
597      * <p>
598      * If an argument index is used for more than one format element
599      * in the pattern string, then the corresponding new format is used
600      * for all such format elements. If an argument index is not used
601      * for any format element in the pattern string, then the
602      * corresponding new format is ignored. If fewer formats are provided
603      * than needed, then only the formats for argument indices less
604      * than <code>newFormats.length</code> are replaced.
605      *
606      * @param newFormats the new formats to use
607      * @exception NullPointerException if <code>newFormats</code> is null
608      * @stable ICU 3.0
609      */

610     public void setFormatsByArgumentIndex(Format JavaDoc[] newFormats) {
611         for (int i = 0; i <= maxOffset; i++) {
612             int j = argumentNumbers[i];
613             if (j < newFormats.length) {
614                 formats[i] = newFormats[j];
615             }
616         }
617     }
618
619     /**
620      * Sets the formats to use for the format elements in the
621      * previously set pattern string.
622      * The order of formats in <code>newFormats</code> corresponds to
623      * the order of format elements in the pattern string.
624      * <p>
625      * If more formats are provided than needed by the pattern string,
626      * the remaining ones are ignored. If fewer formats are provided
627      * than needed, then only the first <code>newFormats.length</code>
628      * formats are replaced.
629      * <p>
630      * Since the order of format elements in a pattern string often
631      * changes during localization, it is generally better to use the
632      * {@link #setFormatsByArgumentIndex setFormatsByArgumentIndex}
633      * method, which assumes an order of formats corresponding to the
634      * order of elements in the <code>arguments</code> array passed to
635      * the <code>format</code> methods or the result array returned by
636      * the <code>parse</code> methods.
637      *
638      * @param newFormats the new formats to use
639      * @exception NullPointerException if <code>newFormats</code> is null
640      * @stable ICU 3.0
641      */

642     public void setFormats(Format JavaDoc[] newFormats) {
643         int runsToCopy = newFormats.length;
644         if (runsToCopy > maxOffset + 1) {
645             runsToCopy = maxOffset + 1;
646         }
647         for (int i = 0; i < runsToCopy; i++) {
648             formats[i] = newFormats[i];
649         }
650     }
651
652     /**
653      * Sets the format to use for the format elements within the
654      * previously set pattern string that use the given argument
655      * index.
656      * The argument index is part of the format element definition and
657      * represents an index into the <code>arguments</code> array passed
658      * to the <code>format</code> methods or the result array returned
659      * by the <code>parse</code> methods.
660      * <p>
661      * If the argument index is used for more than one format element
662      * in the pattern string, then the new format is used for all such
663      * format elements. If the argument index is not used for any format
664      * element in the pattern string, then the new format is ignored.
665      *
666      * @param argumentIndex the argument index for which to use the new format
667      * @param newFormat the new format to use
668      * @stable ICU 3.0
669      */

670     public void setFormatByArgumentIndex(int argumentIndex, Format JavaDoc newFormat) {
671         for (int j = 0; j <= maxOffset; j++) {
672             if (argumentNumbers[j] == argumentIndex) {
673                 formats[j] = newFormat;
674             }
675         }
676     }
677
678     /**
679      * Sets the format to use for the format element with the given
680      * format element index within the previously set pattern string.
681      * The format element index is the zero-based number of the format
682      * element counting from the start of the pattern string.
683      * <p>
684      * Since the order of format elements in a pattern string often
685      * changes during localization, it is generally better to use the
686      * {@link #setFormatByArgumentIndex setFormatByArgumentIndex}
687      * method, which accesses format elements based on the argument
688      * index they specify.
689      *
690      * @param formatElementIndex the index of a format element within the pattern
691      * @param newFormat the format to use for the specified format element
692      * @exception ArrayIndexOutOfBoundsException if formatElementIndex is equal to or
693      * larger than the number of format elements in the pattern string
694      * @stable ICU 3.0
695      */

696     public void setFormat(int formatElementIndex, Format JavaDoc newFormat) {
697         formats[formatElementIndex] = newFormat;
698     }
699
700     /**
701      * Gets the formats used for the values passed into
702      * <code>format</code> methods or returned from <code>parse</code>
703      * methods. The indices of elements in the returned array
704      * correspond to the argument indices used in the previously set
705      * pattern string.
706      * The order of formats in the returned array thus corresponds to
707      * the order of elements in the <code>arguments</code> array passed
708      * to the <code>format</code> methods or the result array returned
709      * by the <code>parse</code> methods.
710      * <p>
711      * If an argument index is used for more than one format element
712      * in the pattern string, then the format used for the last such
713      * format element is returned in the array. If an argument index
714      * is not used for any format element in the pattern string, then
715      * null is returned in the array.
716      *
717      * @return the formats used for the arguments within the pattern
718      * @stable ICU 3.0
719      */

720     public Format JavaDoc[] getFormatsByArgumentIndex() {
721         int maximumArgumentNumber = -1;
722         for (int i = 0; i <= maxOffset; i++) {
723             if (argumentNumbers[i] > maximumArgumentNumber) {
724                 maximumArgumentNumber = argumentNumbers[i];
725             }
726         }
727         Format JavaDoc[] resultArray = new Format JavaDoc[maximumArgumentNumber + 1];
728         for (int i = 0; i <= maxOffset; i++) {
729             resultArray[argumentNumbers[i]] = formats[i];
730         }
731         return resultArray;
732     }
733
734     /**
735      * Gets the formats used for the format elements in the
736      * previously set pattern string.
737      * The order of formats in the returned array corresponds to
738      * the order of format elements in the pattern string.
739      * <p>
740      * Since the order of format elements in a pattern string often
741      * changes during localization, it's generally better to use the
742      * {@link #getFormatsByArgumentIndex getFormatsByArgumentIndex}
743      * method, which assumes an order of formats corresponding to the
744      * order of elements in the <code>arguments</code> array passed to
745      * the <code>format</code> methods or the result array returned by
746      * the <code>parse</code> methods.
747      *
748      * @return the formats used for the format elements in the pattern
749      * @stable ICU 3.0
750      */

751     public Format JavaDoc[] getFormats() {
752         Format JavaDoc[] resultArray = new Format JavaDoc[maxOffset + 1];
753         System.arraycopy(formats, 0, resultArray, 0, maxOffset + 1);
754         return resultArray;
755     }
756
757     /**
758      * Formats an array of objects and appends the <code>MessageFormat</code>'s
759      * pattern, with format elements replaced by the formatted objects, to the
760      * provided <code>StringBuffer</code>.
761      * <p>
762      * The text substituted for the individual format elements is derived from
763      * the current subformat of the format element and the
764      * <code>arguments</code> element at the format element's argument index
765      * as indicated by the first matching line of the following table. An
766      * argument is <i>unavailable</i> if <code>arguments</code> is
767      * <code>null</code> or has fewer than argumentIndex+1 elements.
768      * <p>
769      * <table border=1>
770      * <tr>
771      * <th>Subformat
772      * <th>Argument
773      * <th>Formatted Text
774      * <tr>
775      * <td><i>any</i>
776      * <td><i>unavailable</i>
777      * <td><code>"{" + argumentIndex + "}"</code>
778      * <tr>
779      * <td><i>any</i>
780      * <td><code>null</code>
781      * <td><code>"null"</code>
782      * <tr>
783      * <td><code>instanceof ChoiceFormat</code>
784      * <td><i>any</i>
785      * <td><code>subformat.format(argument).indexOf('{') >= 0 ?<br>
786      * (new MessageFormat(subformat.format(argument), getLocale())).format(argument) :
787      * subformat.format(argument)</code>
788      * <tr>
789      * <td><code>!= null</code>
790      * <td><i>any</i>
791      * <td><code>subformat.format(argument)</code>
792      * <tr>
793      * <td><code>null</code>
794      * <td><code>instanceof Number</code>
795      * <td><code>NumberFormat.getInstance(getLocale()).format(argument)</code>
796      * <tr>
797      * <td><code>null</code>
798      * <td><code>instanceof Date</code>
799      * <td><code>DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, getLocale()).format(argument)</code>
800      * <tr>
801      * <td><code>null</code>
802      * <td><code>instanceof String</code>
803      * <td><code>argument</code>
804      * <tr>
805      * <td><code>null</code>
806      * <td><i>any</i>
807      * <td><code>argument.toString()</code>
808      * </table>
809      * <p>
810      * If <code>pos</code> is non-null, and refers to
811      * <code>Field.ARGUMENT</code>, the location of the first formatted
812      * string will be returned.
813      *
814      * @param arguments an array of objects to be formatted and substituted.
815      * @param result where text is appended.
816      * @param pos On input: an alignment field, if desired.
817      * On output: the offsets of the alignment field.
818      * @exception IllegalArgumentException if an argument in the
819      * <code>arguments</code> array is not of the type
820      * expected by the format element(s) that use it.
821      * @stable ICU 3.0
822      */

823     public final StringBuffer JavaDoc format(Object JavaDoc[] arguments, StringBuffer JavaDoc result,
824                                      FieldPosition JavaDoc pos)
825     {
826         return subformat(arguments, result, pos);
827     }
828
829     /**
830      * Creates a MessageFormat with the given pattern and uses it
831      * to format the given arguments. This is equivalent to
832      * <blockquote>
833      * <code>(new {@link #MessageFormat(String) MessageFormat}(pattern)).{@link #format(java.lang.Object[], java.lang.StringBuffer, java.text.FieldPosition) format}(arguments, new StringBuffer(), null).toString()</code>
834      * </blockquote>
835      *
836      * @exception IllegalArgumentException if the pattern is invalid,
837      * or if an argument in the <code>arguments</code> array
838      * is not of the type expected by the format element(s)
839      * that use it.
840      * @stable ICU 3.0
841      */

842     public static String JavaDoc format(String JavaDoc pattern, Object JavaDoc[] arguments) {
843         MessageFormat temp = new MessageFormat(pattern);
844         return temp.format(arguments);
845     }
846
847     // Overrides
848
/**
849      * Formats an array of objects and appends the <code>MessageFormat</code>'s
850      * pattern, with format elements replaced by the formatted objects, to the
851      * provided <code>StringBuffer</code>.
852      * This is equivalent to
853      * <blockquote>
854      * <code>{@link #format(java.lang.Object[], java.lang.StringBuffer, java.text.FieldPosition) format}((Object[]) arguments, result, pos)</code>
855      * </blockquote>
856      *
857      * @param arguments an array of objects to be formatted and substituted.
858      * @param result where text is appended.
859      * @param pos On input: an alignment field, if desired.
860      * On output: the offsets of the alignment field.
861      * @exception IllegalArgumentException if an argument in the
862      * <code>arguments</code> array is not of the type
863      * expected by the format element(s) that use it.
864      * @stable ICU 3.0
865      */

866     public final StringBuffer JavaDoc format(Object JavaDoc arguments, StringBuffer JavaDoc result,
867                                      FieldPosition JavaDoc pos)
868     {
869         return subformat((Object JavaDoc[]) arguments, result, pos);
870     }
871
872 // TODO Do not remove, this is API in JDK that we need to implement
873
// /**
874
// * Formats an array of objects and inserts them into the
875
// * <code>MessageFormat</code>'s pattern, producing an
876
// * <code>AttributedCharacterIterator</code>.
877
// * You can use the returned <code>AttributedCharacterIterator</code>
878
// * to build the resulting String, as well as to determine information
879
// * about the resulting String.
880
// * <p>
881
// * The text of the returned <code>AttributedCharacterIterator</code> is
882
// * the same that would be returned by
883
// * <blockquote>
884
// * <code>{@link #format(java.lang.Object[], java.lang.StringBuffer, java.text.FieldPosition) format}(arguments, new StringBuffer(), null).toString()</code>
885
// * </blockquote>
886
// * <p>
887
// * In addition, the <code>AttributedCharacterIterator</code> contains at
888
// * least attributes indicating where text was generated from an
889
// * argument in the <code>arguments</code> array. The keys of these attributes are of
890
// * type <code>MessageFormat.Field</code>, their values are
891
// * <code>Integer</code> objects indicating the index in the <code>arguments</code>
892
// * array of the argument from which the text was generated.
893
// * <p>
894
// * The attributes/value from the underlying <code>Format</code>
895
// * instances that <code>MessageFormat</code> uses will also be
896
// * placed in the resulting <code>AttributedCharacterIterator</code>.
897
// * This allows you to not only find where an argument is placed in the
898
// * resulting String, but also which fields it contains in turn.
899
// *
900
// * @param arguments an array of objects to be formatted and substituted.
901
// * @return AttributedCharacterIterator describing the formatted value.
902
// * @exception NullPointerException if <code>arguments</code> is null.
903
// * @exception IllegalArgumentException if an argument in the
904
// * <code>arguments</code> array is not of the type
905
// * expected by the format element(s) that use it.
906
// */
907
// public AttributedCharacterIterator formatToCharacterIterator(Object arguments) {
908
// StringBuffer result = new StringBuffer();
909
// ArrayList iterators = new ArrayList();
910
//
911
// if (arguments == null) {
912
// throw new NullPointerException(
913
// "formatToCharacterIterator must be passed non-null object");
914
// }
915
// subformat((Object[]) arguments, result, null, iterators);
916
// if (iterators.size() == 0) {
917
// return createAttributedCharacterIterator("");
918
// }
919
// return createAttributedCharacterIterator(
920
// (AttributedCharacterIterator[])iterators.toArray(
921
// new AttributedCharacterIterator[iterators.size()]));
922
// }
923

924     /**
925      * Parses the string.
926      *
927      * <p>Caveats: The parse may fail in a number of circumstances.
928      * For example:
929      * <ul>
930      * <li>If one of the arguments does not occur in the pattern.
931      * <li>If the format of an argument loses information, such as
932      * with a choice format where a large number formats to "many".
933      * <li>Does not yet handle recursion (where
934      * the substituted strings contain {n} references.)
935      * <li>Will not always find a match (or the correct match)
936      * if some part of the parse is ambiguous.
937      * For example, if the pattern "{1},{2}" is used with the
938      * string arguments {"a,b", "c"}, it will format as "a,b,c".
939      * When the result is parsed, it will return {"a", "b,c"}.
940  &