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