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      * <li>If a single argument is parsed more than once in the string,
941      * then the later parse wins.
942      * </ul>
943      * When the parse fails, use ParsePosition.getErrorIndex() to find out
944      * where in the string did the parsing failed. The returned error
945      * index is the starting offset of the sub-patterns that the string
946      * is comparing with. For example, if the parsing string "AAA {0} BBB"
947      * is comparing against the pattern "AAD {0} BBB", the error index is
948      * 0. When an error occurs, the call to this method will return null.
949      * If the source is null, return an empty array.
950      * @stable ICU 3.0
951      */

952     public Object JavaDoc[] parse(String JavaDoc source, ParsePosition JavaDoc pos) {
953         if (source == null) {
954             Object JavaDoc[] empty = {};
955             return empty;
956         }
957
958         int maximumArgumentNumber = -1;
959         for (int i = 0; i <= maxOffset; i++) {
960             if (argumentNumbers[i] > maximumArgumentNumber) {
961                 maximumArgumentNumber = argumentNumbers[i];
962             }
963         }
964         Object JavaDoc[] resultArray = new Object JavaDoc[maximumArgumentNumber + 1];
965
966         int patternOffset = 0;
967         int sourceOffset = pos.getIndex();
968         ParsePosition JavaDoc tempStatus = new ParsePosition JavaDoc(0);
969         for (int i = 0; i <= maxOffset; ++i) {
970             // match up to format
971
int len = offsets[i] - patternOffset;
972             if (len == 0 || pattern.regionMatches(patternOffset,
973                                                   source, sourceOffset, len)) {
974                 sourceOffset += len;
975                 patternOffset += len;
976             } else {
977                 pos.setErrorIndex(sourceOffset);
978                 return null; // leave index as is to signal error
979
}
980
981             // now use format
982
if (formats[i] == null) { // string format
983
// if at end, use longest possible match
984
// otherwise uses first match to intervening string
985
// does NOT recursively try all possibilities
986
int tempLength = (i != maxOffset) ? offsets[i+1] : pattern.length();
987
988                 int next;
989                 if (patternOffset >= tempLength) {
990                     next = source.length();
991                 }else{
992                     next = source.indexOf( pattern.substring(patternOffset,tempLength), sourceOffset);
993                 }
994
995                 if (next < 0) {
996                     pos.setErrorIndex(sourceOffset);
997                     return null; // leave index as is to signal error
998
} else {
999                     String JavaDoc strValue= source.substring(sourceOffset,next);
1000                    if (!strValue.equals("{"+argumentNumbers[i]+"}"))
1001                        resultArray[argumentNumbers[i]]
1002                            = source.substring(sourceOffset,next);
1003                    sourceOffset = next;
1004                }
1005            } else {
1006                tempStatus.setIndex(sourceOffset);
1007                resultArray[argumentNumbers[i]]
1008                    = formats[i].parseObject(source,tempStatus);
1009                if (tempStatus.getIndex() == sourceOffset) {
1010                    pos.setErrorIndex(sourceOffset);
1011                    return null; // leave index as is to signal error
1012
}
1013                sourceOffset = tempStatus.getIndex(); // update
1014
}
1015        }
1016        int len = pattern.length() - patternOffset;
1017        if (len == 0 || pattern.regionMatches(patternOffset,
1018                                              source, sourceOffset, len)) {
1019            pos.setIndex(sourceOffset + len);
1020        } else {
1021            pos.setErrorIndex(sourceOffset);
1022            return null; // leave index as is to signal error
1023
}
1024        return resultArray;
1025    }
1026
1027    /**
1028     * Parses text from the beginning of the given string to produce an object
1029     * array.
1030     * The method may not use the entire text of the given string.
1031     * <p>
1032     * See the {@link #parse(String, ParsePosition)} method for more information
1033     * on message parsing.
1034     *
1035     * @param source A <code>String</code> whose beginning should be parsed.
1036     * @return An <code>Object</code> array parsed from the string.
1037     * @exception ParseException if the beginning of the specified string
1038     * cannot be parsed.
1039     * @stable ICU 3.0
1040     */

1041    public Object JavaDoc[] parse(String JavaDoc source) throws ParseException JavaDoc {
1042        ParsePosition JavaDoc pos = new ParsePosition JavaDoc(0);
1043        Object JavaDoc[] result = parse(source, pos);
1044        if (pos.getIndex() == 0) // unchanged, returned object is null
1045
throw new ParseException JavaDoc("MessageFormat parse error!", pos.getErrorIndex());
1046
1047        return result;
1048    }
1049
1050    /**
1051     * Parses text from a string to produce an object array.
1052     * <p>
1053     * The method attempts to parse text starting at the index given by
1054     * <code>pos</code>.
1055     * If parsing succeeds, then the index of <code>pos</code> is updated
1056     * to the index after the last character used (parsing does not necessarily
1057     * use all characters up to the end of the string), and the parsed
1058     * object array is returned. The updated <code>pos</code> can be used to
1059     * indicate the starting point for the next call to this method.
1060     * If an error occurs, then the index of <code>pos</code> is not
1061     * changed, the error index of <code>pos</code> is set to the index of
1062     * the character where the error occurred, and null is returned.
1063     * <p>
1064     * See the {@link #parse(String, ParsePosition)} method for more information
1065     * on message parsing.
1066     *
1067     * @param source A <code>String</code>, part of which should be parsed.
1068     * @param pos A <code>ParsePosition</code> object with index and error
1069     * index information as described above.
1070     * @return An <code>Object</code> array parsed from the string. In case of
1071     * error, returns null.
1072     * @exception NullPointerException if <code>pos</code> is null.
1073     * @stable ICU 3.0
1074     */

1075    public Object JavaDoc parseObject(String JavaDoc source, ParsePosition JavaDoc pos) {
1076        return parse(source, pos);
1077    }
1078
1079    /**
1080     * Creates and returns a copy of this object.
1081     *
1082     * @return a clone of this instance.
1083     * @stable ICU 3.0
1084     */

1085    public Object JavaDoc clone() {
1086        MessageFormat other = (MessageFormat) super.clone();
1087
1088        // clone arrays. Can't do with utility because of bug in Cloneable
1089
other.formats = (Format JavaDoc[]) formats.clone(); // shallow clone
1090
for (int i = 0; i < formats.length; ++i) {
1091            if (formats[i] != null)
1092                other.formats[i] = (Format JavaDoc)formats[i].clone();
1093        }
1094        // for primitives or immutables, shallow clone is enough
1095
other.offsets = (int[]) offsets.clone();
1096        other.argumentNumbers = (int[]) argumentNumbers.clone();
1097
1098        return other;
1099    }
1100
1101    /**
1102     * Equality comparison between two message format objects
1103     * @stable ICU 3.0
1104     */

1105    public boolean equals(Object JavaDoc obj) {
1106        if (this == obj) // quick check
1107
return true;
1108        if (obj == null || getClass() != obj.getClass())
1109            return false;
1110        MessageFormat other = (MessageFormat) obj;
1111        return (maxOffset == other.maxOffset
1112                && pattern.equals(other.pattern)
1113                && Utility.objectEquals(ulocale, other.ulocale) // does null check
1114
&& Utility.arrayEquals(offsets,other.offsets)
1115                && Utility.arrayEquals(argumentNumbers,other.argumentNumbers)
1116                && Utility.arrayEquals(formats,other.formats));
1117    }
1118
1119    /**
1120     * Generates a hash code for the message format object.
1121     * @stable ICU 3.0
1122     */

1123    public int hashCode() {
1124        return pattern.hashCode(); // enough for reasonable distribution
1125
}
1126
1127// TODO Do not remove, this is API in JDK that we need to implement
1128
// /**
1129
// * Defines constants that are used as attribute keys in the
1130
// * <code>AttributedCharacterIterator</code> returned
1131
// * from <code>MessageFormat.formatToCharacterIterator</code>.
1132
// * @draft ICU 3.0
1133
// * @provisional This API might change or be removed in a future release.
1134
// */
1135
// public static class Field extends Format.Field {
1136
// /**
1137
// * Creates a Field with the specified name.
1138
// *
1139
// * @param name Name of the attribute
1140
// */
1141
// protected Field(String name) {
1142
// super(name);
1143
// }
1144
//
1145
// /**
1146
// * Resolves instances being deserialized to the predefined constants.
1147
// *
1148
// * @throws InvalidObjectException if the constant could not be
1149
// * resolved.
1150
// * @return resolved MessageFormat.Field constant
1151
// */
1152
// protected Object readResolve() throws InvalidObjectException {
1153
// if (this.getClass() != MessageFormat.Field.class) {
1154
// throw new InvalidObjectException("subclass didn't correctly implement readResolve");
1155
// }
1156
//
1157
// return ARGUMENT;
1158
// }
1159
//
1160
// //
1161
// // The constants
1162
// //
1163
//
1164
// /**
1165
// * Constant identifying a portion of a message that was generated
1166
// * from an argument passed into <code>formatToCharacterIterator</code>.
1167
// * The value associated with the key will be an <code>Integer</code>
1168
// * indicating the index in the <code>arguments</code> array of the
1169
// * argument from which the text was generated.
1170
// */
1171
// public final static Field ARGUMENT =
1172
// new Field("message argument field");
1173
// }
1174

1175    // ===========================privates============================
1176

1177    /**
1178     * The locale to use for formatting numbers and dates.
1179     * This is no longer used, and here only for serialization compatibility.
1180     * @serial
1181     */

1182    private Locale JavaDoc locale;
1183
1184    /**
1185     * The locale to use for formatting numbers and dates.
1186     * @serial
1187     */

1188    private ULocale ulocale;
1189
1190    /**
1191     * The string that the formatted values are to be plugged into. In other words, this
1192     * is the pattern supplied on construction with all of the {} expressions taken out.
1193     * @serial
1194     */

1195    private String JavaDoc pattern = "";
1196
1197    /** The initially expected number of subformats in the format */
1198    private static final int INITIAL_FORMATS = 10;
1199
1200    /**
1201     * An array of formatters, which are used to format the arguments.
1202     * @serial
1203     */

1204    private Format JavaDoc[] formats = new Format JavaDoc[INITIAL_FORMATS];
1205
1206    /**
1207     * The positions where the results of formatting each argument are to be inserted
1208     * into the pattern.
1209     * @serial
1210     */

1211    private int[] offsets = new int[INITIAL_FORMATS];
1212
1213    /**
1214     * The argument numbers corresponding to each formatter. (The formatters are stored
1215     * in the order they occur in the pattern, not in the order in which the arguments
1216     * are specified.)
1217     * @serial
1218     */

1219    private int[] argumentNumbers = new int[INITIAL_FORMATS];
1220
1221    /**
1222     * One less than the number of entries in <code>offsets</code>. Can also be thought of
1223     * as the index of the highest-numbered element in <code>offsets</code> that is being used.
1224     * All of these arrays should have the same number of elements being used as <code>offsets</code>
1225     * does, and so this variable suffices to tell us how many entries are in all of them.
1226     * @serial
1227     */

1228    private int maxOffset = -1;
1229
1230    /**
1231     * Internal routine used by format. If <code>characterIterators</code> is
1232     * non-null, AttributedCharacterIterator will be created from the
1233     * subformats as necessary. If <code>characterIterators</code> is null
1234     * and <code>fp</code> is non-null and identifies
1235     * <code>Field.MESSAGE_ARGUMENT</code>, the location of
1236     * the first replaced argument will be set in it.
1237     *
1238     * @exception IllegalArgumentException if an argument in the
1239     * <code>arguments</code> array is not of the type
1240     * expected by the format element(s) that use it.
1241     */

1242    private StringBuffer JavaDoc subformat(Object JavaDoc[] arguments, StringBuffer JavaDoc result,
1243                                   FieldPosition JavaDoc fp
1244                                   /*, List characterIterators*/) {
1245        // note: this implementation assumes a fast substring & index.
1246
// if this is not true, would be better to append chars one by one.
1247
int lastOffset = 0;
1248        int last = result.length();
1249        for (int i = 0; i <= maxOffset; ++i) {
1250            result.append(pattern.substring(lastOffset, offsets[i]));
1251            lastOffset = offsets[i];
1252            int argumentNumber = argumentNumbers[i];
1253            if (arguments == null || argumentNumber >= arguments.length) {
1254                result.append("{" + argumentNumber + "}");
1255                continue;
1256            }
1257            // int argRecursion = ((recursionProtection >> (argumentNumber*2)) & 0x3);
1258
if (false) { // if (argRecursion == 3){
1259
// prevent loop!!!
1260
result.append('\uFFFD');
1261            } else {
1262                Object JavaDoc obj = arguments[argumentNumber];
1263                String JavaDoc arg = null;
1264                Format JavaDoc subFormatter = null;
1265                if (obj == null) {
1266                    arg = "null";
1267                } else if (formats[i] != null) {
1268                    subFormatter = formats[i];
1269                    if (subFormatter instanceof ChoiceFormat JavaDoc) {
1270                        arg = formats[i].format(obj);
1271                        if (arg.indexOf('{') >= 0) {
1272                            subFormatter = new MessageFormat(arg, ulocale);
1273                            obj = arguments;
1274                            arg = null;
1275                        }
1276                    }
1277                } else if (obj instanceof Number JavaDoc) {
1278                    // format number if can
1279
subFormatter = NumberFormat.getInstance(ulocale);
1280                } else if (obj instanceof Date JavaDoc) {
1281                    // format a Date if can
1282
subFormatter = DateFormat.getDateTimeInstance(
1283                             DateFormat.SHORT, DateFormat.SHORT, ulocale);//fix
1284
} else if (obj instanceof String JavaDoc) {
1285                    arg = (String JavaDoc) obj;
1286
1287                } else {
1288                    arg = obj.toString();
1289                    if (arg == null) arg = "null";
1290                }
1291
1292                // At this point we are in two states, either subFormatter
1293
// is non-null indicating we should format obj using it,
1294
// or arg is non-null and we should use it as the value.
1295

1296// TODO Do not remove, this is API in JDK that we need to implement
1297
// if (characterIterators != null) {
1298
// // If characterIterators is non-null, it indicates we need
1299
// // to get the CharacterIterator from the child formatter.
1300
// if (last != result.length()) {
1301
// characterIterators.add(
1302
// createAttributedCharacterIterator(result.substring
1303
// (last)));
1304
// last = result.length();
1305
// }
1306
// if (subFormatter != null) {
1307
// AttributedCharacterIterator subIterator =
1308
// subFormatter.formatToCharacterIterator(obj);
1309
//
1310
// append(result, subIterator);
1311
// if (last != result.length()) {
1312
// characterIterators.add(
1313
// createAttributedCharacterIterator(
1314
// subIterator, Field.ARGUMENT,
1315
// new Integer(argumentNumber)));
1316
// last = result.length();
1317
// }
1318
// arg = null;
1319
// }
1320
// if (arg != null && arg.length() > 0) {
1321
// result.append(arg);
1322
// characterIterators.add(
1323
// createAttributedCharacterIterator(
1324
// arg, Field.ARGUMENT,
1325
// new Integer(argumentNumber)));
1326
// last = result.length();
1327
// }
1328
// }
1329
// else
1330
{
1331                    if (subFormatter != null) {
1332                        arg = subFormatter.format(obj);
1333                    }
1334// last = result.length(); // Useless? [alan]
1335
result.append(arg);
1336// TODO Do not remove, this is JDK API we need to implement.
1337
// if (i == 0 && fp != null && Field.ARGUMENT.equals(
1338
// fp.getFieldAttribute())) {
1339
// fp.setBeginIndex(last);
1340
// fp.setEndIndex(result.length());
1341
// }
1342
last = result.length();
1343                }
1344            }
1345        }
1346        result.append(pattern.substring(lastOffset, pattern.length()));
1347// TODO Do not remove, this is JDK API we need to implement.
1348
// if (characterIterators != null && last != result.length()) {
1349
// characterIterators.add(createAttributedCharacterIterator(
1350
// result.substring(last)));
1351
// }
1352
return result;
1353    }
1354
1355// TODO Do not remove, this is JDK API we need to implement.
1356
// /**
1357
// * Convenience method to append all the characters in
1358
// * <code>iterator</code> to the StringBuffer <code>result</code>.
1359
// */
1360
// private void append(StringBuffer result, CharacterIterator iterator) {
1361
// if (iterator.first() != CharacterIterator.DONE) {
1362
// char aChar;
1363
//
1364
// result.append(iterator.first());
1365
// while ((aChar = iterator.next()) != CharacterIterator.DONE) {
1366
// result.append(aChar);
1367
// }
1368
// }
1369
// }
1370

1371    private static final String JavaDoc[] typeList =
1372        {"", "number", "date", "time", "choice", "spellout", "ordinal", "duration"};
1373    private static final int
1374        TYPE_EMPTY = 0,
1375        TYPE_NUMBER = 1,
1376        TYPE_DATE = 2,
1377        TYPE_TIME = 3,
1378        TYPE_CHOICE = 4,
1379        TYPE_SPELLOUT = 5,
1380        TYPE_ORDINAL = 6,
1381        TYPE_DURATION = 7;
1382
1383    private static final String JavaDoc[] modifierList =
1384        {"", "currency", "percent", "integer"};
1385    private static final int
1386        MODIFIER_EMPTY = 0,
1387        MODIFIER_CURRENCY = 1,
1388        MODIFIER_PERCENT = 2,
1389        MODIFIER_INTEGER = 3;
1390
1391    private static final String JavaDoc[] dateModifierList =
1392        {"", "short", "medium", "long", "full"};
1393    private static final int
1394        DATE_MODIFIER_EMPTY = 0,
1395        DATE_MODIFIER_SHORT = 1,
1396        DATE_MODIFIER_MEDIUM = 2,
1397        DATE_MODIFIER_LONG = 3,
1398        DATE_MODIFIER_FULL = 4;
1399
1400    private void makeFormat(int position, int offsetNumber,
1401                            StringBuffer JavaDoc[] segments)
1402    {
1403        // get the argument number
1404
int argumentNumber;
1405        try {
1406            argumentNumber = Integer.parseInt(segments[1].toString()); // always unlocalized!
1407
} catch (NumberFormatException JavaDoc e) {
1408            throw new IllegalArgumentException JavaDoc("can't parse argument number " + segments[1]);
1409        }
1410        if (argumentNumber < 0) {
1411            throw new IllegalArgumentException JavaDoc("negative argument number " + argumentNumber);
1412        }
1413
1414        // resize format information arrays if necessary
1415
if (offsetNumber >= formats.length) {
1416            int newLength = formats.length * 2;
1417            Format JavaDoc[] newFormats = new Format JavaDoc[newLength];
1418            int[] newOffsets = new int[newLength];
1419            int[] newArgumentNumbers = new int[newLength];
1420            System.arraycopy(formats, 0, newFormats, 0, maxOffset + 1);
1421            System.arraycopy(offsets, 0, newOffsets, 0, maxOffset + 1);
1422            System.arraycopy(argumentNumbers, 0, newArgumentNumbers, 0, maxOffset + 1);
1423            formats = newFormats;
1424            offsets = newOffsets;
1425            argumentNumbers = newArgumentNumbers;
1426        }
1427        int oldMaxOffset = maxOffset;
1428        maxOffset = offsetNumber;
1429        offsets[offsetNumber] = segments[0].length();
1430        argumentNumbers[offsetNumber] = argumentNumber;
1431
1432        // now get the format
1433
Format JavaDoc newFormat = null;
1434        switch (findKeyword(segments[2].toString(), typeList)) {
1435        case TYPE_EMPTY:
1436            break;
1437        case TYPE_NUMBER:
1438            switch (findKeyword(segments[3].toString(), modifierList)) {
1439            case MODIFIER_EMPTY:
1440                newFormat = NumberFormat.getInstance(ulocale);
1441                break;
1442            case MODIFIER_CURRENCY:
1443                newFormat = NumberFormat.getCurrencyInstance(ulocale);
1444                break;
1445            case MODIFIER_PERCENT:
1446                newFormat = NumberFormat.getPercentInstance(ulocale);
1447                break;
1448            case MODIFIER_INTEGER:
1449                newFormat = NumberFormat.getIntegerInstance(ulocale);
1450                break;
1451            default: // pattern
1452
newFormat = new DecimalFormat(segments[3].toString(), new DecimalFormatSymbols(ulocale));
1453                break;
1454            }
1455            break;
1456        case TYPE_DATE:
1457            switch (findKeyword(segments[3].toString(), dateModifierList)) {
1458            case DATE_MODIFIER_EMPTY:
1459                newFormat = DateFormat.getDateInstance(DateFormat.DEFAULT, ulocale);
1460                break;
1461            case DATE_MODIFIER_SHORT:
1462                newFormat = DateFormat.getDateInstance(DateFormat.SHORT, ulocale);
1463                break;
1464            case DATE_MODIFIER_MEDIUM:
1465                newFormat = DateFormat.getDateInstance(DateFormat.DEFAULT, ulocale);
1466                break;
1467            case DATE_MODIFIER_LONG:
1468                newFormat = DateFormat.getDateInstance(DateFormat.LONG, ulocale);
1469                break;
1470            case DATE_MODIFIER_FULL:
1471                newFormat = DateFormat.getDateInstance(DateFormat.FULL, ulocale);
1472                break;
1473            default:
1474                newFormat = new SimpleDateFormat(segments[3].toString(), ulocale);
1475                break;
1476            }
1477            break;
1478        case TYPE_TIME:
1479            switch (findKeyword(segments[3].toString(), dateModifierList)) {
1480            case DATE_MODIFIER_EMPTY:
1481                newFormat = DateFormat.getTimeInstance(DateFormat.DEFAULT, ulocale);
1482                break;
1483            case DATE_MODIFIER_SHORT:
1484                newFormat = DateFormat.getTimeInstance(DateFormat.SHORT, ulocale);
1485                break;
1486            case DATE_MODIFIER_MEDIUM:
1487                newFormat = DateFormat.getTimeInstance(DateFormat.DEFAULT, ulocale);
1488                break;
1489            case DATE_MODIFIER_LONG:
1490                newFormat = DateFormat.getTimeInstance(DateFormat.LONG, ulocale);
1491                break;
1492            case DATE_MODIFIER_FULL:
1493                newFormat = DateFormat.getTimeInstance(DateFormat.FULL, ulocale);
1494                break;
1495            default:
1496                newFormat = new SimpleDateFormat(segments[3].toString(), ulocale);
1497                break;
1498            }
1499            break;
1500        case TYPE_CHOICE:
1501            try {
1502                newFormat = new ChoiceFormat JavaDoc(segments[3].toString());
1503            } catch (Exception JavaDoc e) {
1504                maxOffset = oldMaxOffset;
1505                throw new IllegalArgumentException JavaDoc(
1506                                         "Choice Pattern incorrect");
1507            }
1508            break;
1509        case TYPE_SPELLOUT:
1510            {
1511                RuleBasedNumberFormat rbnf = new RuleBasedNumberFormat(ulocale, RuleBasedNumberFormat.SPELLOUT);
1512                String JavaDoc ruleset = segments[3].toString().trim();
1513                if (ruleset.length() != 0) {
1514                    try {
1515                        rbnf.setDefaultRuleSet(ruleset);
1516                    }
1517                    catch (Exception JavaDoc e) {
1518                        // warn invalid ruleset
1519
}
1520                }
1521                newFormat = rbnf;
1522            }
1523            break;
1524        case TYPE_ORDINAL:
1525            {
1526                RuleBasedNumberFormat rbnf = new RuleBasedNumberFormat(ulocale, RuleBasedNumberFormat.ORDINAL);
1527                String JavaDoc ruleset = segments[3].toString().trim();
1528                if (ruleset.length() != 0) {
1529                    try {
1530                        rbnf.setDefaultRuleSet(ruleset);
1531                    }
1532                    catch (Exception JavaDoc e) {
1533                        // warn invalid ruleset
1534
}
1535                }
1536                newFormat = rbnf;
1537            }
1538            break;
1539        case TYPE_DURATION:
1540            {
1541                RuleBasedNumberFormat rbnf = new RuleBasedNumberFormat(ulocale, RuleBasedNumberFormat.DURATION);
1542                String JavaDoc ruleset = segments[3].toString().trim();
1543                if (ruleset.length() != 0) {
1544                    try {
1545                        rbnf.setDefaultRuleSet(ruleset);
1546                    }
1547                    catch (Exception JavaDoc e) {
1548                        // warn invalid ruleset
1549
}
1550                }
1551                newFormat = rbnf;
1552            }
1553            break;
1554        default:
1555            maxOffset = oldMaxOffset;
1556            throw new IllegalArgumentException JavaDoc("unknown format type at ");
1557        }
1558        formats[offsetNumber] = newFormat;
1559        segments[1].setLength(0); // throw away other segments
1560
segments[2].setLength(0);
1561        segments[3].setLength(0);
1562    }
1563
1564    private static final int findKeyword(String JavaDoc s, String JavaDoc[] list) {
1565        s = s.trim().toLowerCase();
1566        for (int i = 0; i < list.length; ++i) {
1567            if (s.equals(list[i]))
1568                return i;
1569        }
1570        return -1;
1571    }
1572
1573    private static final void copyAndFixQuotes(String JavaDoc source, int start, int end, StringBuffer JavaDoc target) {
1574        // added 'gotLB' logic from ICU4C - questionable [alan]
1575
boolean gotLB = false;
1576        for (int i = start; i < end; ++i) {
1577            char ch = source.charAt(i);
1578            if (ch == '{') {
1579                target.append("'{'");
1580                gotLB = true;
1581            } else if (ch == '}') {
1582                if (gotLB) {
1583                    target.append(ch);
1584                    gotLB = false;
1585                } else {
1586                    target.append("'}'");
1587                }
1588            } else if (ch == '\'') {
1589                target.append("''");
1590            } else {
1591                target.append(ch);
1592            }
1593        }
1594    }
1595
1596    /**
1597     * After reading an object from the input stream, do a simple verification
1598     * to maintain class invariants.
1599     * @throws InvalidObjectException if the objects read from the stream is invalid.
1600     */

1601    private void readObject(ObjectInputStream JavaDoc in) throws IOException JavaDoc, ClassNotFoundException JavaDoc {
1602        in.defaultReadObject();
1603        boolean isValid = maxOffset >= -1
1604                && formats.length > maxOffset
1605                && offsets.length > maxOffset
1606                && argumentNumbers.length > maxOffset;
1607        if (isValid) {
1608            int lastOffset = pattern.length() + 1;
1609            for (int i = maxOffset; i >= 0; --i) {
1610                if ((offsets[i] < 0) || (offsets[i] > lastOffset)) {
1611                    isValid = false;
1612                    break;
1613                } else {
1614                    lastOffset = offsets[i];
1615                }
1616            }
1617        }
1618        if (!isValid) {
1619            throw new InvalidObjectException JavaDoc("Could not reconstruct MessageFormat from corrupt stream.");
1620        }
1621        if (ulocale == null) {
1622            ulocale = ULocale.forLocale(locale);
1623        }
1624    }
1625
1626    private static final char SINGLE_QUOTE = '\'';
1627    private static final char CURLY_BRACE_LEFT = '{';
1628    private static final char CURLY_BRACE_RIGHT = '}';
1629
1630    private static final int STATE_INITIAL = 0;
1631    private static final int STATE_SINGLE_QUOTE = 1;
1632    private static final int STATE_IN_QUOTE = 2;
1633    private static final int STATE_MSG_ELEMENT = 3;
1634
1635    /**
1636     * Convert an 'apostrophe-friendly' pattern into a standard
1637     * pattern. Standard patterns treat all apostrophes as
1638     * quotes, which is problematic in some languages, e.g.
1639     * French, where apostrophe is commonly used. This utility
1640     * assumes that only an unpaired apostrophe immediately before
1641     * a brace is a true quote. Other unpaired apostrophes are paired,
1642     * and the resulting standard pattern string is returned.
1643     *
1644     * <p><b>Note</b> it is not guaranteed that the returned pattern
1645     * is indeed a valid pattern. The only effect is to convert
1646     * between patterns having different quoting semantics.
1647     *
1648     * @param pattern the 'apostrophe-friendly' patttern to convert
1649     * @return the standard equivalent of the original pattern
1650     * @draft ICU 3.4
1651     * @provisional This API might change or be removed in a future release.
1652     */

1653    public static String JavaDoc autoQuoteApostrophe(String JavaDoc pattern) {
1654        StringBuffer JavaDoc buf = new StringBuffer JavaDoc(pattern.length()*2);
1655        int state = STATE_INITIAL;
1656        int braceCount = 0;
1657        for (int i = 0, j = pattern.length(); i < j; ++i) {
1658            char c = pattern.charAt(i);
1659            switch (state) {
1660            case STATE_INITIAL:
1661                switch (c) {
1662                case SINGLE_QUOTE:
1663                    state = STATE_SINGLE_QUOTE;
1664                    break;
1665                case CURLY_BRACE_LEFT:
1666                    state = STATE_MSG_ELEMENT;
1667                    ++braceCount;
1668                    break;
1669                }
1670                break;
1671            case STATE_SINGLE_QUOTE:
1672                switch (c) {
1673                case SINGLE_QUOTE:
1674                    state = STATE_INITIAL;
1675                    break;
1676                case CURLY_BRACE_LEFT:
1677                case CURLY_BRACE_RIGHT:
1678                    state = STATE_IN_QUOTE;
1679                    break;
1680                default:
1681                    buf.append(SINGLE_QUOTE);
1682                    state = STATE_INITIAL;
1683                    break;
1684                }
1685                break;
1686            case STATE_IN_QUOTE:
1687                switch (c) {
1688                case SINGLE_QUOTE:
1689                    state = STATE_INITIAL;
1690                    break;
1691                }
1692                break;
1693            case STATE_MSG_ELEMENT:
1694                switch (c) {
1695                case CURLY_BRACE_LEFT:
1696                    ++braceCount;
1697                    break;
1698                case CURLY_BRACE_RIGHT:
1699                    if (--braceCount == 0) {
1700                        state = STATE_INITIAL;
1701                    }
1702                    break;
1703                }
1704                break;
1705            default: // Never happens.
1706
break;
1707            }
1708            buf.append(c);
1709        }
1710        // End of scan
1711
if (state == STATE_SINGLE_QUOTE || state == STATE_IN_QUOTE) {
1712            buf.append(SINGLE_QUOTE);
1713        }
1714        return new String JavaDoc(buf);
1715    }
1716}
1717
Popular Tags