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 
  39 package java.text;
  40 
  41 import java.io.InvalidObjectException;
  42 import java.io.IOException;
  43 import java.io.ObjectInputStream;
  44 import java.text.DecimalFormat;
  45 import java.util.ArrayList;
  46 import java.util.Arrays;
  47 import java.util.Date;
  48 import java.util.List;
  49 import 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 
 344 public 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      * @throws NullPointerException if {@code source} is null.
1073      */
1074     public Object parseObject(String source, ParsePosition pos) {
1075         return parse(source, pos);
1076     }
1077 
1078     /**
1079      * Creates and returns a copy of this object.
1080      *
1081      * @return a clone of this instance.
1082      */
1083     public Object clone() {
1084         MessageFormat other = (MessageFormat) super.clone();
1085 
1086         // clone arrays. Can't do with utility because of bug in Cloneable
1087         other.formats = formats.clone(); // shallow clone
1088         for (int i = 0; i < formats.length; ++i) {
1089             if (formats[i] != null)
1090                 other.formats[i] = (Format)formats[i].clone();
1091         }
1092         // for primitives or immutables, shallow clone is enough
1093         other.offsets = offsets.clone();
1094         other.argumentNumbers = argumentNumbers.clone();
1095 
1096         return other;
1097     }
1098 
1099     /**
1100      * Equality comparison between two message format objects
1101      */
1102     public boolean equals(Object obj) {
1103         if (this == obj)                      // quick check
1104             return true;
1105         if (obj == null || getClass() != obj.getClass())
1106             return false;
1107         MessageFormat other = (MessageFormat) obj;
1108         return (maxOffset == other.maxOffset
1109                 && pattern.equals(other.pattern)
1110                 && ((locale != null && locale.equals(other.locale))
1111                  || (locale == null && other.locale == null))
1112                 && Arrays.equals(offsets,other.offsets)
1113                 && Arrays.equals(argumentNumbers,other.argumentNumbers)
1114                 && Arrays.equals(formats,other.formats));
1115     }
1116 
1117     /**
1118      * Generates a hash code for the message format object.
1119      */
1120     public int hashCode() {
1121         return pattern.hashCode(); // enough for reasonable distribution
1122     }
1123 
1124 
1125     /**
1126      * Defines constants that are used as attribute keys in the
1127      * <code>AttributedCharacterIterator</code> returned
1128      * from <code>MessageFormat.formatToCharacterIterator</code>.
1129      *
1130      * @since 1.4
1131      */
1132     public static class Field extends Format.Field {
1133 
1134         // Proclaim serial compatibility with 1.4 FCS
1135         private static final long serialVersionUID = 7899943957617360810L;
1136 
1137         /**
1138          * Creates a Field with the specified name.
1139          *
1140          * @param name Name of the attribute
1141          */
1142         protected Field(String name) {
1143             super(name);
1144         }
1145 
1146         /**
1147          * Resolves instances being deserialized to the predefined constants.
1148          *
1149          * @throws InvalidObjectException if the constant could not be
1150          *         resolved.
1151          * @return resolved MessageFormat.Field constant
1152          */
1153         protected Object readResolve() throws InvalidObjectException {
1154             if (this.getClass() != MessageFormat.Field.class) {
1155                 throw new InvalidObjectException("subclass didn't correctly implement readResolve");
1156             }
1157 
1158             return ARGUMENT;
1159         }
1160 
1161         //
1162         // The constants
1163         //
1164 
1165         /**
1166          * Constant identifying a portion of a message that was generated
1167          * from an argument passed into <code>formatToCharacterIterator</code>.
1168          * The value associated with the key will be an <code>Integer</code>
1169          * indicating the index in the <code>arguments</code> array of the
1170          * argument from which the text was generated.
1171          */
1172         public static final Field ARGUMENT =
1173                            new Field("message argument field");
1174     }
1175 
1176     // ===========================privates============================
1177 
1178     /**
1179      * The locale to use for formatting numbers and dates.
1180      * @serial
1181      */
1182     private Locale locale;
1183 
1184     /**
1185      * The string that the formatted values are to be plugged into.  In other words, this
1186      * is the pattern supplied on construction with all of the {} expressions taken out.
1187      * @serial
1188      */
1189     private String pattern = "";
1190 
1191     /** The initially expected number of subformats in the format */
1192     private static final int INITIAL_FORMATS = 10;
1193 
1194     /**
1195      * An array of formatters, which are used to format the arguments.
1196      * @serial
1197      */
1198     private Format[] formats = new Format[INITIAL_FORMATS];
1199 
1200     /**
1201      * The positions where the results of formatting each argument are to be inserted
1202      * into the pattern.
1203      * @serial
1204      */
1205     private int[] offsets = new int[INITIAL_FORMATS];
1206 
1207     /**
1208      * The argument numbers corresponding to each formatter.  (The formatters are stored
1209      * in the order they occur in the pattern, not in the order in which the arguments
1210      * are specified.)
1211      * @serial
1212      */
1213     private int[] argumentNumbers = new int[INITIAL_FORMATS];
1214 
1215     /**
1216      * One less than the number of entries in <code>offsets</code>.  Can also be thought of
1217      * as the index of the highest-numbered element in <code>offsets</code> that is being used.
1218      * All of these arrays should have the same number of elements being used as <code>offsets</code>
1219      * does, and so this variable suffices to tell us how many entries are in all of them.
1220      * @serial
1221      */
1222     private int maxOffset = -1;
1223 
1224     /**
1225      * Internal routine used by format. If <code>characterIterators</code> is
1226      * non-null, AttributedCharacterIterator will be created from the
1227      * subformats as necessary. If <code>characterIterators</code> is null
1228      * and <code>fp</code> is non-null and identifies
1229      * <code>Field.MESSAGE_ARGUMENT</code>, the location of
1230      * the first replaced argument will be set in it.
1231      *
1232      * @exception IllegalArgumentException if an argument in the
1233      *            <code>arguments</code> array is not of the type
1234      *            expected by the format element(s) that use it.
1235      */
1236     private StringBuffer subformat(Object[] arguments, StringBuffer result,
1237                                    FieldPosition fp, List<AttributedCharacterIterator> characterIterators) {
1238         // note: this implementation assumes a fast substring & index.
1239         // if this is not true, would be better to append chars one by one.
1240         int lastOffset = 0;
1241         int last = result.length();
1242         for (int i = 0; i <= maxOffset; ++i) {
1243             result.append(pattern, lastOffset, offsets[i]);
1244             lastOffset = offsets[i];
1245             int argumentNumber = argumentNumbers[i];
1246             if (arguments == null || argumentNumber >= arguments.length) {
1247                 result.append('{').append(argumentNumber).append('}');
1248                 continue;
1249             }
1250             // int argRecursion = ((recursionProtection >> (argumentNumber*2)) & 0x3);
1251             if (false) { // if (argRecursion == 3){
1252                 // prevent loop!!!
1253                 result.append('\uFFFD');
1254             } else {
1255                 Object obj = arguments[argumentNumber];
1256                 String arg = null;
1257                 Format subFormatter = null;
1258                 if (obj == null) {
1259                     arg = "null";
1260                 } else if (formats[i] != null) {
1261                     subFormatter = formats[i];
1262                     if (subFormatter instanceof ChoiceFormat) {
1263                         arg = formats[i].format(obj);
1264                         if (arg.indexOf('{') >= 0) {
1265                             subFormatter = new MessageFormat(arg, locale);
1266                             obj = arguments;
1267                             arg = null;
1268                         }
1269                     }
1270                 } else if (obj instanceof Number) {
1271                     // format number if can
1272                     subFormatter = NumberFormat.getInstance(locale);
1273                 } else if (obj instanceof Date) {
1274                     // format a Date if can
1275                     subFormatter = DateFormat.getDateTimeInstance(
1276                              DateFormat.SHORT, DateFormat.SHORT, locale);//fix
1277                 } else if (obj instanceof String) {
1278                     arg = (String) obj;
1279 
1280                 } else {
1281                     arg = obj.toString();
1282                     if (arg == null) arg = "null";
1283                 }
1284 
1285                 // At this point we are in two states, either subFormatter
1286                 // is non-null indicating we should format obj using it,
1287                 // or arg is non-null and we should use it as the value.
1288 
1289                 if (characterIterators != null) {
1290                     // If characterIterators is non-null, it indicates we need
1291                     // to get the CharacterIterator from the child formatter.
1292                     if (last != result.length()) {
1293                         characterIterators.add(
1294                             createAttributedCharacterIterator(result.substring
1295                                                               (last)));
1296                         last = result.length();
1297                     }
1298                     if (subFormatter != null) {
1299                         AttributedCharacterIterator subIterator =
1300                                    subFormatter.formatToCharacterIterator(obj);
1301 
1302                         append(result, subIterator);
1303                         if (last != result.length()) {
1304                             characterIterators.add(
1305                                          createAttributedCharacterIterator(
1306                                          subIterator, Field.ARGUMENT,
1307                                          Integer.valueOf(argumentNumber)));
1308                             last = result.length();
1309                         }
1310                         arg = null;
1311                     }
1312                     if (arg != null && arg.length() > 0) {
1313                         result.append(arg);
1314                         characterIterators.add(
1315                                  createAttributedCharacterIterator(
1316                                  arg, Field.ARGUMENT,
1317                                  Integer.valueOf(argumentNumber)));
1318                         last = result.length();
1319                     }
1320                 }
1321                 else {
1322                     if (subFormatter != null) {
1323                         arg = subFormatter.format(obj);
1324                     }
1325                     last = result.length();
1326                     result.append(arg);
1327                     if (i == 0 && fp != null && Field.ARGUMENT.equals(
1328                                   fp.getFieldAttribute())) {
1329                         fp.setBeginIndex(last);
1330                         fp.setEndIndex(result.length());
1331                     }
1332                     last = result.length();
1333                 }
1334             }
1335         }
1336         result.append(pattern, lastOffset, pattern.length());
1337         if (characterIterators != null && last != result.length()) {
1338             characterIterators.add(createAttributedCharacterIterator(
1339                                    result.substring(last)));
1340         }
1341         return result;
1342     }
1343 
1344     /**
1345      * Convenience method to append all the characters in
1346      * <code>iterator</code> to the StringBuffer <code>result</code>.
1347      */
1348     private void append(StringBuffer result, CharacterIterator iterator) {
1349         if (iterator.first() != CharacterIterator.DONE) {
1350             char aChar;
1351 
1352             result.append(iterator.first());
1353             while ((aChar = iterator.next()) != CharacterIterator.DONE) {
1354                 result.append(aChar);
1355             }
1356         }
1357     }
1358 
1359     // Indices for segments
1360     private static final int SEG_RAW      = 0;
1361     private static final int SEG_INDEX    = 1;
1362     private static final int SEG_TYPE     = 2;
1363     private static final int SEG_MODIFIER = 3; // modifier or subformat
1364 
1365     // Indices for type keywords
1366     private static final int TYPE_NULL    = 0;
1367     private static final int TYPE_NUMBER  = 1;
1368     private static final int TYPE_DATE    = 2;
1369     private static final int TYPE_TIME    = 3;
1370     private static final int TYPE_CHOICE  = 4;
1371 
1372     private static final String[] TYPE_KEYWORDS = {
1373         "",
1374         "number",
1375         "date",
1376         "time",
1377         "choice"
1378     };
1379 
1380     // Indices for number modifiers
1381     private static final int MODIFIER_DEFAULT  = 0; // common in number and date-time
1382     private static final int MODIFIER_CURRENCY = 1;
1383     private static final int MODIFIER_PERCENT  = 2;
1384     private static final int MODIFIER_INTEGER  = 3;
1385 
1386     private static final String[] NUMBER_MODIFIER_KEYWORDS = {
1387         "",
1388         "currency",
1389         "percent",
1390         "integer"
1391     };
1392 
1393     // Indices for date-time modifiers
1394     private static final int MODIFIER_SHORT   = 1;
1395     private static final int MODIFIER_MEDIUM  = 2;
1396     private static final int MODIFIER_LONG    = 3;
1397     private static final int MODIFIER_FULL    = 4;
1398 
1399     private static final String[] DATE_TIME_MODIFIER_KEYWORDS = {
1400         "",
1401         "short",
1402         "medium",
1403         "long",
1404         "full"
1405     };
1406 
1407     // Date-time style values corresponding to the date-time modifiers.
1408     private static final int[] DATE_TIME_MODIFIERS = {
1409         DateFormat.DEFAULT,
1410         DateFormat.SHORT,
1411         DateFormat.MEDIUM,
1412         DateFormat.LONG,
1413         DateFormat.FULL,
1414     };
1415 
1416     private void makeFormat(int position, int offsetNumber,
1417                             StringBuilder[] textSegments)
1418     {
1419         String[] segments = new String[textSegments.length];
1420         for (int i = 0; i < textSegments.length; i++) {
1421             StringBuilder oneseg = textSegments[i];
1422             segments[i] = (oneseg != null) ? oneseg.toString() : "";
1423         }
1424 
1425         // get the argument number
1426         int argumentNumber;
1427         try {
1428             argumentNumber = Integer.parseInt(segments[SEG_INDEX]); // always unlocalized!
1429         } catch (NumberFormatException e) {
1430             throw new IllegalArgumentException("can't parse argument number: "
1431                                                + segments[SEG_INDEX], e);
1432         }
1433         if (argumentNumber < 0) {
1434             throw new IllegalArgumentException("negative argument number: "
1435                                                + argumentNumber);
1436         }
1437 
1438         // resize format information arrays if necessary
1439         if (offsetNumber >= formats.length) {
1440             int newLength = formats.length * 2;
1441             Format[] newFormats = new Format[newLength];
1442             int[] newOffsets = new int[newLength];
1443             int[] newArgumentNumbers = new int[newLength];
1444             System.arraycopy(formats, 0, newFormats, 0, maxOffset + 1);
1445             System.arraycopy(offsets, 0, newOffsets, 0, maxOffset + 1);
1446             System.arraycopy(argumentNumbers, 0, newArgumentNumbers, 0, maxOffset + 1);
1447             formats = newFormats;
1448             offsets = newOffsets;
1449             argumentNumbers = newArgumentNumbers;
1450         }
1451         int oldMaxOffset = maxOffset;
1452         maxOffset = offsetNumber;
1453         offsets[offsetNumber] = segments[SEG_RAW].length();
1454         argumentNumbers[offsetNumber] = argumentNumber;
1455 
1456         // now get the format
1457         Format newFormat = null;
1458         if (segments[SEG_TYPE].length() != 0) {
1459             int type = findKeyword(segments[SEG_TYPE], TYPE_KEYWORDS);
1460             switch (type) {
1461             case TYPE_NULL:
1462                 // Type "" is allowed. e.g., "{0,}", "{0,,}", and "{0,,#}"
1463                 // are treated as "{0}".
1464                 break;
1465 
1466             case TYPE_NUMBER:
1467                 switch (findKeyword(segments[SEG_MODIFIER], NUMBER_MODIFIER_KEYWORDS)) {
1468                 case MODIFIER_DEFAULT:
1469                     newFormat = NumberFormat.getInstance(locale);
1470                     break;
1471                 case MODIFIER_CURRENCY:
1472                     newFormat = NumberFormat.getCurrencyInstance(locale);
1473                     break;
1474                 case MODIFIER_PERCENT:
1475                     newFormat = NumberFormat.getPercentInstance(locale);
1476                     break;
1477                 case MODIFIER_INTEGER:
1478                     newFormat = NumberFormat.getIntegerInstance(locale);
1479                     break;
1480                 default: // DecimalFormat pattern
1481                     try {
1482                         newFormat = new DecimalFormat(segments[SEG_MODIFIER],
1483                                                       DecimalFormatSymbols.getInstance(locale));
1484                     } catch (IllegalArgumentException e) {
1485                         maxOffset = oldMaxOffset;
1486                         throw e;
1487                     }
1488                     break;
1489                 }
1490                 break;
1491 
1492             case TYPE_DATE:
1493             case TYPE_TIME:
1494                 int mod = findKeyword(segments[SEG_MODIFIER], DATE_TIME_MODIFIER_KEYWORDS);
1495                 if (mod >= 0 && mod < DATE_TIME_MODIFIER_KEYWORDS.length) {
1496                     if (type == TYPE_DATE) {
1497                         newFormat = DateFormat.getDateInstance(DATE_TIME_MODIFIERS[mod],
1498                                                                locale);
1499                     } else {
1500                         newFormat = DateFormat.getTimeInstance(DATE_TIME_MODIFIERS[mod],
1501                                                                locale);
1502                     }
1503                 } else {
1504                     // SimpleDateFormat pattern
1505                     try {
1506                         newFormat = new SimpleDateFormat(segments[SEG_MODIFIER], locale);
1507                     } catch (IllegalArgumentException e) {
1508                         maxOffset = oldMaxOffset;
1509                         throw e;
1510                     }
1511                 }
1512                 break;
1513 
1514             case TYPE_CHOICE:
1515                 try {
1516                     // ChoiceFormat pattern
1517                     newFormat = new ChoiceFormat(segments[SEG_MODIFIER]);
1518                 } catch (Exception e) {
1519                     maxOffset = oldMaxOffset;
1520                     throw new IllegalArgumentException("Choice Pattern incorrect: "
1521                                                        + segments[SEG_MODIFIER], e);
1522                 }
1523                 break;
1524 
1525             default:
1526                 maxOffset = oldMaxOffset;
1527                 throw new IllegalArgumentException("unknown format type: " +
1528                                                    segments[SEG_TYPE]);
1529             }
1530         }
1531         formats[offsetNumber] = newFormat;
1532     }
1533 
1534     private static final int findKeyword(String s, String[] list) {
1535         for (int i = 0; i < list.length; ++i) {
1536             if (s.equals(list[i]))
1537                 return i;
1538         }
1539 
1540         // Try trimmed lowercase.
1541         String ls = s.trim().toLowerCase(Locale.ROOT);
1542         if (ls != s) {
1543             for (int i = 0; i < list.length; ++i) {
1544                 if (ls.equals(list[i]))
1545                     return i;
1546             }
1547         }
1548         return -1;
1549     }
1550 
1551     private static final void copyAndFixQuotes(String source, int start, int end,
1552                                                StringBuilder target) {
1553         boolean quoted = false;
1554 
1555         for (int i = start; i < end; ++i) {
1556             char ch = source.charAt(i);
1557             if (ch == '{') {
1558                 if (!quoted) {
1559                     target.append('\'');
1560                     quoted = true;
1561                 }
1562                 target.append(ch);
1563             } else if (ch == '\'') {
1564                 target.append("''");
1565             } else {
1566                 if (quoted) {
1567                     target.append('\'');
1568                     quoted = false;
1569                 }
1570                 target.append(ch);
1571             }
1572         }
1573         if (quoted) {
1574             target.append('\'');
1575         }
1576     }
1577 
1578     /**
1579      * After reading an object from the input stream, do a simple verification
1580      * to maintain class invariants.
1581      * @throws InvalidObjectException if the objects read from the stream is invalid.
1582      */
1583     private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
1584         in.defaultReadObject();
1585         boolean isValid = maxOffset >= -1
1586                 && formats.length > maxOffset
1587                 && offsets.length > maxOffset
1588                 && argumentNumbers.length > maxOffset;
1589         if (isValid) {
1590             int lastOffset = pattern.length() + 1;
1591             for (int i = maxOffset; i >= 0; --i) {
1592                 if ((offsets[i] < 0) || (offsets[i] > lastOffset)) {
1593                     isValid = false;
1594                     break;
1595                 } else {
1596                     lastOffset = offsets[i];
1597                 }
1598             }
1599         }
1600         if (!isValid) {
1601             throw new InvalidObjectException("Could not reconstruct MessageFormat from corrupt stream.");
1602         }
1603     }
1604 }