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