1/*
2 * Copyright (C) 2014 The Android Open Source Project
3 * Copyright (c) 1996, 2010, Oracle and/or its affiliates. All rights reserved.
4 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5 *
6 * This code is free software; you can redistribute it and/or modify it
7 * under the terms of the GNU General Public License version 2 only, as
8 * published by the Free Software Foundation.  Oracle designates this
9 * particular file as subject to the "Classpath" exception as provided
10 * by Oracle in the LICENSE file that accompanied this code.
11 *
12 * This code is distributed in the hope that it will be useful, but WITHOUT
13 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
15 * version 2 for more details (a copy is included in the LICENSE file that
16 * accompanied this code).
17 *
18 * You should have received a copy of the GNU General Public License version
19 * 2 along with this work; if not, write to the Free Software Foundation,
20 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
21 *
22 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
23 * or visit www.oracle.com if you need additional information or have any
24 * questions.
25 */
26
27/*
28 * (C) Copyright Taligent, Inc. 1996, 1997 - All Rights Reserved
29 * (C) Copyright IBM Corp. 1996 - 1998 - All Rights Reserved
30 *
31 *   The original version of this source code and documentation is copyrighted
32 * and owned by Taligent, Inc., a wholly-owned subsidiary of IBM. These
33 * materials are provided under terms of a License Agreement between Taligent
34 * and Sun. This technology is protected by multiple US and International
35 * patents. This notice and attribution to Taligent may not be removed.
36 *   Taligent is a registered trademark of Taligent, Inc.
37 *
38 */
39
40package java.text;
41
42import java.io.InvalidObjectException;
43import java.io.IOException;
44import java.io.ObjectInputStream;
45import java.text.DecimalFormat;
46import java.util.ArrayList;
47import java.util.Arrays;
48import java.util.Date;
49import java.util.List;
50import java.util.Locale;
51
52
53/**
54 * <code>MessageFormat</code> provides a means to produce concatenated
55 * messages in a language-neutral way. Use this to construct messages
56 * displayed for end users.
57 *
58 * <p>
59 * <code>MessageFormat</code> takes a set of objects, formats them, then
60 * inserts the formatted strings into the pattern at the appropriate places.
61 *
62 * <p>
63 * <strong>Note:</strong>
64 * <code>MessageFormat</code> differs from the other <code>Format</code>
65 * classes in that you create a <code>MessageFormat</code> object with one
66 * of its constructors (not with a <code>getInstance</code> style factory
67 * method). The factory methods aren't necessary because <code>MessageFormat</code>
68 * itself doesn't implement locale specific behavior. Any locale specific
69 * behavior is defined by the pattern that you provide as well as the
70 * subformats used for inserted arguments.
71 *
72 * <h4><a name="patterns">Patterns and Their Interpretation</a></h4>
73 *
74 * <code>MessageFormat</code> uses patterns of the following form:
75 * <blockquote><pre>
76 * <i>MessageFormatPattern:</i>
77 *         <i>String</i>
78 *         <i>MessageFormatPattern</i> <i>FormatElement</i> <i>String</i>
79 *
80 * <i>FormatElement:</i>
81 *         { <i>ArgumentIndex</i> }
82 *         { <i>ArgumentIndex</i> , <i>FormatType</i> }
83 *         { <i>ArgumentIndex</i> , <i>FormatType</i> , <i>FormatStyle</i> }
84 *
85 * <i>FormatType: one of </i>
86 *         number date time choice
87 *
88 * <i>FormatStyle:</i>
89 *         short
90 *         medium
91 *         long
92 *         full
93 *         integer
94 *         currency
95 *         percent
96 *         <i>SubformatPattern</i>
97 * </pre></blockquote>
98 *
99 * <p>Within a <i>String</i>, a pair of single quotes can be used to
100 * quote any arbitrary characters except single quotes. For example,
101 * pattern string <code>"'{0}'"</code> represents string
102 * <code>"{0}"</code>, not a <i>FormatElement</i>. A single quote itself
103 * must be represented by doubled single quotes {@code ''} throughout a
104 * <i>String</i>.  For example, pattern string <code>"'{''}'"</code> is
105 * interpreted as a sequence of <code>'{</code> (start of quoting and a
106 * left curly brace), <code>''</code> (a single quote), and
107 * <code>}'</code> (a right curly brace and end of quoting),
108 * <em>not</em> <code>'{'</code> and <code>'}'</code> (quoted left and
109 * right curly braces): representing string <code>"{'}"</code>,
110 * <em>not</em> <code>"{}"</code>.
111 *
112 * <p>A <i>SubformatPattern</i> is interpreted by its corresponding
113 * subformat, and subformat-dependent pattern rules apply. For example,
114 * pattern string <code>"{1,number,<u>$'#',##</u>}"</code>
115 * (<i>SubformatPattern</i> with underline) will produce a number format
116 * with the pound-sign quoted, with a result such as: {@code
117 * "$#31,45"}. Refer to each {@code Format} subclass documentation for
118 * details.
119 *
120 * <p>Any unmatched quote is treated as closed at the end of the given
121 * pattern. For example, pattern string {@code "'{0}"} is treated as
122 * pattern {@code "'{0}'"}.
123 *
124 * <p>Any curly braces within an unquoted pattern must be balanced. For
125 * example, <code>"ab {0} de"</code> and <code>"ab '}' de"</code> are
126 * valid patterns, but <code>"ab {0'}' de"</code>, <code>"ab } de"</code>
127 * and <code>"''{''"</code> are not.
128 *
129 * <p>
130 * <dl><dt><b>Warning:</b><dd>The rules for using quotes within message
131 * format patterns unfortunately have shown to be somewhat confusing.
132 * In particular, it isn't always obvious to localizers whether single
133 * quotes need to be doubled or not. Make sure to inform localizers about
134 * the rules, and tell them (for example, by using comments in resource
135 * bundle source files) which strings will be processed by {@code MessageFormat}.
136 * Note that localizers may need to use single quotes in translated
137 * strings where the original version doesn't have them.
138 * </dl>
139 * <p>
140 * The <i>ArgumentIndex</i> value is a non-negative integer written
141 * using the digits {@code '0'} through {@code '9'}, and represents an index into the
142 * {@code arguments} array passed to the {@code format} methods
143 * or the result array returned by the {@code parse} methods.
144 * <p>
145 * The <i>FormatType</i> and <i>FormatStyle</i> values are used to create
146 * a {@code Format} instance for the format element. The following
147 * table shows how the values map to {@code Format} instances. Combinations not
148 * shown in the table are illegal. A <i>SubformatPattern</i> must
149 * be a valid pattern string for the {@code Format} subclass used.
150 * <p>
151 * <table border=1 summary="Shows how FormatType and FormatStyle values map to Format instances">
152 *    <tr>
153 *       <th id="ft" class="TableHeadingColor">FormatType
154 *       <th id="fs" class="TableHeadingColor">FormatStyle
155 *       <th id="sc" class="TableHeadingColor">Subformat Created
156 *    <tr>
157 *       <td headers="ft"><i>(none)</i>
158 *       <td headers="fs"><i>(none)</i>
159 *       <td headers="sc"><code>null</code>
160 *    <tr>
161 *       <td headers="ft" rowspan=5><code>number</code>
162 *       <td headers="fs"><i>(none)</i>
163 *       <td headers="sc">{@link NumberFormat#getInstance(Locale) NumberFormat.getInstance}{@code (getLocale())}
164 *    <tr>
165 *       <td headers="fs"><code>integer</code>
166 *       <td headers="sc">{@link NumberFormat#getIntegerInstance(Locale) NumberFormat.getIntegerInstance}{@code (getLocale())}
167 *    <tr>
168 *       <td headers="fs"><code>currency</code>
169 *       <td headers="sc">{@link NumberFormat#getCurrencyInstance(Locale) NumberFormat.getCurrencyInstance}{@code (getLocale())}
170 *    <tr>
171 *       <td headers="fs"><code>percent</code>
172 *       <td headers="sc">{@link NumberFormat#getPercentInstance(Locale) NumberFormat.getPercentInstance}{@code (getLocale())}
173 *    <tr>
174 *       <td headers="fs"><i>SubformatPattern</i>
175 *       <td headers="sc">{@code new} {@link DecimalFormat#DecimalFormat(String,DecimalFormatSymbols) DecimalFormat}{@code (subformatPattern,} {@link DecimalFormatSymbols#getInstance(Locale) DecimalFormatSymbols.getInstance}{@code (getLocale()))}
176 *    <tr>
177 *       <td headers="ft" rowspan=6><code>date</code>
178 *       <td headers="fs"><i>(none)</i>
179 *       <td headers="sc">{@link DateFormat#getDateInstance(int,Locale) DateFormat.getDateInstance}{@code (}{@link DateFormat#DEFAULT}{@code , getLocale())}
180 *    <tr>
181 *       <td headers="fs"><code>short</code>
182 *       <td headers="sc">{@link DateFormat#getDateInstance(int,Locale) DateFormat.getDateInstance}{@code (}{@link DateFormat#SHORT}{@code , getLocale())}
183 *    <tr>
184 *       <td headers="fs"><code>medium</code>
185 *       <td headers="sc">{@link DateFormat#getDateInstance(int,Locale) DateFormat.getDateInstance}{@code (}{@link DateFormat#DEFAULT}{@code , getLocale())}
186 *    <tr>
187 *       <td headers="fs"><code>long</code>
188 *       <td headers="sc">{@link DateFormat#getDateInstance(int,Locale) DateFormat.getDateInstance}{@code (}{@link DateFormat#LONG}{@code , getLocale())}
189 *    <tr>
190 *       <td headers="fs"><code>full</code>
191 *       <td headers="sc">{@link DateFormat#getDateInstance(int,Locale) DateFormat.getDateInstance}{@code (}{@link DateFormat#FULL}{@code , getLocale())}
192 *    <tr>
193 *       <td headers="fs"><i>SubformatPattern</i>
194 *       <td headers="sc">{@code new} {@link SimpleDateFormat#SimpleDateFormat(String,Locale) SimpleDateFormat}{@code (subformatPattern, getLocale())}
195 *    <tr>
196 *       <td headers="ft" rowspan=6><code>time</code>
197 *       <td headers="fs"><i>(none)</i>
198 *       <td headers="sc">{@link DateFormat#getTimeInstance(int,Locale) DateFormat.getTimeInstance}{@code (}{@link DateFormat#DEFAULT}{@code , getLocale())}
199 *    <tr>
200 *       <td headers="fs"><code>short</code>
201 *       <td headers="sc">{@link DateFormat#getTimeInstance(int,Locale) DateFormat.getTimeInstance}{@code (}{@link DateFormat#SHORT}{@code , getLocale())}
202 *    <tr>
203 *       <td headers="fs"><code>medium</code>
204 *       <td headers="sc">{@link DateFormat#getTimeInstance(int,Locale) DateFormat.getTimeInstance}{@code (}{@link DateFormat#DEFAULT}{@code , getLocale())}
205 *    <tr>
206 *       <td headers="fs"><code>long</code>
207 *       <td headers="sc">{@link DateFormat#getTimeInstance(int,Locale) DateFormat.getTimeInstance}{@code (}{@link DateFormat#LONG}{@code , getLocale())}
208 *    <tr>
209 *       <td headers="fs"><code>full</code>
210 *       <td headers="sc">{@link DateFormat#getTimeInstance(int,Locale) DateFormat.getTimeInstance}{@code (}{@link DateFormat#FULL}{@code , getLocale())}
211 *    <tr>
212 *       <td headers="fs"><i>SubformatPattern</i>
213 *       <td headers="sc">{@code new} {@link SimpleDateFormat#SimpleDateFormat(String,Locale) SimpleDateFormat}{@code (subformatPattern, getLocale())}
214 *    <tr>
215 *       <td headers="ft"><code>choice</code>
216 *       <td headers="fs"><i>SubformatPattern</i>
217 *       <td headers="sc">{@code new} {@link ChoiceFormat#ChoiceFormat(String) ChoiceFormat}{@code (subformatPattern)}
218 * </table>
219 * <p>
220 *
221 * <h4>Usage Information</h4>
222 *
223 * <p>
224 * Here are some examples of usage.
225 * In real internationalized programs, the message format pattern and other
226 * static strings will, of course, be obtained from resource bundles.
227 * Other parameters will be dynamically determined at runtime.
228 * <p>
229 * The first example uses the static method <code>MessageFormat.format</code>,
230 * which internally creates a <code>MessageFormat</code> for one-time use:
231 * <blockquote><pre>
232 * int planet = 7;
233 * String event = "a disturbance in the Force";
234 *
235 * String result = MessageFormat.format(
236 *     "At {1,time} on {1,date}, there was {2} on planet {0,number,integer}.",
237 *     planet, new Date(), event);
238 * </pre></blockquote>
239 * The output is:
240 * <blockquote><pre>
241 * At 12:30 PM on Jul 3, 2053, there was a disturbance in the Force on planet 7.
242 * </pre></blockquote>
243 *
244 * <p>
245 * The following example creates a <code>MessageFormat</code> instance that
246 * can be used repeatedly:
247 * <blockquote><pre>
248 * int fileCount = 1273;
249 * String diskName = "MyDisk";
250 * Object[] testArgs = {new Long(fileCount), diskName};
251 *
252 * MessageFormat form = new MessageFormat(
253 *     "The disk \"{1}\" contains {0} file(s).");
254 *
255 * System.out.println(form.format(testArgs));
256 * </pre></blockquote>
257 * The output with different values for <code>fileCount</code>:
258 * <blockquote><pre>
259 * The disk "MyDisk" contains 0 file(s).
260 * The disk "MyDisk" contains 1 file(s).
261 * The disk "MyDisk" contains 1,273 file(s).
262 * </pre></blockquote>
263 *
264 * <p>
265 * For more sophisticated patterns, you can use a <code>ChoiceFormat</code>
266 * to produce correct forms for singular and plural:
267 * <blockquote><pre>
268 * MessageFormat form = new MessageFormat("The disk \"{1}\" contains {0}.");
269 * double[] filelimits = {0,1,2};
270 * String[] filepart = {"no files","one file","{0,number} files"};
271 * ChoiceFormat fileform = new ChoiceFormat(filelimits, filepart);
272 * form.setFormatByArgumentIndex(0, fileform);
273 *
274 * int fileCount = 1273;
275 * String diskName = "MyDisk";
276 * Object[] testArgs = {new Long(fileCount), diskName};
277 *
278 * System.out.println(form.format(testArgs));
279 * </pre></blockquote>
280 * The output with different values for <code>fileCount</code>:
281 * <blockquote><pre>
282 * The disk "MyDisk" contains no files.
283 * The disk "MyDisk" contains one file.
284 * The disk "MyDisk" contains 1,273 files.
285 * </pre></blockquote>
286 *
287 * <p>
288 * You can create the <code>ChoiceFormat</code> programmatically, as in the
289 * above example, or by using a pattern. See {@link ChoiceFormat}
290 * for more information.
291 * <blockquote><pre>
292 * form.applyPattern(
293 *    "There {0,choice,0#are no files|1#is one file|1&lt;are {0,number,integer} files}.");
294 * </pre></blockquote>
295 *
296 * <p>
297 * <strong>Note:</strong> As we see above, the string produced
298 * by a <code>ChoiceFormat</code> in <code>MessageFormat</code> is treated as special;
299 * occurrences of '{' are used to indicate subformats, and cause recursion.
300 * If you create both a <code>MessageFormat</code> and <code>ChoiceFormat</code>
301 * programmatically (instead of using the string patterns), then be careful not to
302 * produce a format that recurses on itself, which will cause an infinite loop.
303 * <p>
304 * When a single argument is parsed more than once in the string, the last match
305 * will be the final result of the parsing.  For example,
306 * <blockquote><pre>
307 * MessageFormat mf = new MessageFormat("{0,number,#.##}, {0,number,#.#}");
308 * Object[] objs = {new Double(3.1415)};
309 * String result = mf.format( objs );
310 * // result now equals "3.14, 3.1"
311 * objs = null;
312 * objs = mf.parse(result, new ParsePosition(0));
313 * // objs now equals {new Double(3.1)}
314 * </pre></blockquote>
315 *
316 * <p>
317 * Likewise, parsing with a {@code MessageFormat} object using patterns containing
318 * multiple occurrences of the same argument would return the last match.  For
319 * example,
320 * <blockquote><pre>
321 * MessageFormat mf = new MessageFormat("{0}, {0}, {0}");
322 * String forParsing = "x, y, z";
323 * Object[] objs = mf.parse(forParsing, new ParsePosition(0));
324 * // result now equals {new String("z")}
325 * </pre></blockquote>
326 *
327 * <h4><a name="synchronization">Synchronization</a></h4>
328 *
329 * <p>
330 * Message formats are not synchronized.
331 * It is recommended to create separate format instances for each thread.
332 * If multiple threads access a format concurrently, it must be synchronized
333 * externally.
334 *
335 * @see          java.util.Locale
336 * @see          Format
337 * @see          NumberFormat
338 * @see          DecimalFormat
339 * @see          DecimalFormatSymbols
340 * @see          ChoiceFormat
341 * @see          DateFormat
342 * @see          SimpleDateFormat
343 *
344 * @author       Mark Davis
345 */
346
347public class MessageFormat extends Format {
348
349    private static final long serialVersionUID = 6479157306784022952L;
350
351    /**
352     * Constructs a MessageFormat for the default locale and the
353     * specified pattern.
354     * The constructor first sets the locale, then parses the pattern and
355     * creates a list of subformats for the format elements contained in it.
356     * Patterns and their interpretation are specified in the
357     * <a href="#patterns">class description</a>.
358     *
359     * @param pattern the pattern for this message format
360     * @exception IllegalArgumentException if the pattern is invalid
361     */
362    public MessageFormat(String pattern) {
363        this.locale = Locale.getDefault(Locale.Category.FORMAT);
364        applyPattern(pattern);
365    }
366
367    /**
368     * Constructs a MessageFormat for the specified locale and
369     * pattern.
370     * The constructor first sets the locale, then parses the pattern and
371     * creates a list of subformats for the format elements contained in it.
372     * Patterns and their interpretation are specified in the
373     * <a href="#patterns">class description</a>.
374     *
375     * @param pattern the pattern for this message format
376     * @param locale the locale for this message format
377     * @exception IllegalArgumentException if the pattern is invalid
378     * @since 1.4
379     */
380    public MessageFormat(String pattern, Locale locale) {
381        this.locale = locale;
382        applyPattern(pattern);
383    }
384
385    /**
386     * Sets the locale to be used when creating or comparing subformats.
387     * This affects subsequent calls
388     * <ul>
389     * <li>to the {@link #applyPattern applyPattern}
390     *     and {@link #toPattern toPattern} methods if format elements specify
391     *     a format type and therefore have the subformats created in the
392     *     <code>applyPattern</code> method, as well as
393     * <li>to the <code>format</code> and
394     *     {@link #formatToCharacterIterator formatToCharacterIterator} methods
395     *     if format elements do not specify a format type and therefore have
396     *     the subformats created in the formatting methods.
397     * </ul>
398     * Subformats that have already been created are not affected.
399     *
400     * @param locale the locale to be used when creating or comparing subformats
401     */
402    public void setLocale(Locale locale) {
403        this.locale = locale;
404    }
405
406    /**
407     * Gets the locale that's used when creating or comparing subformats.
408     *
409     * @return the locale used when creating or comparing subformats
410     */
411    public Locale getLocale() {
412        return locale;
413    }
414
415
416    /**
417     * Sets the pattern used by this message format.
418     * The method parses the pattern and creates a list of subformats
419     * for the format elements contained in it.
420     * Patterns and their interpretation are specified in the
421     * <a href="#patterns">class description</a>.
422     *
423     * @param pattern the pattern for this message format
424     * @exception IllegalArgumentException if the pattern is invalid
425     */
426    public void applyPattern(String pattern) {
427            StringBuilder[] segments = new StringBuilder[4];
428            // Allocate only segments[SEG_RAW] here. The rest are
429            // allocated on demand.
430            segments[SEG_RAW] = new StringBuilder();
431
432            int part = SEG_RAW;
433            int formatNumber = 0;
434            boolean inQuote = false;
435            int braceStack = 0;
436            maxOffset = -1;
437            for (int i = 0; i < pattern.length(); ++i) {
438                char ch = pattern.charAt(i);
439                if (part == SEG_RAW) {
440                    if (ch == '\'') {
441                        if (i + 1 < pattern.length()
442                            && pattern.charAt(i+1) == '\'') {
443                            segments[part].append(ch);  // handle doubles
444                            ++i;
445                        } else {
446                            inQuote = !inQuote;
447                        }
448                    } else if (ch == '{' && !inQuote) {
449                        part = SEG_INDEX;
450                        if (segments[SEG_INDEX] == null) {
451                            segments[SEG_INDEX] = new StringBuilder();
452                        }
453                    } else {
454                        segments[part].append(ch);
455                    }
456                } else  {
457                    if (inQuote) {              // just copy quotes in parts
458                        segments[part].append(ch);
459                        if (ch == '\'') {
460                            inQuote = false;
461                        }
462                    } else {
463                        switch (ch) {
464                        case ',':
465                            if (part < SEG_MODIFIER) {
466                                if (segments[++part] == null) {
467                                    segments[part] = new StringBuilder();
468                                }
469                            } else {
470                                segments[part].append(ch);
471                            }
472                            break;
473                        case '{':
474                            ++braceStack;
475                            segments[part].append(ch);
476                            break;
477                        case '}':
478                            if (braceStack == 0) {
479                                part = SEG_RAW;
480                                makeFormat(i, formatNumber, segments);
481                                formatNumber++;
482                                // throw away other segments
483                                segments[SEG_INDEX] = null;
484                                segments[SEG_TYPE] = null;
485                                segments[SEG_MODIFIER] = null;
486                            } else {
487                                --braceStack;
488                                segments[part].append(ch);
489                            }
490                            break;
491                        case ' ':
492                            // Skip any leading space chars for SEG_TYPE.
493                            if (part != SEG_TYPE || segments[SEG_TYPE].length() > 0) {
494                                segments[part].append(ch);
495                            }
496                            break;
497                        case '\'':
498                            inQuote = true;
499                            // fall through, so we keep quotes in other parts
500                        default:
501                            segments[part].append(ch);
502                            break;
503                        }
504                    }
505                }
506            }
507            if (braceStack == 0 && part != 0) {
508                maxOffset = -1;
509                throw new IllegalArgumentException("Unmatched braces in the pattern.");
510            }
511            this.pattern = segments[0].toString();
512    }
513
514
515    /**
516     * Returns a pattern representing the current state of the message format.
517     * The string is constructed from internal information and therefore
518     * does not necessarily equal the previously applied pattern.
519     *
520     * @return a pattern representing the current state of the message format
521     */
522    public String toPattern() {
523        // later, make this more extensible
524        int lastOffset = 0;
525        StringBuilder result = new StringBuilder();
526        for (int i = 0; i <= maxOffset; ++i) {
527            copyAndFixQuotes(pattern, lastOffset, offsets[i], result);
528            lastOffset = offsets[i];
529            result.append('{').append(argumentNumbers[i]);
530            Format fmt = formats[i];
531            if (fmt == null) {
532                // do nothing, string format
533            } else if (fmt instanceof NumberFormat) {
534                if (fmt.equals(NumberFormat.getInstance(locale))) {
535                    result.append(",number");
536                } else if (fmt.equals(NumberFormat.getCurrencyInstance(locale))) {
537                    result.append(",number,currency");
538                } else if (fmt.equals(NumberFormat.getPercentInstance(locale))) {
539                    result.append(",number,percent");
540                } else if (fmt.equals(NumberFormat.getIntegerInstance(locale))) {
541                    result.append(",number,integer");
542                } else {
543                    if (fmt instanceof DecimalFormat) {
544                        result.append(",number,").append(((DecimalFormat)fmt).toPattern());
545                    } else if (fmt instanceof ChoiceFormat) {
546                        result.append(",choice,").append(((ChoiceFormat)fmt).toPattern());
547                    } else {
548                        // UNKNOWN
549                    }
550                }
551            } else if (fmt instanceof DateFormat) {
552                int index;
553                for (index = MODIFIER_DEFAULT; index < DATE_TIME_MODIFIERS.length; index++) {
554                    DateFormat df = DateFormat.getDateInstance(DATE_TIME_MODIFIERS[index],
555                                                               locale);
556                    if (fmt.equals(df)) {
557                        result.append(",date");
558                        break;
559                    }
560                    df = DateFormat.getTimeInstance(DATE_TIME_MODIFIERS[index],
561                                                    locale);
562                    if (fmt.equals(df)) {
563                        result.append(",time");
564                        break;
565                    }
566                }
567                if (index >= DATE_TIME_MODIFIERS.length) {
568                    if (fmt instanceof SimpleDateFormat) {
569                        result.append(",date,").append(((SimpleDateFormat)fmt).toPattern());
570                    } else {
571                        // UNKNOWN
572                    }
573                } else if (index != MODIFIER_DEFAULT) {
574                    result.append(',').append(DATE_TIME_MODIFIER_KEYWORDS[index]);
575                }
576            } else {
577                //result.append(", unknown");
578            }
579            result.append('}');
580        }
581        copyAndFixQuotes(pattern, lastOffset, pattern.length(), result);
582        return result.toString();
583    }
584
585    /**
586     * Sets the formats to use for the values passed into
587     * <code>format</code> methods or returned from <code>parse</code>
588     * methods. The indices of elements in <code>newFormats</code>
589     * correspond to the argument indices used in the previously set
590     * pattern string.
591     * The order of formats in <code>newFormats</code> thus corresponds to
592     * the order of elements in the <code>arguments</code> array passed
593     * to the <code>format</code> methods or the result array returned
594     * by the <code>parse</code> methods.
595     * <p>
596     * If an argument index is used for more than one format element
597     * in the pattern string, then the corresponding new format is used
598     * for all such format elements. If an argument index is not used
599     * for any format element in the pattern string, then the
600     * corresponding new format is ignored. If fewer formats are provided
601     * than needed, then only the formats for argument indices less
602     * than <code>newFormats.length</code> are replaced.
603     *
604     * @param newFormats the new formats to use
605     * @exception NullPointerException if <code>newFormats</code> is null
606     * @since 1.4
607     */
608    public void setFormatsByArgumentIndex(Format[] newFormats) {
609        for (int i = 0; i <= maxOffset; i++) {
610            int j = argumentNumbers[i];
611            if (j < newFormats.length) {
612                formats[i] = newFormats[j];
613            }
614        }
615    }
616
617    /**
618     * Sets the formats to use for the format elements in the
619     * previously set pattern string.
620     * The order of formats in <code>newFormats</code> corresponds to
621     * the order of format elements in the pattern string.
622     * <p>
623     * If more formats are provided than needed by the pattern string,
624     * the remaining ones are ignored. If fewer formats are provided
625     * than needed, then only the first <code>newFormats.length</code>
626     * formats are replaced.
627     * <p>
628     * Since the order of format elements in a pattern string often
629     * changes during localization, it is generally better to use the
630     * {@link #setFormatsByArgumentIndex setFormatsByArgumentIndex}
631     * method, which assumes an order of formats corresponding to the
632     * order of elements in the <code>arguments</code> array passed to
633     * the <code>format</code> methods or the result array returned by
634     * the <code>parse</code> methods.
635     *
636     * @param newFormats the new formats to use
637     * @exception NullPointerException if <code>newFormats</code> is null
638     */
639    public void setFormats(Format[] newFormats) {
640        int runsToCopy = newFormats.length;
641        if (runsToCopy > maxOffset + 1) {
642            runsToCopy = maxOffset + 1;
643        }
644        for (int i = 0; i < runsToCopy; i++) {
645            formats[i] = newFormats[i];
646        }
647    }
648
649    /**
650     * Sets the format to use for the format elements within the
651     * previously set pattern string that use the given argument
652     * index.
653     * The argument index is part of the format element definition and
654     * represents an index into the <code>arguments</code> array passed
655     * to the <code>format</code> methods or the result array returned
656     * by the <code>parse</code> methods.
657     * <p>
658     * If the argument index is used for more than one format element
659     * in the pattern string, then the new format is used for all such
660     * format elements. If the argument index is not used for any format
661     * element in the pattern string, then the new format is ignored.
662     *
663     * @param argumentIndex the argument index for which to use the new format
664     * @param newFormat the new format to use
665     * @since 1.4
666     */
667    public void setFormatByArgumentIndex(int argumentIndex, Format newFormat) {
668        for (int j = 0; j <= maxOffset; j++) {
669            if (argumentNumbers[j] == argumentIndex) {
670                formats[j] = newFormat;
671            }
672        }
673    }
674
675    /**
676     * Sets the format to use for the format element with the given
677     * format element index within the previously set pattern string.
678     * The format element index is the zero-based number of the format
679     * element counting from the start of the pattern string.
680     * <p>
681     * Since the order of format elements in a pattern string often
682     * changes during localization, it is generally better to use the
683     * {@link #setFormatByArgumentIndex setFormatByArgumentIndex}
684     * method, which accesses format elements based on the argument
685     * index they specify.
686     *
687     * @param formatElementIndex the index of a format element within the pattern
688     * @param newFormat the format to use for the specified format element
689     * @exception ArrayIndexOutOfBoundsException if {@code formatElementIndex} is equal to or
690     *            larger than the number of format elements in the pattern string
691     */
692    public void setFormat(int formatElementIndex, Format newFormat) {
693        if (formatElementIndex > maxOffset) {
694            throw new ArrayIndexOutOfBoundsException(maxOffset, formatElementIndex);
695        }
696        formats[formatElementIndex] = newFormat;
697    }
698
699    /**
700     * Gets the formats used for the values passed into
701     * <code>format</code> methods or returned from <code>parse</code>
702     * methods. The indices of elements in the returned array
703     * correspond to the argument indices used in the previously set
704     * pattern string.
705     * The order of formats in the returned array thus corresponds to
706     * the order of elements in the <code>arguments</code> array passed
707     * to the <code>format</code> methods or the result array returned
708     * by the <code>parse</code> methods.
709     * <p>
710     * If an argument index is used for more than one format element
711     * in the pattern string, then the format used for the last such
712     * format element is returned in the array. If an argument index
713     * is not used for any format element in the pattern string, then
714     * null is returned in the array.
715     *
716     * @return the formats used for the arguments within the pattern
717     * @since 1.4
718     */
719    public Format[] getFormatsByArgumentIndex() {
720        int maximumArgumentNumber = -1;
721        for (int i = 0; i <= maxOffset; i++) {
722            if (argumentNumbers[i] > maximumArgumentNumber) {
723                maximumArgumentNumber = argumentNumbers[i];
724            }
725        }
726        Format[] resultArray = new Format[maximumArgumentNumber + 1];
727        for (int i = 0; i <= maxOffset; i++) {
728            resultArray[argumentNumbers[i]] = formats[i];
729        }
730        return resultArray;
731    }
732
733    /**
734     * Gets the formats used for the format elements in the
735     * previously set pattern string.
736     * The order of formats in the returned array corresponds to
737     * the order of format elements in the pattern string.
738     * <p>
739     * Since the order of format elements in a pattern string often
740     * changes during localization, it's generally better to use the
741     * {@link #getFormatsByArgumentIndex getFormatsByArgumentIndex}
742     * method, which assumes an order of formats corresponding to the
743     * order of elements in the <code>arguments</code> array passed to
744     * the <code>format</code> methods or the result array returned by
745     * the <code>parse</code> methods.
746     *
747     * @return the formats used for the format elements in the pattern
748     */
749    public Format[] getFormats() {
750        Format[] resultArray = new Format[maxOffset + 1];
751        System.arraycopy(formats, 0, resultArray, 0, maxOffset + 1);
752        return resultArray;
753    }
754
755    /**
756     * Formats an array of objects and appends the <code>MessageFormat</code>'s
757     * pattern, with format elements replaced by the formatted objects, to the
758     * provided <code>StringBuffer</code>.
759     * <p>
760     * The text substituted for the individual format elements is derived from
761     * the current subformat of the format element and the
762     * <code>arguments</code> element at the format element's argument index
763     * as indicated by the first matching line of the following table. An
764     * argument is <i>unavailable</i> if <code>arguments</code> is
765     * <code>null</code> or has fewer than argumentIndex+1 elements.
766     * <p>
767     * <table border=1 summary="Examples of subformat,argument,and formatted text">
768     *    <tr>
769     *       <th>Subformat
770     *       <th>Argument
771     *       <th>Formatted Text
772     *    <tr>
773     *       <td><i>any</i>
774     *       <td><i>unavailable</i>
775     *       <td><code>"{" + argumentIndex + "}"</code>
776     *    <tr>
777     *       <td><i>any</i>
778     *       <td><code>null</code>
779     *       <td><code>"null"</code>
780     *    <tr>
781     *       <td><code>instanceof ChoiceFormat</code>
782     *       <td><i>any</i>
783     *       <td><code>subformat.format(argument).indexOf('{') >= 0 ?<br>
784     *           (new MessageFormat(subformat.format(argument), getLocale())).format(argument) :
785     *           subformat.format(argument)</code>
786     *    <tr>
787     *       <td><code>!= null</code>
788     *       <td><i>any</i>
789     *       <td><code>subformat.format(argument)</code>
790     *    <tr>
791     *       <td><code>null</code>
792     *       <td><code>instanceof Number</code>
793     *       <td><code>NumberFormat.getInstance(getLocale()).format(argument)</code>
794     *    <tr>
795     *       <td><code>null</code>
796     *       <td><code>instanceof Date</code>
797     *       <td><code>DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, getLocale()).format(argument)</code>
798     *    <tr>
799     *       <td><code>null</code>
800     *       <td><code>instanceof String</code>
801     *       <td><code>argument</code>
802     *    <tr>
803     *       <td><code>null</code>
804     *       <td><i>any</i>
805     *       <td><code>argument.toString()</code>
806     * </table>
807     * <p>
808     * If <code>pos</code> is non-null, and refers to
809     * <code>Field.ARGUMENT</code>, the location of the first formatted
810     * string will be returned.
811     *
812     * @param arguments an array of objects to be formatted and substituted.
813     * @param result where text is appended.
814     * @param pos On input: an alignment field, if desired.
815     *            On output: the offsets of the alignment field.
816     * @exception IllegalArgumentException if an argument in the
817     *            <code>arguments</code> array is not of the type
818     *            expected by the format element(s) that use it.
819     */
820    public final StringBuffer format(Object[] arguments, StringBuffer result,
821                                     FieldPosition pos)
822    {
823        return subformat(arguments, result, pos, null);
824    }
825
826    /**
827     * Creates a MessageFormat with the given pattern and uses it
828     * to format the given arguments. This is equivalent to
829     * <blockquote>
830     *     <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>
831     * </blockquote>
832     *
833     * @exception IllegalArgumentException if the pattern is invalid,
834     *            or if an argument in the <code>arguments</code> array
835     *            is not of the type expected by the format element(s)
836     *            that use it.
837     */
838    public static String format(String pattern, Object ... arguments) {
839        MessageFormat temp = new MessageFormat(pattern);
840        return temp.format(arguments);
841    }
842
843    // Overrides
844    /**
845     * Formats an array of objects and appends the <code>MessageFormat</code>'s
846     * pattern, with format elements replaced by the formatted objects, to the
847     * provided <code>StringBuffer</code>.
848     * This is equivalent to
849     * <blockquote>
850     *     <code>{@link #format(java.lang.Object[], java.lang.StringBuffer, java.text.FieldPosition) format}((Object[]) arguments, result, pos)</code>
851     * </blockquote>
852     *
853     * @param arguments an array of objects to be formatted and substituted.
854     * @param result where text is appended.
855     * @param pos On input: an alignment field, if desired.
856     *            On output: the offsets of the alignment field.
857     * @exception IllegalArgumentException if an argument in the
858     *            <code>arguments</code> array is not of the type
859     *            expected by the format element(s) that use it.
860     */
861    public final StringBuffer format(Object arguments, StringBuffer result,
862                                     FieldPosition pos)
863    {
864        return subformat((Object[]) arguments, result, pos, null);
865    }
866
867    /**
868     * Formats an array of objects and inserts them into the
869     * <code>MessageFormat</code>'s pattern, producing an
870     * <code>AttributedCharacterIterator</code>.
871     * You can use the returned <code>AttributedCharacterIterator</code>
872     * to build the resulting String, as well as to determine information
873     * about the resulting String.
874     * <p>
875     * The text of the returned <code>AttributedCharacterIterator</code> is
876     * the same that would be returned by
877     * <blockquote>
878     *     <code>{@link #format(java.lang.Object[], java.lang.StringBuffer, java.text.FieldPosition) format}(arguments, new StringBuffer(), null).toString()</code>
879     * </blockquote>
880     * <p>
881     * In addition, the <code>AttributedCharacterIterator</code> contains at
882     * least attributes indicating where text was generated from an
883     * argument in the <code>arguments</code> array. The keys of these attributes are of
884     * type <code>MessageFormat.Field</code>, their values are
885     * <code>Integer</code> objects indicating the index in the <code>arguments</code>
886     * array of the argument from which the text was generated.
887     * <p>
888     * The attributes/value from the underlying <code>Format</code>
889     * instances that <code>MessageFormat</code> uses will also be
890     * placed in the resulting <code>AttributedCharacterIterator</code>.
891     * This allows you to not only find where an argument is placed in the
892     * resulting String, but also which fields it contains in turn.
893     *
894     * @param arguments an array of objects to be formatted and substituted.
895     * @return AttributedCharacterIterator describing the formatted value.
896     * @exception NullPointerException if <code>arguments</code> is null.
897     * @exception IllegalArgumentException if an argument in the
898     *            <code>arguments</code> array is not of the type
899     *            expected by the format element(s) that use it.
900     * @since 1.4
901     */
902    public AttributedCharacterIterator formatToCharacterIterator(Object arguments) {
903        StringBuffer result = new StringBuffer();
904        ArrayList iterators = new ArrayList();
905
906        if (arguments == null) {
907            throw new NullPointerException(
908                   "formatToCharacterIterator must be passed non-null object");
909        }
910        subformat((Object[]) arguments, result, null, iterators);
911        if (iterators.size() == 0) {
912            return createAttributedCharacterIterator("");
913        }
914        return createAttributedCharacterIterator(
915                     (AttributedCharacterIterator[])iterators.toArray(
916                     new AttributedCharacterIterator[iterators.size()]));
917    }
918
919    /**
920     * Parses the string.
921     *
922     * <p>Caveats: The parse may fail in a number of circumstances.
923     * For example:
924     * <ul>
925     * <li>If one of the arguments does not occur in the pattern.
926     * <li>If the format of an argument loses information, such as
927     *     with a choice format where a large number formats to "many".
928     * <li>Does not yet handle recursion (where
929     *     the substituted strings contain {n} references.)
930     * <li>Will not always find a match (or the correct match)
931     *     if some part of the parse is ambiguous.
932     *     For example, if the pattern "{1},{2}" is used with the
933     *     string arguments {"a,b", "c"}, it will format as "a,b,c".
934     *     When the result is parsed, it will return {"a", "b,c"}.
935     * <li>If a single argument is parsed more than once in the string,
936     *     then the later parse wins.
937     * </ul>
938     * When the parse fails, use ParsePosition.getErrorIndex() to find out
939     * where in the string the parsing failed.  The returned error
940     * index is the starting offset of the sub-patterns that the string
941     * is comparing with.  For example, if the parsing string "AAA {0} BBB"
942     * is comparing against the pattern "AAD {0} BBB", the error index is
943     * 0. When an error occurs, the call to this method will return null.
944     * If the source is null, return an empty array.
945     */
946    public Object[] parse(String source, ParsePosition pos) {
947        if (source == null) {
948            Object[] empty = {};
949            return empty;
950        }
951
952        int maximumArgumentNumber = -1;
953        for (int i = 0; i <= maxOffset; i++) {
954            if (argumentNumbers[i] > maximumArgumentNumber) {
955                maximumArgumentNumber = argumentNumbers[i];
956            }
957        }
958        Object[] resultArray = new Object[maximumArgumentNumber + 1];
959
960        int patternOffset = 0;
961        int sourceOffset = pos.index;
962        ParsePosition tempStatus = new ParsePosition(0);
963        for (int i = 0; i <= maxOffset; ++i) {
964            // match up to format
965            int len = offsets[i] - patternOffset;
966            if (len == 0 || pattern.regionMatches(patternOffset,
967                                                  source, sourceOffset, len)) {
968                sourceOffset += len;
969                patternOffset += len;
970            } else {
971                pos.errorIndex = sourceOffset;
972                return null; // leave index as is to signal error
973            }
974
975            // now use format
976            if (formats[i] == null) {   // string format
977                // if at end, use longest possible match
978                // otherwise uses first match to intervening string
979                // does NOT recursively try all possibilities
980                int tempLength = (i != maxOffset) ? offsets[i+1] : pattern.length();
981
982                int next;
983                if (patternOffset >= tempLength) {
984                    next = source.length();
985                }else{
986                    next = source.indexOf(pattern.substring(patternOffset, tempLength),
987                                          sourceOffset);
988                }
989
990                if (next < 0) {
991                    pos.errorIndex = sourceOffset;
992                    return null; // leave index as is to signal error
993                } else {
994                    String strValue= source.substring(sourceOffset,next);
995                    if (!strValue.equals("{"+argumentNumbers[i]+"}"))
996                        resultArray[argumentNumbers[i]]
997                            = source.substring(sourceOffset,next);
998                    sourceOffset = next;
999                }
1000            } else {
1001                tempStatus.index = sourceOffset;
1002                resultArray[argumentNumbers[i]]
1003                    = formats[i].parseObject(source,tempStatus);
1004                if (tempStatus.index == sourceOffset) {
1005                    pos.errorIndex = sourceOffset;
1006                    return null; // leave index as is to signal error
1007                }
1008                sourceOffset = tempStatus.index; // update
1009            }
1010        }
1011        int len = pattern.length() - patternOffset;
1012        if (len == 0 || pattern.regionMatches(patternOffset,
1013                                              source, sourceOffset, len)) {
1014            pos.index = sourceOffset + len;
1015        } else {
1016            pos.errorIndex = sourceOffset;
1017            return null; // leave index as is to signal error
1018        }
1019        return resultArray;
1020    }
1021
1022    /**
1023     * Parses text from the beginning of the given string to produce an object
1024     * array.
1025     * The method may not use the entire text of the given string.
1026     * <p>
1027     * See the {@link #parse(String, ParsePosition)} method for more information
1028     * on message parsing.
1029     *
1030     * @param source A <code>String</code> whose beginning should be parsed.
1031     * @return An <code>Object</code> array parsed from the string.
1032     * @exception ParseException if the beginning of the specified string
1033     *            cannot be parsed.
1034     */
1035    public Object[] parse(String source) throws ParseException {
1036        ParsePosition pos  = new ParsePosition(0);
1037        Object[] result = parse(source, pos);
1038        if (pos.index == 0)  // unchanged, returned object is null
1039            throw new ParseException("MessageFormat parse error!", pos.errorIndex);
1040
1041        return result;
1042    }
1043
1044    /**
1045     * Parses text from a string to produce an object array.
1046     * <p>
1047     * The method attempts to parse text starting at the index given by
1048     * <code>pos</code>.
1049     * If parsing succeeds, then the index of <code>pos</code> is updated
1050     * to the index after the last character used (parsing does not necessarily
1051     * use all characters up to the end of the string), and the parsed
1052     * object array is returned. The updated <code>pos</code> can be used to
1053     * indicate the starting point for the next call to this method.
1054     * If an error occurs, then the index of <code>pos</code> is not
1055     * changed, the error index of <code>pos</code> is set to the index of
1056     * the character where the error occurred, and null is returned.
1057     * <p>
1058     * See the {@link #parse(String, ParsePosition)} method for more information
1059     * on message parsing.
1060     *
1061     * @param source A <code>String</code>, part of which should be parsed.
1062     * @param pos A <code>ParsePosition</code> object with index and error
1063     *            index information as described above.
1064     * @return An <code>Object</code> array parsed from the string. In case of
1065     *         error, returns null.
1066     * @exception NullPointerException if <code>pos</code> is null.
1067     */
1068    public Object parseObject(String source, ParsePosition pos) {
1069        return parse(source, pos);
1070    }
1071
1072    /**
1073     * Creates and returns a copy of this object.
1074     *
1075     * @return a clone of this instance.
1076     */
1077    public Object clone() {
1078        MessageFormat other = (MessageFormat) super.clone();
1079
1080        // clone arrays. Can't do with utility because of bug in Cloneable
1081        other.formats = (Format[]) formats.clone(); // shallow clone
1082        for (int i = 0; i < formats.length; ++i) {
1083            if (formats[i] != null)
1084                other.formats[i] = (Format)formats[i].clone();
1085        }
1086        // for primitives or immutables, shallow clone is enough
1087        other.offsets = (int[]) offsets.clone();
1088        other.argumentNumbers = (int[]) argumentNumbers.clone();
1089
1090        return other;
1091    }
1092
1093    /**
1094     * Equality comparison between two message format objects
1095     */
1096    public boolean equals(Object obj) {
1097        if (this == obj)                      // quick check
1098            return true;
1099        if (obj == null || getClass() != obj.getClass())
1100            return false;
1101        MessageFormat other = (MessageFormat) obj;
1102        return (maxOffset == other.maxOffset
1103                && pattern.equals(other.pattern)
1104                && ((locale != null && locale.equals(other.locale))
1105                 || (locale == null && other.locale == null))
1106                && Arrays.equals(offsets,other.offsets)
1107                && Arrays.equals(argumentNumbers,other.argumentNumbers)
1108                && Arrays.equals(formats,other.formats));
1109    }
1110
1111    /**
1112     * Generates a hash code for the message format object.
1113     */
1114    public int hashCode() {
1115        return pattern.hashCode(); // enough for reasonable distribution
1116    }
1117
1118
1119    /**
1120     * Defines constants that are used as attribute keys in the
1121     * <code>AttributedCharacterIterator</code> returned
1122     * from <code>MessageFormat.formatToCharacterIterator</code>.
1123     *
1124     * @since 1.4
1125     */
1126    public static class Field extends Format.Field {
1127
1128        // Proclaim serial compatibility with 1.4 FCS
1129        private static final long serialVersionUID = 7899943957617360810L;
1130
1131        /**
1132         * Creates a Field with the specified name.
1133         *
1134         * @param name Name of the attribute
1135         */
1136        protected Field(String name) {
1137            super(name);
1138        }
1139
1140        /**
1141         * Resolves instances being deserialized to the predefined constants.
1142         *
1143         * @throws InvalidObjectException if the constant could not be
1144         *         resolved.
1145         * @return resolved MessageFormat.Field constant
1146         */
1147        protected Object readResolve() throws InvalidObjectException {
1148            if (this.getClass() != MessageFormat.Field.class) {
1149                throw new InvalidObjectException("subclass didn't correctly implement readResolve");
1150            }
1151
1152            return ARGUMENT;
1153        }
1154
1155        //
1156        // The constants
1157        //
1158
1159        /**
1160         * Constant identifying a portion of a message that was generated
1161         * from an argument passed into <code>formatToCharacterIterator</code>.
1162         * The value associated with the key will be an <code>Integer</code>
1163         * indicating the index in the <code>arguments</code> array of the
1164         * argument from which the text was generated.
1165         */
1166        public final static Field ARGUMENT =
1167                           new Field("message argument field");
1168    }
1169
1170    // ===========================privates============================
1171
1172    /**
1173     * The locale to use for formatting numbers and dates.
1174     * @serial
1175     */
1176    private Locale locale;
1177
1178    /**
1179     * The string that the formatted values are to be plugged into.  In other words, this
1180     * is the pattern supplied on construction with all of the {} expressions taken out.
1181     * @serial
1182     */
1183    private String pattern = "";
1184
1185    /** The initially expected number of subformats in the format */
1186    private static final int INITIAL_FORMATS = 10;
1187
1188    /**
1189     * An array of formatters, which are used to format the arguments.
1190     * @serial
1191     */
1192    private Format[] formats = new Format[INITIAL_FORMATS];
1193
1194    /**
1195     * The positions where the results of formatting each argument are to be inserted
1196     * into the pattern.
1197     * @serial
1198     */
1199    private int[] offsets = new int[INITIAL_FORMATS];
1200
1201    /**
1202     * The argument numbers corresponding to each formatter.  (The formatters are stored
1203     * in the order they occur in the pattern, not in the order in which the arguments
1204     * are specified.)
1205     * @serial
1206     */
1207    private int[] argumentNumbers = new int[INITIAL_FORMATS];
1208
1209    /**
1210     * One less than the number of entries in <code>offsets</code>.  Can also be thought of
1211     * as the index of the highest-numbered element in <code>offsets</code> that is being used.
1212     * All of these arrays should have the same number of elements being used as <code>offsets</code>
1213     * does, and so this variable suffices to tell us how many entries are in all of them.
1214     * @serial
1215     */
1216    private int maxOffset = -1;
1217
1218    /**
1219     * Internal routine used by format. If <code>characterIterators</code> is
1220     * non-null, AttributedCharacterIterator will be created from the
1221     * subformats as necessary. If <code>characterIterators</code> is null
1222     * and <code>fp</code> is non-null and identifies
1223     * <code>Field.MESSAGE_ARGUMENT</code>, the location of
1224     * the first replaced argument will be set in it.
1225     *
1226     * @exception IllegalArgumentException if an argument in the
1227     *            <code>arguments</code> array is not of the type
1228     *            expected by the format element(s) that use it.
1229     */
1230    private StringBuffer subformat(Object[] arguments, StringBuffer result,
1231                                   FieldPosition fp, List characterIterators) {
1232        // note: this implementation assumes a fast substring & index.
1233        // if this is not true, would be better to append chars one by one.
1234        int lastOffset = 0;
1235        int last = result.length();
1236        for (int i = 0; i <= maxOffset; ++i) {
1237            result.append(pattern.substring(lastOffset, offsets[i]));
1238            lastOffset = offsets[i];
1239            int argumentNumber = argumentNumbers[i];
1240            if (arguments == null || argumentNumber >= arguments.length) {
1241                result.append('{').append(argumentNumber).append('}');
1242                continue;
1243            }
1244            // int argRecursion = ((recursionProtection >> (argumentNumber*2)) & 0x3);
1245            if (false) { // if (argRecursion == 3){
1246                // prevent loop!!!
1247                result.append('\uFFFD');
1248            } else {
1249                Object obj = arguments[argumentNumber];
1250                String arg = null;
1251                Format subFormatter = null;
1252                if (obj == null) {
1253                    arg = "null";
1254                } else if (formats[i] != null) {
1255                    subFormatter = formats[i];
1256                    if (subFormatter instanceof ChoiceFormat) {
1257                        arg = formats[i].format(obj);
1258                        if (arg.indexOf('{') >= 0) {
1259                            subFormatter = new MessageFormat(arg, locale);
1260                            obj = arguments;
1261                            arg = null;
1262                        }
1263                    }
1264                } else if (obj instanceof Number) {
1265                    // format number if can
1266                    subFormatter = NumberFormat.getInstance(locale);
1267                } else if (obj instanceof Date) {
1268                    // format a Date if can
1269                    subFormatter = DateFormat.getDateTimeInstance(
1270                             DateFormat.SHORT, DateFormat.SHORT, locale);//fix
1271                } else if (obj instanceof String) {
1272                    arg = (String) obj;
1273
1274                } else {
1275                    arg = obj.toString();
1276                    if (arg == null) arg = "null";
1277                }
1278
1279                // At this point we are in two states, either subFormatter
1280                // is non-null indicating we should format obj using it,
1281                // or arg is non-null and we should use it as the value.
1282
1283                if (characterIterators != null) {
1284                    // If characterIterators is non-null, it indicates we need
1285                    // to get the CharacterIterator from the child formatter.
1286                    if (last != result.length()) {
1287                        characterIterators.add(
1288                            createAttributedCharacterIterator(result.substring
1289                                                              (last)));
1290                        last = result.length();
1291                    }
1292                    if (subFormatter != null) {
1293                        AttributedCharacterIterator subIterator =
1294                                   subFormatter.formatToCharacterIterator(obj);
1295
1296                        append(result, subIterator);
1297                        if (last != result.length()) {
1298                            characterIterators.add(
1299                                         createAttributedCharacterIterator(
1300                                         subIterator, Field.ARGUMENT,
1301                                         Integer.valueOf(argumentNumber)));
1302                            last = result.length();
1303                        }
1304                        arg = null;
1305                    }
1306                    if (arg != null && arg.length() > 0) {
1307                        result.append(arg);
1308                        characterIterators.add(
1309                                 createAttributedCharacterIterator(
1310                                 arg, Field.ARGUMENT,
1311                                 Integer.valueOf(argumentNumber)));
1312                        last = result.length();
1313                    }
1314                }
1315                else {
1316                    if (subFormatter != null) {
1317                        arg = subFormatter.format(obj);
1318                    }
1319                    last = result.length();
1320                    result.append(arg);
1321                    if (i == 0 && fp != null && Field.ARGUMENT.equals(
1322                                  fp.getFieldAttribute())) {
1323                        fp.setBeginIndex(last);
1324                        fp.setEndIndex(result.length());
1325                    }
1326                    last = result.length();
1327                }
1328            }
1329        }
1330        result.append(pattern.substring(lastOffset, pattern.length()));
1331        if (characterIterators != null && last != result.length()) {
1332            characterIterators.add(createAttributedCharacterIterator(
1333                                   result.substring(last)));
1334        }
1335        return result;
1336    }
1337
1338    /**
1339     * Convenience method to append all the characters in
1340     * <code>iterator</code> to the StringBuffer <code>result</code>.
1341     */
1342    private void append(StringBuffer result, CharacterIterator iterator) {
1343        if (iterator.first() != CharacterIterator.DONE) {
1344            char aChar;
1345
1346            result.append(iterator.first());
1347            while ((aChar = iterator.next()) != CharacterIterator.DONE) {
1348                result.append(aChar);
1349            }
1350        }
1351    }
1352
1353    // Indices for segments
1354    private static final int SEG_RAW      = 0;
1355    private static final int SEG_INDEX    = 1;
1356    private static final int SEG_TYPE     = 2;
1357    private static final int SEG_MODIFIER = 3; // modifier or subformat
1358
1359    // Indices for type keywords
1360    private static final int TYPE_NULL    = 0;
1361    private static final int TYPE_NUMBER  = 1;
1362    private static final int TYPE_DATE    = 2;
1363    private static final int TYPE_TIME    = 3;
1364    private static final int TYPE_CHOICE  = 4;
1365
1366    private static final String[] TYPE_KEYWORDS = {
1367        "",
1368        "number",
1369        "date",
1370        "time",
1371        "choice"
1372    };
1373
1374    // Indices for number modifiers
1375    private static final int MODIFIER_DEFAULT  = 0; // common in number and date-time
1376    private static final int MODIFIER_CURRENCY = 1;
1377    private static final int MODIFIER_PERCENT  = 2;
1378    private static final int MODIFIER_INTEGER  = 3;
1379
1380    private static final String[] NUMBER_MODIFIER_KEYWORDS = {
1381        "",
1382        "currency",
1383        "percent",
1384        "integer"
1385    };
1386
1387    // Indices for date-time modifiers
1388    private static final int MODIFIER_SHORT   = 1;
1389    private static final int MODIFIER_MEDIUM  = 2;
1390    private static final int MODIFIER_LONG    = 3;
1391    private static final int MODIFIER_FULL    = 4;
1392
1393    private static final String[] DATE_TIME_MODIFIER_KEYWORDS = {
1394        "",
1395        "short",
1396        "medium",
1397        "long",
1398        "full"
1399    };
1400
1401    // Date-time style values corresponding to the date-time modifiers.
1402    private static final int[] DATE_TIME_MODIFIERS = {
1403        DateFormat.DEFAULT,
1404        DateFormat.SHORT,
1405        DateFormat.MEDIUM,
1406        DateFormat.LONG,
1407        DateFormat.FULL,
1408    };
1409
1410    private void makeFormat(int position, int offsetNumber,
1411                            StringBuilder[] textSegments)
1412    {
1413        String[] segments = new String[textSegments.length];
1414        for (int i = 0; i < textSegments.length; i++) {
1415            StringBuilder oneseg = textSegments[i];
1416            segments[i] = (oneseg != null) ? oneseg.toString() : "";
1417        }
1418
1419        // get the argument number
1420        int argumentNumber;
1421        try {
1422            argumentNumber = Integer.parseInt(segments[SEG_INDEX]); // always unlocalized!
1423        } catch (NumberFormatException e) {
1424            throw new IllegalArgumentException("can't parse argument number: "
1425                                               + segments[SEG_INDEX], e);
1426        }
1427        if (argumentNumber < 0) {
1428            throw new IllegalArgumentException("negative argument number: "
1429                                               + argumentNumber);
1430        }
1431
1432        // resize format information arrays if necessary
1433        if (offsetNumber >= formats.length) {
1434            int newLength = formats.length * 2;
1435            Format[] newFormats = new Format[newLength];
1436            int[] newOffsets = new int[newLength];
1437            int[] newArgumentNumbers = new int[newLength];
1438            System.arraycopy(formats, 0, newFormats, 0, maxOffset + 1);
1439            System.arraycopy(offsets, 0, newOffsets, 0, maxOffset + 1);
1440            System.arraycopy(argumentNumbers, 0, newArgumentNumbers, 0, maxOffset + 1);
1441            formats = newFormats;
1442            offsets = newOffsets;
1443            argumentNumbers = newArgumentNumbers;
1444        }
1445        int oldMaxOffset = maxOffset;
1446        maxOffset = offsetNumber;
1447        offsets[offsetNumber] = segments[SEG_RAW].length();
1448        argumentNumbers[offsetNumber] = argumentNumber;
1449
1450        // now get the format
1451        Format newFormat = null;
1452        if (segments[SEG_TYPE].length() != 0) {
1453            int type = findKeyword(segments[SEG_TYPE], TYPE_KEYWORDS);
1454            switch (type) {
1455            case TYPE_NULL:
1456                // Type "" is allowed. e.g., "{0,}", "{0,,}", and "{0,,#}"
1457                // are treated as "{0}".
1458                break;
1459
1460            case TYPE_NUMBER:
1461                switch (findKeyword(segments[SEG_MODIFIER], NUMBER_MODIFIER_KEYWORDS)) {
1462                case MODIFIER_DEFAULT:
1463                    newFormat = NumberFormat.getInstance(locale);
1464                    break;
1465                case MODIFIER_CURRENCY:
1466                    newFormat = NumberFormat.getCurrencyInstance(locale);
1467                    break;
1468                case MODIFIER_PERCENT:
1469                    newFormat = NumberFormat.getPercentInstance(locale);
1470                    break;
1471                case MODIFIER_INTEGER:
1472                    newFormat = NumberFormat.getIntegerInstance(locale);
1473                    break;
1474                default: // DecimalFormat pattern
1475                    try {
1476                        newFormat = new DecimalFormat(segments[SEG_MODIFIER],
1477                                                      DecimalFormatSymbols.getInstance(locale));
1478                    } catch (IllegalArgumentException e) {
1479                        maxOffset = oldMaxOffset;
1480                        throw e;
1481                    }
1482                    break;
1483                }
1484                break;
1485
1486            case TYPE_DATE:
1487            case TYPE_TIME:
1488                int mod = findKeyword(segments[SEG_MODIFIER], DATE_TIME_MODIFIER_KEYWORDS);
1489                if (mod >= 0 && mod < DATE_TIME_MODIFIER_KEYWORDS.length) {
1490                    if (type == TYPE_DATE) {
1491                        newFormat = DateFormat.getDateInstance(DATE_TIME_MODIFIERS[mod],
1492                                                               locale);
1493                    } else {
1494                        newFormat = DateFormat.getTimeInstance(DATE_TIME_MODIFIERS[mod],
1495                                                               locale);
1496                    }
1497                } else {
1498                    // SimpleDateFormat pattern
1499                    try {
1500                        newFormat = new SimpleDateFormat(segments[SEG_MODIFIER], locale);
1501                    } catch (IllegalArgumentException e) {
1502                        maxOffset = oldMaxOffset;
1503                        throw e;
1504                    }
1505                }
1506                break;
1507
1508            case TYPE_CHOICE:
1509                try {
1510                    // ChoiceFormat pattern
1511                    newFormat = new ChoiceFormat(segments[SEG_MODIFIER]);
1512                } catch (Exception e) {
1513                    maxOffset = oldMaxOffset;
1514                    throw new IllegalArgumentException("Choice Pattern incorrect: "
1515                                                       + segments[SEG_MODIFIER], e);
1516                }
1517                break;
1518
1519            default:
1520                maxOffset = oldMaxOffset;
1521                throw new IllegalArgumentException("unknown format type: " +
1522                                                   segments[SEG_TYPE]);
1523            }
1524        }
1525        formats[offsetNumber] = newFormat;
1526    }
1527
1528    private static final int findKeyword(String s, String[] list) {
1529        for (int i = 0; i < list.length; ++i) {
1530            if (s.equals(list[i]))
1531                return i;
1532        }
1533
1534        // Try trimmed lowercase.
1535        String ls = s.trim().toLowerCase(Locale.ROOT);
1536        if (ls != s) {
1537            for (int i = 0; i < list.length; ++i) {
1538                if (ls.equals(list[i]))
1539                    return i;
1540            }
1541        }
1542        return -1;
1543    }
1544
1545    private static final void copyAndFixQuotes(String source, int start, int end,
1546                                               StringBuilder target) {
1547        boolean quoted = false;
1548
1549        for (int i = start; i < end; ++i) {
1550            char ch = source.charAt(i);
1551            if (ch == '{') {
1552                if (!quoted) {
1553                    target.append('\'');
1554                    quoted = true;
1555                }
1556                target.append(ch);
1557            } else if (ch == '\'') {
1558                target.append("''");
1559            } else {
1560                if (quoted) {
1561                    target.append('\'');
1562                    quoted = false;
1563                }
1564                target.append(ch);
1565            }
1566        }
1567        if (quoted) {
1568            target.append('\'');
1569        }
1570    }
1571
1572    /**
1573     * After reading an object from the input stream, do a simple verification
1574     * to maintain class invariants.
1575     * @throws InvalidObjectException if the objects read from the stream is invalid.
1576     */
1577    private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
1578        in.defaultReadObject();
1579        boolean isValid = maxOffset >= -1
1580                && formats.length > maxOffset
1581                && offsets.length > maxOffset
1582                && argumentNumbers.length > maxOffset;
1583        if (isValid) {
1584            int lastOffset = pattern.length() + 1;
1585            for (int i = maxOffset; i >= 0; --i) {
1586                if ((offsets[i] < 0) || (offsets[i] > lastOffset)) {
1587                    isValid = false;
1588                    break;
1589                } else {
1590                    lastOffset = offsets[i];
1591                }
1592            }
1593        }
1594        if (!isValid) {
1595            throw new InvalidObjectException("Could not reconstruct MessageFormat from corrupt stream.");
1596        }
1597    }
1598}
1599