rt/emul/compact/src/main/java/java/text/MessageFormat.java
branchjdk7-b147
changeset 1334 588d5bf7a560
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/rt/emul/compact/src/main/java/java/text/MessageFormat.java	Thu Oct 03 15:40:35 2013 +0200
     1.3 @@ -0,0 +1,1594 @@
     1.4 +/*
     1.5 + * Copyright (c) 1996, 2010, Oracle and/or its affiliates. All rights reserved.
     1.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     1.7 + *
     1.8 + * This code is free software; you can redistribute it and/or modify it
     1.9 + * under the terms of the GNU General Public License version 2 only, as
    1.10 + * published by the Free Software Foundation.  Oracle designates this
    1.11 + * particular file as subject to the "Classpath" exception as provided
    1.12 + * by Oracle in the LICENSE file that accompanied this code.
    1.13 + *
    1.14 + * This code is distributed in the hope that it will be useful, but WITHOUT
    1.15 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    1.16 + * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    1.17 + * version 2 for more details (a copy is included in the LICENSE file that
    1.18 + * accompanied this code).
    1.19 + *
    1.20 + * You should have received a copy of the GNU General Public License version
    1.21 + * 2 along with this work; if not, write to the Free Software Foundation,
    1.22 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    1.23 + *
    1.24 + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    1.25 + * or visit www.oracle.com if you need additional information or have any
    1.26 + * questions.
    1.27 + */
    1.28 +
    1.29 +/*
    1.30 + * (C) Copyright Taligent, Inc. 1996, 1997 - All Rights Reserved
    1.31 + * (C) Copyright IBM Corp. 1996 - 1998 - All Rights Reserved
    1.32 + *
    1.33 + *   The original version of this source code and documentation is copyrighted
    1.34 + * and owned by Taligent, Inc., a wholly-owned subsidiary of IBM. These
    1.35 + * materials are provided under terms of a License Agreement between Taligent
    1.36 + * and Sun. This technology is protected by multiple US and International
    1.37 + * patents. This notice and attribution to Taligent may not be removed.
    1.38 + *   Taligent is a registered trademark of Taligent, Inc.
    1.39 + *
    1.40 + */
    1.41 +
    1.42 +package java.text;
    1.43 +
    1.44 +import java.io.InvalidObjectException;
    1.45 +import java.io.IOException;
    1.46 +import java.io.ObjectInputStream;
    1.47 +import java.text.DecimalFormat;
    1.48 +import java.util.ArrayList;
    1.49 +import java.util.Arrays;
    1.50 +import java.util.Date;
    1.51 +import java.util.List;
    1.52 +import java.util.Locale;
    1.53 +
    1.54 +
    1.55 +/**
    1.56 + * <code>MessageFormat</code> provides a means to produce concatenated
    1.57 + * messages in a language-neutral way. Use this to construct messages
    1.58 + * displayed for end users.
    1.59 + *
    1.60 + * <p>
    1.61 + * <code>MessageFormat</code> takes a set of objects, formats them, then
    1.62 + * inserts the formatted strings into the pattern at the appropriate places.
    1.63 + *
    1.64 + * <p>
    1.65 + * <strong>Note:</strong>
    1.66 + * <code>MessageFormat</code> differs from the other <code>Format</code>
    1.67 + * classes in that you create a <code>MessageFormat</code> object with one
    1.68 + * of its constructors (not with a <code>getInstance</code> style factory
    1.69 + * method). The factory methods aren't necessary because <code>MessageFormat</code>
    1.70 + * itself doesn't implement locale specific behavior. Any locale specific
    1.71 + * behavior is defined by the pattern that you provide as well as the
    1.72 + * subformats used for inserted arguments.
    1.73 + *
    1.74 + * <h4><a name="patterns">Patterns and Their Interpretation</a></h4>
    1.75 + *
    1.76 + * <code>MessageFormat</code> uses patterns of the following form:
    1.77 + * <blockquote><pre>
    1.78 + * <i>MessageFormatPattern:</i>
    1.79 + *         <i>String</i>
    1.80 + *         <i>MessageFormatPattern</i> <i>FormatElement</i> <i>String</i>
    1.81 + *
    1.82 + * <i>FormatElement:</i>
    1.83 + *         { <i>ArgumentIndex</i> }
    1.84 + *         { <i>ArgumentIndex</i> , <i>FormatType</i> }
    1.85 + *         { <i>ArgumentIndex</i> , <i>FormatType</i> , <i>FormatStyle</i> }
    1.86 + *
    1.87 + * <i>FormatType: one of </i>
    1.88 + *         number date time choice
    1.89 + *
    1.90 + * <i>FormatStyle:</i>
    1.91 + *         short
    1.92 + *         medium
    1.93 + *         long
    1.94 + *         full
    1.95 + *         integer
    1.96 + *         currency
    1.97 + *         percent
    1.98 + *         <i>SubformatPattern</i>
    1.99 + * </pre></blockquote>
   1.100 + *
   1.101 + * <p>Within a <i>String</i>, a pair of single quotes can be used to
   1.102 + * quote any arbitrary characters except single quotes. For example,
   1.103 + * pattern string <code>"'{0}'"</code> represents string
   1.104 + * <code>"{0}"</code>, not a <i>FormatElement</i>. A single quote itself
   1.105 + * must be represented by doubled single quotes {@code ''} throughout a
   1.106 + * <i>String</i>.  For example, pattern string <code>"'{''}'"</code> is
   1.107 + * interpreted as a sequence of <code>'{</code> (start of quoting and a
   1.108 + * left curly brace), <code>''</code> (a single quote), and
   1.109 + * <code>}'</code> (a right curly brace and end of quoting),
   1.110 + * <em>not</em> <code>'{'</code> and <code>'}'</code> (quoted left and
   1.111 + * right curly braces): representing string <code>"{'}"</code>,
   1.112 + * <em>not</em> <code>"{}"</code>.
   1.113 + *
   1.114 + * <p>A <i>SubformatPattern</i> is interpreted by its corresponding
   1.115 + * subformat, and subformat-dependent pattern rules apply. For example,
   1.116 + * pattern string <code>"{1,number,<u>$'#',##</u>}"</code>
   1.117 + * (<i>SubformatPattern</i> with underline) will produce a number format
   1.118 + * with the pound-sign quoted, with a result such as: {@code
   1.119 + * "$#31,45"}. Refer to each {@code Format} subclass documentation for
   1.120 + * details.
   1.121 + *
   1.122 + * <p>Any unmatched quote is treated as closed at the end of the given
   1.123 + * pattern. For example, pattern string {@code "'{0}"} is treated as
   1.124 + * pattern {@code "'{0}'"}.
   1.125 + *
   1.126 + * <p>Any curly braces within an unquoted pattern must be balanced. For
   1.127 + * example, <code>"ab {0} de"</code> and <code>"ab '}' de"</code> are
   1.128 + * valid patterns, but <code>"ab {0'}' de"</code>, <code>"ab } de"</code>
   1.129 + * and <code>"''{''"</code> are not.
   1.130 + *
   1.131 + * <p>
   1.132 + * <dl><dt><b>Warning:</b><dd>The rules for using quotes within message
   1.133 + * format patterns unfortunately have shown to be somewhat confusing.
   1.134 + * In particular, it isn't always obvious to localizers whether single
   1.135 + * quotes need to be doubled or not. Make sure to inform localizers about
   1.136 + * the rules, and tell them (for example, by using comments in resource
   1.137 + * bundle source files) which strings will be processed by {@code MessageFormat}.
   1.138 + * Note that localizers may need to use single quotes in translated
   1.139 + * strings where the original version doesn't have them.
   1.140 + * </dl>
   1.141 + * <p>
   1.142 + * The <i>ArgumentIndex</i> value is a non-negative integer written
   1.143 + * using the digits {@code '0'} through {@code '9'}, and represents an index into the
   1.144 + * {@code arguments} array passed to the {@code format} methods
   1.145 + * or the result array returned by the {@code parse} methods.
   1.146 + * <p>
   1.147 + * The <i>FormatType</i> and <i>FormatStyle</i> values are used to create
   1.148 + * a {@code Format} instance for the format element. The following
   1.149 + * table shows how the values map to {@code Format} instances. Combinations not
   1.150 + * shown in the table are illegal. A <i>SubformatPattern</i> must
   1.151 + * be a valid pattern string for the {@code Format} subclass used.
   1.152 + * <p>
   1.153 + * <table border=1 summary="Shows how FormatType and FormatStyle values map to Format instances">
   1.154 + *    <tr>
   1.155 + *       <th id="ft" class="TableHeadingColor">FormatType
   1.156 + *       <th id="fs" class="TableHeadingColor">FormatStyle
   1.157 + *       <th id="sc" class="TableHeadingColor">Subformat Created
   1.158 + *    <tr>
   1.159 + *       <td headers="ft"><i>(none)</i>
   1.160 + *       <td headers="fs"><i>(none)</i>
   1.161 + *       <td headers="sc"><code>null</code>
   1.162 + *    <tr>
   1.163 + *       <td headers="ft" rowspan=5><code>number</code>
   1.164 + *       <td headers="fs"><i>(none)</i>
   1.165 + *       <td headers="sc">{@link NumberFormat#getInstance(Locale) NumberFormat.getInstance}{@code (getLocale())}
   1.166 + *    <tr>
   1.167 + *       <td headers="fs"><code>integer</code>
   1.168 + *       <td headers="sc">{@link NumberFormat#getIntegerInstance(Locale) NumberFormat.getIntegerInstance}{@code (getLocale())}
   1.169 + *    <tr>
   1.170 + *       <td headers="fs"><code>currency</code>
   1.171 + *       <td headers="sc">{@link NumberFormat#getCurrencyInstance(Locale) NumberFormat.getCurrencyInstance}{@code (getLocale())}
   1.172 + *    <tr>
   1.173 + *       <td headers="fs"><code>percent</code>
   1.174 + *       <td headers="sc">{@link NumberFormat#getPercentInstance(Locale) NumberFormat.getPercentInstance}{@code (getLocale())}
   1.175 + *    <tr>
   1.176 + *       <td headers="fs"><i>SubformatPattern</i>
   1.177 + *       <td headers="sc">{@code new} {@link DecimalFormat#DecimalFormat(String,DecimalFormatSymbols) DecimalFormat}{@code (subformatPattern,} {@link DecimalFormatSymbols#getInstance(Locale) DecimalFormatSymbols.getInstance}{@code (getLocale()))}
   1.178 + *    <tr>
   1.179 + *       <td headers="ft" rowspan=6><code>date</code>
   1.180 + *       <td headers="fs"><i>(none)</i>
   1.181 + *       <td headers="sc">{@link DateFormat#getDateInstance(int,Locale) DateFormat.getDateInstance}{@code (}{@link DateFormat#DEFAULT}{@code , getLocale())}
   1.182 + *    <tr>
   1.183 + *       <td headers="fs"><code>short</code>
   1.184 + *       <td headers="sc">{@link DateFormat#getDateInstance(int,Locale) DateFormat.getDateInstance}{@code (}{@link DateFormat#SHORT}{@code , getLocale())}
   1.185 + *    <tr>
   1.186 + *       <td headers="fs"><code>medium</code>
   1.187 + *       <td headers="sc">{@link DateFormat#getDateInstance(int,Locale) DateFormat.getDateInstance}{@code (}{@link DateFormat#DEFAULT}{@code , getLocale())}
   1.188 + *    <tr>
   1.189 + *       <td headers="fs"><code>long</code>
   1.190 + *       <td headers="sc">{@link DateFormat#getDateInstance(int,Locale) DateFormat.getDateInstance}{@code (}{@link DateFormat#LONG}{@code , getLocale())}
   1.191 + *    <tr>
   1.192 + *       <td headers="fs"><code>full</code>
   1.193 + *       <td headers="sc">{@link DateFormat#getDateInstance(int,Locale) DateFormat.getDateInstance}{@code (}{@link DateFormat#FULL}{@code , getLocale())}
   1.194 + *    <tr>
   1.195 + *       <td headers="fs"><i>SubformatPattern</i>
   1.196 + *       <td headers="sc">{@code new} {@link SimpleDateFormat#SimpleDateFormat(String,Locale) SimpleDateFormat}{@code (subformatPattern, getLocale())}
   1.197 + *    <tr>
   1.198 + *       <td headers="ft" rowspan=6><code>time</code>
   1.199 + *       <td headers="fs"><i>(none)</i>
   1.200 + *       <td headers="sc">{@link DateFormat#getTimeInstance(int,Locale) DateFormat.getTimeInstance}{@code (}{@link DateFormat#DEFAULT}{@code , getLocale())}
   1.201 + *    <tr>
   1.202 + *       <td headers="fs"><code>short</code>
   1.203 + *       <td headers="sc">{@link DateFormat#getTimeInstance(int,Locale) DateFormat.getTimeInstance}{@code (}{@link DateFormat#SHORT}{@code , getLocale())}
   1.204 + *    <tr>
   1.205 + *       <td headers="fs"><code>medium</code>
   1.206 + *       <td headers="sc">{@link DateFormat#getTimeInstance(int,Locale) DateFormat.getTimeInstance}{@code (}{@link DateFormat#DEFAULT}{@code , getLocale())}
   1.207 + *    <tr>
   1.208 + *       <td headers="fs"><code>long</code>
   1.209 + *       <td headers="sc">{@link DateFormat#getTimeInstance(int,Locale) DateFormat.getTimeInstance}{@code (}{@link DateFormat#LONG}{@code , getLocale())}
   1.210 + *    <tr>
   1.211 + *       <td headers="fs"><code>full</code>
   1.212 + *       <td headers="sc">{@link DateFormat#getTimeInstance(int,Locale) DateFormat.getTimeInstance}{@code (}{@link DateFormat#FULL}{@code , getLocale())}
   1.213 + *    <tr>
   1.214 + *       <td headers="fs"><i>SubformatPattern</i>
   1.215 + *       <td headers="sc">{@code new} {@link SimpleDateFormat#SimpleDateFormat(String,Locale) SimpleDateFormat}{@code (subformatPattern, getLocale())}
   1.216 + *    <tr>
   1.217 + *       <td headers="ft"><code>choice</code>
   1.218 + *       <td headers="fs"><i>SubformatPattern</i>
   1.219 + *       <td headers="sc">{@code new} {@link ChoiceFormat#ChoiceFormat(String) ChoiceFormat}{@code (subformatPattern)}
   1.220 + * </table>
   1.221 + * <p>
   1.222 + *
   1.223 + * <h4>Usage Information</h4>
   1.224 + *
   1.225 + * <p>
   1.226 + * Here are some examples of usage.
   1.227 + * In real internationalized programs, the message format pattern and other
   1.228 + * static strings will, of course, be obtained from resource bundles.
   1.229 + * Other parameters will be dynamically determined at runtime.
   1.230 + * <p>
   1.231 + * The first example uses the static method <code>MessageFormat.format</code>,
   1.232 + * which internally creates a <code>MessageFormat</code> for one-time use:
   1.233 + * <blockquote><pre>
   1.234 + * int planet = 7;
   1.235 + * String event = "a disturbance in the Force";
   1.236 + *
   1.237 + * String result = MessageFormat.format(
   1.238 + *     "At {1,time} on {1,date}, there was {2} on planet {0,number,integer}.",
   1.239 + *     planet, new Date(), event);
   1.240 + * </pre></blockquote>
   1.241 + * The output is:
   1.242 + * <blockquote><pre>
   1.243 + * At 12:30 PM on Jul 3, 2053, there was a disturbance in the Force on planet 7.
   1.244 + * </pre></blockquote>
   1.245 + *
   1.246 + * <p>
   1.247 + * The following example creates a <code>MessageFormat</code> instance that
   1.248 + * can be used repeatedly:
   1.249 + * <blockquote><pre>
   1.250 + * int fileCount = 1273;
   1.251 + * String diskName = "MyDisk";
   1.252 + * Object[] testArgs = {new Long(fileCount), diskName};
   1.253 + *
   1.254 + * MessageFormat form = new MessageFormat(
   1.255 + *     "The disk \"{1}\" contains {0} file(s).");
   1.256 + *
   1.257 + * System.out.println(form.format(testArgs));
   1.258 + * </pre></blockquote>
   1.259 + * The output with different values for <code>fileCount</code>:
   1.260 + * <blockquote><pre>
   1.261 + * The disk "MyDisk" contains 0 file(s).
   1.262 + * The disk "MyDisk" contains 1 file(s).
   1.263 + * The disk "MyDisk" contains 1,273 file(s).
   1.264 + * </pre></blockquote>
   1.265 + *
   1.266 + * <p>
   1.267 + * For more sophisticated patterns, you can use a <code>ChoiceFormat</code>
   1.268 + * to produce correct forms for singular and plural:
   1.269 + * <blockquote><pre>
   1.270 + * MessageFormat form = new MessageFormat("The disk \"{1}\" contains {0}.");
   1.271 + * double[] filelimits = {0,1,2};
   1.272 + * String[] filepart = {"no files","one file","{0,number} files"};
   1.273 + * ChoiceFormat fileform = new ChoiceFormat(filelimits, filepart);
   1.274 + * form.setFormatByArgumentIndex(0, fileform);
   1.275 + *
   1.276 + * int fileCount = 1273;
   1.277 + * String diskName = "MyDisk";
   1.278 + * Object[] testArgs = {new Long(fileCount), diskName};
   1.279 + *
   1.280 + * System.out.println(form.format(testArgs));
   1.281 + * </pre></blockquote>
   1.282 + * The output with different values for <code>fileCount</code>:
   1.283 + * <blockquote><pre>
   1.284 + * The disk "MyDisk" contains no files.
   1.285 + * The disk "MyDisk" contains one file.
   1.286 + * The disk "MyDisk" contains 1,273 files.
   1.287 + * </pre></blockquote>
   1.288 + *
   1.289 + * <p>
   1.290 + * You can create the <code>ChoiceFormat</code> programmatically, as in the
   1.291 + * above example, or by using a pattern. See {@link ChoiceFormat}
   1.292 + * for more information.
   1.293 + * <blockquote><pre>
   1.294 + * form.applyPattern(
   1.295 + *    "There {0,choice,0#are no files|1#is one file|1&lt;are {0,number,integer} files}.");
   1.296 + * </pre></blockquote>
   1.297 + *
   1.298 + * <p>
   1.299 + * <strong>Note:</strong> As we see above, the string produced
   1.300 + * by a <code>ChoiceFormat</code> in <code>MessageFormat</code> is treated as special;
   1.301 + * occurrences of '{' are used to indicate subformats, and cause recursion.
   1.302 + * If you create both a <code>MessageFormat</code> and <code>ChoiceFormat</code>
   1.303 + * programmatically (instead of using the string patterns), then be careful not to
   1.304 + * produce a format that recurses on itself, which will cause an infinite loop.
   1.305 + * <p>
   1.306 + * When a single argument is parsed more than once in the string, the last match
   1.307 + * will be the final result of the parsing.  For example,
   1.308 + * <blockquote><pre>
   1.309 + * MessageFormat mf = new MessageFormat("{0,number,#.##}, {0,number,#.#}");
   1.310 + * Object[] objs = {new Double(3.1415)};
   1.311 + * String result = mf.format( objs );
   1.312 + * // result now equals "3.14, 3.1"
   1.313 + * objs = null;
   1.314 + * objs = mf.parse(result, new ParsePosition(0));
   1.315 + * // objs now equals {new Double(3.1)}
   1.316 + * </pre></blockquote>
   1.317 + *
   1.318 + * <p>
   1.319 + * Likewise, parsing with a {@code MessageFormat} object using patterns containing
   1.320 + * multiple occurrences of the same argument would return the last match.  For
   1.321 + * example,
   1.322 + * <blockquote><pre>
   1.323 + * MessageFormat mf = new MessageFormat("{0}, {0}, {0}");
   1.324 + * String forParsing = "x, y, z";
   1.325 + * Object[] objs = mf.parse(forParsing, new ParsePosition(0));
   1.326 + * // result now equals {new String("z")}
   1.327 + * </pre></blockquote>
   1.328 + *
   1.329 + * <h4><a name="synchronization">Synchronization</a></h4>
   1.330 + *
   1.331 + * <p>
   1.332 + * Message formats are not synchronized.
   1.333 + * It is recommended to create separate format instances for each thread.
   1.334 + * If multiple threads access a format concurrently, it must be synchronized
   1.335 + * externally.
   1.336 + *
   1.337 + * @see          java.util.Locale
   1.338 + * @see          Format
   1.339 + * @see          NumberFormat
   1.340 + * @see          DecimalFormat
   1.341 + * @see          DecimalFormatSymbols
   1.342 + * @see          ChoiceFormat
   1.343 + * @see          DateFormat
   1.344 + * @see          SimpleDateFormat
   1.345 + *
   1.346 + * @author       Mark Davis
   1.347 + */
   1.348 +
   1.349 +public class MessageFormat extends Format {
   1.350 +
   1.351 +    private static final long serialVersionUID = 6479157306784022952L;
   1.352 +
   1.353 +    /**
   1.354 +     * Constructs a MessageFormat for the default locale and the
   1.355 +     * specified pattern.
   1.356 +     * The constructor first sets the locale, then parses the pattern and
   1.357 +     * creates a list of subformats for the format elements contained in it.
   1.358 +     * Patterns and their interpretation are specified in the
   1.359 +     * <a href="#patterns">class description</a>.
   1.360 +     *
   1.361 +     * @param pattern the pattern for this message format
   1.362 +     * @exception IllegalArgumentException if the pattern is invalid
   1.363 +     */
   1.364 +    public MessageFormat(String pattern) {
   1.365 +        this.locale = Locale.getDefault(Locale.Category.FORMAT);
   1.366 +        applyPattern(pattern);
   1.367 +    }
   1.368 +
   1.369 +    /**
   1.370 +     * Constructs a MessageFormat for the specified locale and
   1.371 +     * pattern.
   1.372 +     * The constructor first sets the locale, then parses the pattern and
   1.373 +     * creates a list of subformats for the format elements contained in it.
   1.374 +     * Patterns and their interpretation are specified in the
   1.375 +     * <a href="#patterns">class description</a>.
   1.376 +     *
   1.377 +     * @param pattern the pattern for this message format
   1.378 +     * @param locale the locale for this message format
   1.379 +     * @exception IllegalArgumentException if the pattern is invalid
   1.380 +     * @since 1.4
   1.381 +     */
   1.382 +    public MessageFormat(String pattern, Locale locale) {
   1.383 +        this.locale = locale;
   1.384 +        applyPattern(pattern);
   1.385 +    }
   1.386 +
   1.387 +    /**
   1.388 +     * Sets the locale to be used when creating or comparing subformats.
   1.389 +     * This affects subsequent calls
   1.390 +     * <ul>
   1.391 +     * <li>to the {@link #applyPattern applyPattern}
   1.392 +     *     and {@link #toPattern toPattern} methods if format elements specify
   1.393 +     *     a format type and therefore have the subformats created in the
   1.394 +     *     <code>applyPattern</code> method, as well as
   1.395 +     * <li>to the <code>format</code> and
   1.396 +     *     {@link #formatToCharacterIterator formatToCharacterIterator} methods
   1.397 +     *     if format elements do not specify a format type and therefore have
   1.398 +     *     the subformats created in the formatting methods.
   1.399 +     * </ul>
   1.400 +     * Subformats that have already been created are not affected.
   1.401 +     *
   1.402 +     * @param locale the locale to be used when creating or comparing subformats
   1.403 +     */
   1.404 +    public void setLocale(Locale locale) {
   1.405 +        this.locale = locale;
   1.406 +    }
   1.407 +
   1.408 +    /**
   1.409 +     * Gets the locale that's used when creating or comparing subformats.
   1.410 +     *
   1.411 +     * @return the locale used when creating or comparing subformats
   1.412 +     */
   1.413 +    public Locale getLocale() {
   1.414 +        return locale;
   1.415 +    }
   1.416 +
   1.417 +
   1.418 +    /**
   1.419 +     * Sets the pattern used by this message format.
   1.420 +     * The method parses the pattern and creates a list of subformats
   1.421 +     * for the format elements contained in it.
   1.422 +     * Patterns and their interpretation are specified in the
   1.423 +     * <a href="#patterns">class description</a>.
   1.424 +     *
   1.425 +     * @param pattern the pattern for this message format
   1.426 +     * @exception IllegalArgumentException if the pattern is invalid
   1.427 +     */
   1.428 +    public void applyPattern(String pattern) {
   1.429 +            StringBuilder[] segments = new StringBuilder[4];
   1.430 +            // Allocate only segments[SEG_RAW] here. The rest are
   1.431 +            // allocated on demand.
   1.432 +            segments[SEG_RAW] = new StringBuilder();
   1.433 +
   1.434 +            int part = SEG_RAW;
   1.435 +            int formatNumber = 0;
   1.436 +            boolean inQuote = false;
   1.437 +            int braceStack = 0;
   1.438 +            maxOffset = -1;
   1.439 +            for (int i = 0; i < pattern.length(); ++i) {
   1.440 +                char ch = pattern.charAt(i);
   1.441 +                if (part == SEG_RAW) {
   1.442 +                    if (ch == '\'') {
   1.443 +                        if (i + 1 < pattern.length()
   1.444 +                            && pattern.charAt(i+1) == '\'') {
   1.445 +                            segments[part].append(ch);  // handle doubles
   1.446 +                            ++i;
   1.447 +                        } else {
   1.448 +                            inQuote = !inQuote;
   1.449 +                        }
   1.450 +                    } else if (ch == '{' && !inQuote) {
   1.451 +                        part = SEG_INDEX;
   1.452 +                        if (segments[SEG_INDEX] == null) {
   1.453 +                            segments[SEG_INDEX] = new StringBuilder();
   1.454 +                        }
   1.455 +                    } else {
   1.456 +                        segments[part].append(ch);
   1.457 +                    }
   1.458 +                } else  {
   1.459 +                    if (inQuote) {              // just copy quotes in parts
   1.460 +                        segments[part].append(ch);
   1.461 +                        if (ch == '\'') {
   1.462 +                            inQuote = false;
   1.463 +                        }
   1.464 +                    } else {
   1.465 +                        switch (ch) {
   1.466 +                        case ',':
   1.467 +                            if (part < SEG_MODIFIER) {
   1.468 +                                if (segments[++part] == null) {
   1.469 +                                    segments[part] = new StringBuilder();
   1.470 +                                }
   1.471 +                            } else {
   1.472 +                                segments[part].append(ch);
   1.473 +                            }
   1.474 +                            break;
   1.475 +                        case '{':
   1.476 +                            ++braceStack;
   1.477 +                            segments[part].append(ch);
   1.478 +                            break;
   1.479 +                        case '}':
   1.480 +                            if (braceStack == 0) {
   1.481 +                                part = SEG_RAW;
   1.482 +                                makeFormat(i, formatNumber, segments);
   1.483 +                                formatNumber++;
   1.484 +                                // throw away other segments
   1.485 +                                segments[SEG_INDEX] = null;
   1.486 +                                segments[SEG_TYPE] = null;
   1.487 +                                segments[SEG_MODIFIER] = null;
   1.488 +                            } else {
   1.489 +                                --braceStack;
   1.490 +                                segments[part].append(ch);
   1.491 +                            }
   1.492 +                            break;
   1.493 +                        case ' ':
   1.494 +                            // Skip any leading space chars for SEG_TYPE.
   1.495 +                            if (part != SEG_TYPE || segments[SEG_TYPE].length() > 0) {
   1.496 +                                segments[part].append(ch);
   1.497 +                            }
   1.498 +                            break;
   1.499 +                        case '\'':
   1.500 +                            inQuote = true;
   1.501 +                            // fall through, so we keep quotes in other parts
   1.502 +                        default:
   1.503 +                            segments[part].append(ch);
   1.504 +                            break;
   1.505 +                        }
   1.506 +                    }
   1.507 +                }
   1.508 +            }
   1.509 +            if (braceStack == 0 && part != 0) {
   1.510 +                maxOffset = -1;
   1.511 +                throw new IllegalArgumentException("Unmatched braces in the pattern.");
   1.512 +            }
   1.513 +            this.pattern = segments[0].toString();
   1.514 +    }
   1.515 +
   1.516 +
   1.517 +    /**
   1.518 +     * Returns a pattern representing the current state of the message format.
   1.519 +     * The string is constructed from internal information and therefore
   1.520 +     * does not necessarily equal the previously applied pattern.
   1.521 +     *
   1.522 +     * @return a pattern representing the current state of the message format
   1.523 +     */
   1.524 +    public String toPattern() {
   1.525 +        // later, make this more extensible
   1.526 +        int lastOffset = 0;
   1.527 +        StringBuilder result = new StringBuilder();
   1.528 +        for (int i = 0; i <= maxOffset; ++i) {
   1.529 +            copyAndFixQuotes(pattern, lastOffset, offsets[i], result);
   1.530 +            lastOffset = offsets[i];
   1.531 +            result.append('{').append(argumentNumbers[i]);
   1.532 +            Format fmt = formats[i];
   1.533 +            if (fmt == null) {
   1.534 +                // do nothing, string format
   1.535 +            } else if (fmt instanceof NumberFormat) {
   1.536 +                if (fmt.equals(NumberFormat.getInstance(locale))) {
   1.537 +                    result.append(",number");
   1.538 +                } else if (fmt.equals(NumberFormat.getCurrencyInstance(locale))) {
   1.539 +                    result.append(",number,currency");
   1.540 +                } else if (fmt.equals(NumberFormat.getPercentInstance(locale))) {
   1.541 +                    result.append(",number,percent");
   1.542 +                } else if (fmt.equals(NumberFormat.getIntegerInstance(locale))) {
   1.543 +                    result.append(",number,integer");
   1.544 +                } else {
   1.545 +                    if (fmt instanceof DecimalFormat) {
   1.546 +                        result.append(",number,").append(((DecimalFormat)fmt).toPattern());
   1.547 +                    } else if (fmt instanceof ChoiceFormat) {
   1.548 +                        result.append(",choice,").append(((ChoiceFormat)fmt).toPattern());
   1.549 +                    } else {
   1.550 +                        // UNKNOWN
   1.551 +                    }
   1.552 +                }
   1.553 +            } else if (fmt instanceof DateFormat) {
   1.554 +                int index;
   1.555 +                for (index = MODIFIER_DEFAULT; index < DATE_TIME_MODIFIERS.length; index++) {
   1.556 +                    DateFormat df = DateFormat.getDateInstance(DATE_TIME_MODIFIERS[index],
   1.557 +                                                               locale);
   1.558 +                    if (fmt.equals(df)) {
   1.559 +                        result.append(",date");
   1.560 +                        break;
   1.561 +                    }
   1.562 +                    df = DateFormat.getTimeInstance(DATE_TIME_MODIFIERS[index],
   1.563 +                                                    locale);
   1.564 +                    if (fmt.equals(df)) {
   1.565 +                        result.append(",time");
   1.566 +                        break;
   1.567 +                    }
   1.568 +                }
   1.569 +                if (index >= DATE_TIME_MODIFIERS.length) {
   1.570 +                    if (fmt instanceof SimpleDateFormat) {
   1.571 +                        result.append(",date,").append(((SimpleDateFormat)fmt).toPattern());
   1.572 +                    } else {
   1.573 +                        // UNKNOWN
   1.574 +                    }
   1.575 +                } else if (index != MODIFIER_DEFAULT) {
   1.576 +                    result.append(',').append(DATE_TIME_MODIFIER_KEYWORDS[index]);
   1.577 +                }
   1.578 +            } else {
   1.579 +                //result.append(", unknown");
   1.580 +            }
   1.581 +            result.append('}');
   1.582 +        }
   1.583 +        copyAndFixQuotes(pattern, lastOffset, pattern.length(), result);
   1.584 +        return result.toString();
   1.585 +    }
   1.586 +
   1.587 +    /**
   1.588 +     * Sets the formats to use for the values passed into
   1.589 +     * <code>format</code> methods or returned from <code>parse</code>
   1.590 +     * methods. The indices of elements in <code>newFormats</code>
   1.591 +     * correspond to the argument indices used in the previously set
   1.592 +     * pattern string.
   1.593 +     * The order of formats in <code>newFormats</code> thus corresponds to
   1.594 +     * the order of elements in the <code>arguments</code> array passed
   1.595 +     * to the <code>format</code> methods or the result array returned
   1.596 +     * by the <code>parse</code> methods.
   1.597 +     * <p>
   1.598 +     * If an argument index is used for more than one format element
   1.599 +     * in the pattern string, then the corresponding new format is used
   1.600 +     * for all such format elements. If an argument index is not used
   1.601 +     * for any format element in the pattern string, then the
   1.602 +     * corresponding new format is ignored. If fewer formats are provided
   1.603 +     * than needed, then only the formats for argument indices less
   1.604 +     * than <code>newFormats.length</code> are replaced.
   1.605 +     *
   1.606 +     * @param newFormats the new formats to use
   1.607 +     * @exception NullPointerException if <code>newFormats</code> is null
   1.608 +     * @since 1.4
   1.609 +     */
   1.610 +    public void setFormatsByArgumentIndex(Format[] newFormats) {
   1.611 +        for (int i = 0; i <= maxOffset; i++) {
   1.612 +            int j = argumentNumbers[i];
   1.613 +            if (j < newFormats.length) {
   1.614 +                formats[i] = newFormats[j];
   1.615 +            }
   1.616 +        }
   1.617 +    }
   1.618 +
   1.619 +    /**
   1.620 +     * Sets the formats to use for the format elements in the
   1.621 +     * previously set pattern string.
   1.622 +     * The order of formats in <code>newFormats</code> corresponds to
   1.623 +     * the order of format elements in the pattern string.
   1.624 +     * <p>
   1.625 +     * If more formats are provided than needed by the pattern string,
   1.626 +     * the remaining ones are ignored. If fewer formats are provided
   1.627 +     * than needed, then only the first <code>newFormats.length</code>
   1.628 +     * formats are replaced.
   1.629 +     * <p>
   1.630 +     * Since the order of format elements in a pattern string often
   1.631 +     * changes during localization, it is generally better to use the
   1.632 +     * {@link #setFormatsByArgumentIndex setFormatsByArgumentIndex}
   1.633 +     * method, which assumes an order of formats corresponding to the
   1.634 +     * order of elements in the <code>arguments</code> array passed to
   1.635 +     * the <code>format</code> methods or the result array returned by
   1.636 +     * the <code>parse</code> methods.
   1.637 +     *
   1.638 +     * @param newFormats the new formats to use
   1.639 +     * @exception NullPointerException if <code>newFormats</code> is null
   1.640 +     */
   1.641 +    public void setFormats(Format[] newFormats) {
   1.642 +        int runsToCopy = newFormats.length;
   1.643 +        if (runsToCopy > maxOffset + 1) {
   1.644 +            runsToCopy = maxOffset + 1;
   1.645 +        }
   1.646 +        for (int i = 0; i < runsToCopy; i++) {
   1.647 +            formats[i] = newFormats[i];
   1.648 +        }
   1.649 +    }
   1.650 +
   1.651 +    /**
   1.652 +     * Sets the format to use for the format elements within the
   1.653 +     * previously set pattern string that use the given argument
   1.654 +     * index.
   1.655 +     * The argument index is part of the format element definition and
   1.656 +     * represents an index into the <code>arguments</code> array passed
   1.657 +     * to the <code>format</code> methods or the result array returned
   1.658 +     * by the <code>parse</code> methods.
   1.659 +     * <p>
   1.660 +     * If the argument index is used for more than one format element
   1.661 +     * in the pattern string, then the new format is used for all such
   1.662 +     * format elements. If the argument index is not used for any format
   1.663 +     * element in the pattern string, then the new format is ignored.
   1.664 +     *
   1.665 +     * @param argumentIndex the argument index for which to use the new format
   1.666 +     * @param newFormat the new format to use
   1.667 +     * @since 1.4
   1.668 +     */
   1.669 +    public void setFormatByArgumentIndex(int argumentIndex, Format newFormat) {
   1.670 +        for (int j = 0; j <= maxOffset; j++) {
   1.671 +            if (argumentNumbers[j] == argumentIndex) {
   1.672 +                formats[j] = newFormat;
   1.673 +            }
   1.674 +        }
   1.675 +    }
   1.676 +
   1.677 +    /**
   1.678 +     * Sets the format to use for the format element with the given
   1.679 +     * format element index within the previously set pattern string.
   1.680 +     * The format element index is the zero-based number of the format
   1.681 +     * element counting from the start of the pattern string.
   1.682 +     * <p>
   1.683 +     * Since the order of format elements in a pattern string often
   1.684 +     * changes during localization, it is generally better to use the
   1.685 +     * {@link #setFormatByArgumentIndex setFormatByArgumentIndex}
   1.686 +     * method, which accesses format elements based on the argument
   1.687 +     * index they specify.
   1.688 +     *
   1.689 +     * @param formatElementIndex the index of a format element within the pattern
   1.690 +     * @param newFormat the format to use for the specified format element
   1.691 +     * @exception ArrayIndexOutOfBoundsException if {@code formatElementIndex} is equal to or
   1.692 +     *            larger than the number of format elements in the pattern string
   1.693 +     */
   1.694 +    public void setFormat(int formatElementIndex, Format newFormat) {
   1.695 +        formats[formatElementIndex] = newFormat;
   1.696 +    }
   1.697 +
   1.698 +    /**
   1.699 +     * Gets the formats used for the values passed into
   1.700 +     * <code>format</code> methods or returned from <code>parse</code>
   1.701 +     * methods. The indices of elements in the returned array
   1.702 +     * correspond to the argument indices used in the previously set
   1.703 +     * pattern string.
   1.704 +     * The order of formats in the returned array thus corresponds to
   1.705 +     * the order of elements in the <code>arguments</code> array passed
   1.706 +     * to the <code>format</code> methods or the result array returned
   1.707 +     * by the <code>parse</code> methods.
   1.708 +     * <p>
   1.709 +     * If an argument index is used for more than one format element
   1.710 +     * in the pattern string, then the format used for the last such
   1.711 +     * format element is returned in the array. If an argument index
   1.712 +     * is not used for any format element in the pattern string, then
   1.713 +     * null is returned in the array.
   1.714 +     *
   1.715 +     * @return the formats used for the arguments within the pattern
   1.716 +     * @since 1.4
   1.717 +     */
   1.718 +    public Format[] getFormatsByArgumentIndex() {
   1.719 +        int maximumArgumentNumber = -1;
   1.720 +        for (int i = 0; i <= maxOffset; i++) {
   1.721 +            if (argumentNumbers[i] > maximumArgumentNumber) {
   1.722 +                maximumArgumentNumber = argumentNumbers[i];
   1.723 +            }
   1.724 +        }
   1.725 +        Format[] resultArray = new Format[maximumArgumentNumber + 1];
   1.726 +        for (int i = 0; i <= maxOffset; i++) {
   1.727 +            resultArray[argumentNumbers[i]] = formats[i];
   1.728 +        }
   1.729 +        return resultArray;
   1.730 +    }
   1.731 +
   1.732 +    /**
   1.733 +     * Gets the formats used for the format elements in the
   1.734 +     * previously set pattern string.
   1.735 +     * The order of formats in the returned array corresponds to
   1.736 +     * the order of format elements in the pattern string.
   1.737 +     * <p>
   1.738 +     * Since the order of format elements in a pattern string often
   1.739 +     * changes during localization, it's generally better to use the
   1.740 +     * {@link #getFormatsByArgumentIndex getFormatsByArgumentIndex}
   1.741 +     * method, which assumes an order of formats corresponding to the
   1.742 +     * order of elements in the <code>arguments</code> array passed to
   1.743 +     * the <code>format</code> methods or the result array returned by
   1.744 +     * the <code>parse</code> methods.
   1.745 +     *
   1.746 +     * @return the formats used for the format elements in the pattern
   1.747 +     */
   1.748 +    public Format[] getFormats() {
   1.749 +        Format[] resultArray = new Format[maxOffset + 1];
   1.750 +        System.arraycopy(formats, 0, resultArray, 0, maxOffset + 1);
   1.751 +        return resultArray;
   1.752 +    }
   1.753 +
   1.754 +    /**
   1.755 +     * Formats an array of objects and appends the <code>MessageFormat</code>'s
   1.756 +     * pattern, with format elements replaced by the formatted objects, to the
   1.757 +     * provided <code>StringBuffer</code>.
   1.758 +     * <p>
   1.759 +     * The text substituted for the individual format elements is derived from
   1.760 +     * the current subformat of the format element and the
   1.761 +     * <code>arguments</code> element at the format element's argument index
   1.762 +     * as indicated by the first matching line of the following table. An
   1.763 +     * argument is <i>unavailable</i> if <code>arguments</code> is
   1.764 +     * <code>null</code> or has fewer than argumentIndex+1 elements.
   1.765 +     * <p>
   1.766 +     * <table border=1 summary="Examples of subformat,argument,and formatted text">
   1.767 +     *    <tr>
   1.768 +     *       <th>Subformat
   1.769 +     *       <th>Argument
   1.770 +     *       <th>Formatted Text
   1.771 +     *    <tr>
   1.772 +     *       <td><i>any</i>
   1.773 +     *       <td><i>unavailable</i>
   1.774 +     *       <td><code>"{" + argumentIndex + "}"</code>
   1.775 +     *    <tr>
   1.776 +     *       <td><i>any</i>
   1.777 +     *       <td><code>null</code>
   1.778 +     *       <td><code>"null"</code>
   1.779 +     *    <tr>
   1.780 +     *       <td><code>instanceof ChoiceFormat</code>
   1.781 +     *       <td><i>any</i>
   1.782 +     *       <td><code>subformat.format(argument).indexOf('{') >= 0 ?<br>
   1.783 +     *           (new MessageFormat(subformat.format(argument), getLocale())).format(argument) :
   1.784 +     *           subformat.format(argument)</code>
   1.785 +     *    <tr>
   1.786 +     *       <td><code>!= null</code>
   1.787 +     *       <td><i>any</i>
   1.788 +     *       <td><code>subformat.format(argument)</code>
   1.789 +     *    <tr>
   1.790 +     *       <td><code>null</code>
   1.791 +     *       <td><code>instanceof Number</code>
   1.792 +     *       <td><code>NumberFormat.getInstance(getLocale()).format(argument)</code>
   1.793 +     *    <tr>
   1.794 +     *       <td><code>null</code>
   1.795 +     *       <td><code>instanceof Date</code>
   1.796 +     *       <td><code>DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, getLocale()).format(argument)</code>
   1.797 +     *    <tr>
   1.798 +     *       <td><code>null</code>
   1.799 +     *       <td><code>instanceof String</code>
   1.800 +     *       <td><code>argument</code>
   1.801 +     *    <tr>
   1.802 +     *       <td><code>null</code>
   1.803 +     *       <td><i>any</i>
   1.804 +     *       <td><code>argument.toString()</code>
   1.805 +     * </table>
   1.806 +     * <p>
   1.807 +     * If <code>pos</code> is non-null, and refers to
   1.808 +     * <code>Field.ARGUMENT</code>, the location of the first formatted
   1.809 +     * string will be returned.
   1.810 +     *
   1.811 +     * @param arguments an array of objects to be formatted and substituted.
   1.812 +     * @param result where text is appended.
   1.813 +     * @param pos On input: an alignment field, if desired.
   1.814 +     *            On output: the offsets of the alignment field.
   1.815 +     * @exception IllegalArgumentException if an argument in the
   1.816 +     *            <code>arguments</code> array is not of the type
   1.817 +     *            expected by the format element(s) that use it.
   1.818 +     */
   1.819 +    public final StringBuffer format(Object[] arguments, StringBuffer result,
   1.820 +                                     FieldPosition pos)
   1.821 +    {
   1.822 +        return subformat(arguments, result, pos, null);
   1.823 +    }
   1.824 +
   1.825 +    /**
   1.826 +     * Creates a MessageFormat with the given pattern and uses it
   1.827 +     * to format the given arguments. This is equivalent to
   1.828 +     * <blockquote>
   1.829 +     *     <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>
   1.830 +     * </blockquote>
   1.831 +     *
   1.832 +     * @exception IllegalArgumentException if the pattern is invalid,
   1.833 +     *            or if an argument in the <code>arguments</code> array
   1.834 +     *            is not of the type expected by the format element(s)
   1.835 +     *            that use it.
   1.836 +     */
   1.837 +    public static String format(String pattern, Object ... arguments) {
   1.838 +        MessageFormat temp = new MessageFormat(pattern);
   1.839 +        return temp.format(arguments);
   1.840 +    }
   1.841 +
   1.842 +    // Overrides
   1.843 +    /**
   1.844 +     * Formats an array of objects and appends the <code>MessageFormat</code>'s
   1.845 +     * pattern, with format elements replaced by the formatted objects, to the
   1.846 +     * provided <code>StringBuffer</code>.
   1.847 +     * This is equivalent to
   1.848 +     * <blockquote>
   1.849 +     *     <code>{@link #format(java.lang.Object[], java.lang.StringBuffer, java.text.FieldPosition) format}((Object[]) arguments, result, pos)</code>
   1.850 +     * </blockquote>
   1.851 +     *
   1.852 +     * @param arguments an array of objects to be formatted and substituted.
   1.853 +     * @param result where text is appended.
   1.854 +     * @param pos On input: an alignment field, if desired.
   1.855 +     *            On output: the offsets of the alignment field.
   1.856 +     * @exception IllegalArgumentException if an argument in the
   1.857 +     *            <code>arguments</code> array is not of the type
   1.858 +     *            expected by the format element(s) that use it.
   1.859 +     */
   1.860 +    public final StringBuffer format(Object arguments, StringBuffer result,
   1.861 +                                     FieldPosition pos)
   1.862 +    {
   1.863 +        return subformat((Object[]) arguments, result, pos, null);
   1.864 +    }
   1.865 +
   1.866 +    /**
   1.867 +     * Formats an array of objects and inserts them into the
   1.868 +     * <code>MessageFormat</code>'s pattern, producing an
   1.869 +     * <code>AttributedCharacterIterator</code>.
   1.870 +     * You can use the returned <code>AttributedCharacterIterator</code>
   1.871 +     * to build the resulting String, as well as to determine information
   1.872 +     * about the resulting String.
   1.873 +     * <p>
   1.874 +     * The text of the returned <code>AttributedCharacterIterator</code> is
   1.875 +     * the same that would be returned by
   1.876 +     * <blockquote>
   1.877 +     *     <code>{@link #format(java.lang.Object[], java.lang.StringBuffer, java.text.FieldPosition) format}(arguments, new StringBuffer(), null).toString()</code>
   1.878 +     * </blockquote>
   1.879 +     * <p>
   1.880 +     * In addition, the <code>AttributedCharacterIterator</code> contains at
   1.881 +     * least attributes indicating where text was generated from an
   1.882 +     * argument in the <code>arguments</code> array. The keys of these attributes are of
   1.883 +     * type <code>MessageFormat.Field</code>, their values are
   1.884 +     * <code>Integer</code> objects indicating the index in the <code>arguments</code>
   1.885 +     * array of the argument from which the text was generated.
   1.886 +     * <p>
   1.887 +     * The attributes/value from the underlying <code>Format</code>
   1.888 +     * instances that <code>MessageFormat</code> uses will also be
   1.889 +     * placed in the resulting <code>AttributedCharacterIterator</code>.
   1.890 +     * This allows you to not only find where an argument is placed in the
   1.891 +     * resulting String, but also which fields it contains in turn.
   1.892 +     *
   1.893 +     * @param arguments an array of objects to be formatted and substituted.
   1.894 +     * @return AttributedCharacterIterator describing the formatted value.
   1.895 +     * @exception NullPointerException if <code>arguments</code> is null.
   1.896 +     * @exception IllegalArgumentException if an argument in the
   1.897 +     *            <code>arguments</code> array is not of the type
   1.898 +     *            expected by the format element(s) that use it.
   1.899 +     * @since 1.4
   1.900 +     */
   1.901 +    public AttributedCharacterIterator formatToCharacterIterator(Object arguments) {
   1.902 +        StringBuffer result = new StringBuffer();
   1.903 +        ArrayList iterators = new ArrayList();
   1.904 +
   1.905 +        if (arguments == null) {
   1.906 +            throw new NullPointerException(
   1.907 +                   "formatToCharacterIterator must be passed non-null object");
   1.908 +        }
   1.909 +        subformat((Object[]) arguments, result, null, iterators);
   1.910 +        if (iterators.size() == 0) {
   1.911 +            return createAttributedCharacterIterator("");
   1.912 +        }
   1.913 +        return createAttributedCharacterIterator(
   1.914 +                     (AttributedCharacterIterator[])iterators.toArray(
   1.915 +                     new AttributedCharacterIterator[iterators.size()]));
   1.916 +    }
   1.917 +
   1.918 +    /**
   1.919 +     * Parses the string.
   1.920 +     *
   1.921 +     * <p>Caveats: The parse may fail in a number of circumstances.
   1.922 +     * For example:
   1.923 +     * <ul>
   1.924 +     * <li>If one of the arguments does not occur in the pattern.
   1.925 +     * <li>If the format of an argument loses information, such as
   1.926 +     *     with a choice format where a large number formats to "many".
   1.927 +     * <li>Does not yet handle recursion (where
   1.928 +     *     the substituted strings contain {n} references.)
   1.929 +     * <li>Will not always find a match (or the correct match)
   1.930 +     *     if some part of the parse is ambiguous.
   1.931 +     *     For example, if the pattern "{1},{2}" is used with the
   1.932 +     *     string arguments {"a,b", "c"}, it will format as "a,b,c".
   1.933 +     *     When the result is parsed, it will return {"a", "b,c"}.
   1.934 +     * <li>If a single argument is parsed more than once in the string,
   1.935 +     *     then the later parse wins.
   1.936 +     * </ul>
   1.937 +     * When the parse fails, use ParsePosition.getErrorIndex() to find out
   1.938 +     * where in the string the parsing failed.  The returned error
   1.939 +     * index is the starting offset of the sub-patterns that the string
   1.940 +     * is comparing with.  For example, if the parsing string "AAA {0} BBB"
   1.941 +     * is comparing against the pattern "AAD {0} BBB", the error index is
   1.942 +     * 0. When an error occurs, the call to this method will return null.
   1.943 +     * If the source is null, return an empty array.
   1.944 +     */
   1.945 +    public Object[] parse(String source, ParsePosition pos) {
   1.946 +        if (source == null) {
   1.947 +            Object[] empty = {};
   1.948 +            return empty;
   1.949 +        }
   1.950 +
   1.951 +        int maximumArgumentNumber = -1;
   1.952 +        for (int i = 0; i <= maxOffset; i++) {
   1.953 +            if (argumentNumbers[i] > maximumArgumentNumber) {
   1.954 +                maximumArgumentNumber = argumentNumbers[i];
   1.955 +            }
   1.956 +        }
   1.957 +        Object[] resultArray = new Object[maximumArgumentNumber + 1];
   1.958 +
   1.959 +        int patternOffset = 0;
   1.960 +        int sourceOffset = pos.index;
   1.961 +        ParsePosition tempStatus = new ParsePosition(0);
   1.962 +        for (int i = 0; i <= maxOffset; ++i) {
   1.963 +            // match up to format
   1.964 +            int len = offsets[i] - patternOffset;
   1.965 +            if (len == 0 || pattern.regionMatches(patternOffset,
   1.966 +                                                  source, sourceOffset, len)) {
   1.967 +                sourceOffset += len;
   1.968 +                patternOffset += len;
   1.969 +            } else {
   1.970 +                pos.errorIndex = sourceOffset;
   1.971 +                return null; // leave index as is to signal error
   1.972 +            }
   1.973 +
   1.974 +            // now use format
   1.975 +            if (formats[i] == null) {   // string format
   1.976 +                // if at end, use longest possible match
   1.977 +                // otherwise uses first match to intervening string
   1.978 +                // does NOT recursively try all possibilities
   1.979 +                int tempLength = (i != maxOffset) ? offsets[i+1] : pattern.length();
   1.980 +
   1.981 +                int next;
   1.982 +                if (patternOffset >= tempLength) {
   1.983 +                    next = source.length();
   1.984 +                }else{
   1.985 +                    next = source.indexOf(pattern.substring(patternOffset, tempLength),
   1.986 +                                          sourceOffset);
   1.987 +                }
   1.988 +
   1.989 +                if (next < 0) {
   1.990 +                    pos.errorIndex = sourceOffset;
   1.991 +                    return null; // leave index as is to signal error
   1.992 +                } else {
   1.993 +                    String strValue= source.substring(sourceOffset,next);
   1.994 +                    if (!strValue.equals("{"+argumentNumbers[i]+"}"))
   1.995 +                        resultArray[argumentNumbers[i]]
   1.996 +                            = source.substring(sourceOffset,next);
   1.997 +                    sourceOffset = next;
   1.998 +                }
   1.999 +            } else {
  1.1000 +                tempStatus.index = sourceOffset;
  1.1001 +                resultArray[argumentNumbers[i]]
  1.1002 +                    = formats[i].parseObject(source,tempStatus);
  1.1003 +                if (tempStatus.index == sourceOffset) {
  1.1004 +                    pos.errorIndex = sourceOffset;
  1.1005 +                    return null; // leave index as is to signal error
  1.1006 +                }
  1.1007 +                sourceOffset = tempStatus.index; // update
  1.1008 +            }
  1.1009 +        }
  1.1010 +        int len = pattern.length() - patternOffset;
  1.1011 +        if (len == 0 || pattern.regionMatches(patternOffset,
  1.1012 +                                              source, sourceOffset, len)) {
  1.1013 +            pos.index = sourceOffset + len;
  1.1014 +        } else {
  1.1015 +            pos.errorIndex = sourceOffset;
  1.1016 +            return null; // leave index as is to signal error
  1.1017 +        }
  1.1018 +        return resultArray;
  1.1019 +    }
  1.1020 +
  1.1021 +    /**
  1.1022 +     * Parses text from the beginning of the given string to produce an object
  1.1023 +     * array.
  1.1024 +     * The method may not use the entire text of the given string.
  1.1025 +     * <p>
  1.1026 +     * See the {@link #parse(String, ParsePosition)} method for more information
  1.1027 +     * on message parsing.
  1.1028 +     *
  1.1029 +     * @param source A <code>String</code> whose beginning should be parsed.
  1.1030 +     * @return An <code>Object</code> array parsed from the string.
  1.1031 +     * @exception ParseException if the beginning of the specified string
  1.1032 +     *            cannot be parsed.
  1.1033 +     */
  1.1034 +    public Object[] parse(String source) throws ParseException {
  1.1035 +        ParsePosition pos  = new ParsePosition(0);
  1.1036 +        Object[] result = parse(source, pos);
  1.1037 +        if (pos.index == 0)  // unchanged, returned object is null
  1.1038 +            throw new ParseException("MessageFormat parse error!", pos.errorIndex);
  1.1039 +
  1.1040 +        return result;
  1.1041 +    }
  1.1042 +
  1.1043 +    /**
  1.1044 +     * Parses text from a string to produce an object array.
  1.1045 +     * <p>
  1.1046 +     * The method attempts to parse text starting at the index given by
  1.1047 +     * <code>pos</code>.
  1.1048 +     * If parsing succeeds, then the index of <code>pos</code> is updated
  1.1049 +     * to the index after the last character used (parsing does not necessarily
  1.1050 +     * use all characters up to the end of the string), and the parsed
  1.1051 +     * object array is returned. The updated <code>pos</code> can be used to
  1.1052 +     * indicate the starting point for the next call to this method.
  1.1053 +     * If an error occurs, then the index of <code>pos</code> is not
  1.1054 +     * changed, the error index of <code>pos</code> is set to the index of
  1.1055 +     * the character where the error occurred, and null is returned.
  1.1056 +     * <p>
  1.1057 +     * See the {@link #parse(String, ParsePosition)} method for more information
  1.1058 +     * on message parsing.
  1.1059 +     *
  1.1060 +     * @param source A <code>String</code>, part of which should be parsed.
  1.1061 +     * @param pos A <code>ParsePosition</code> object with index and error
  1.1062 +     *            index information as described above.
  1.1063 +     * @return An <code>Object</code> array parsed from the string. In case of
  1.1064 +     *         error, returns null.
  1.1065 +     * @exception NullPointerException if <code>pos</code> is null.
  1.1066 +     */
  1.1067 +    public Object parseObject(String source, ParsePosition pos) {
  1.1068 +        return parse(source, pos);
  1.1069 +    }
  1.1070 +
  1.1071 +    /**
  1.1072 +     * Creates and returns a copy of this object.
  1.1073 +     *
  1.1074 +     * @return a clone of this instance.
  1.1075 +     */
  1.1076 +    public Object clone() {
  1.1077 +        MessageFormat other = (MessageFormat) super.clone();
  1.1078 +
  1.1079 +        // clone arrays. Can't do with utility because of bug in Cloneable
  1.1080 +        other.formats = (Format[]) formats.clone(); // shallow clone
  1.1081 +        for (int i = 0; i < formats.length; ++i) {
  1.1082 +            if (formats[i] != null)
  1.1083 +                other.formats[i] = (Format)formats[i].clone();
  1.1084 +        }
  1.1085 +        // for primitives or immutables, shallow clone is enough
  1.1086 +        other.offsets = (int[]) offsets.clone();
  1.1087 +        other.argumentNumbers = (int[]) argumentNumbers.clone();
  1.1088 +
  1.1089 +        return other;
  1.1090 +    }
  1.1091 +
  1.1092 +    /**
  1.1093 +     * Equality comparison between two message format objects
  1.1094 +     */
  1.1095 +    public boolean equals(Object obj) {
  1.1096 +        if (this == obj)                      // quick check
  1.1097 +            return true;
  1.1098 +        if (obj == null || getClass() != obj.getClass())
  1.1099 +            return false;
  1.1100 +        MessageFormat other = (MessageFormat) obj;
  1.1101 +        return (maxOffset == other.maxOffset
  1.1102 +                && pattern.equals(other.pattern)
  1.1103 +                && ((locale != null && locale.equals(other.locale))
  1.1104 +                 || (locale == null && other.locale == null))
  1.1105 +                && Arrays.equals(offsets,other.offsets)
  1.1106 +                && Arrays.equals(argumentNumbers,other.argumentNumbers)
  1.1107 +                && Arrays.equals(formats,other.formats));
  1.1108 +    }
  1.1109 +
  1.1110 +    /**
  1.1111 +     * Generates a hash code for the message format object.
  1.1112 +     */
  1.1113 +    public int hashCode() {
  1.1114 +        return pattern.hashCode(); // enough for reasonable distribution
  1.1115 +    }
  1.1116 +
  1.1117 +
  1.1118 +    /**
  1.1119 +     * Defines constants that are used as attribute keys in the
  1.1120 +     * <code>AttributedCharacterIterator</code> returned
  1.1121 +     * from <code>MessageFormat.formatToCharacterIterator</code>.
  1.1122 +     *
  1.1123 +     * @since 1.4
  1.1124 +     */
  1.1125 +    public static class Field extends Format.Field {
  1.1126 +
  1.1127 +        // Proclaim serial compatibility with 1.4 FCS
  1.1128 +        private static final long serialVersionUID = 7899943957617360810L;
  1.1129 +
  1.1130 +        /**
  1.1131 +         * Creates a Field with the specified name.
  1.1132 +         *
  1.1133 +         * @param name Name of the attribute
  1.1134 +         */
  1.1135 +        protected Field(String name) {
  1.1136 +            super(name);
  1.1137 +        }
  1.1138 +
  1.1139 +        /**
  1.1140 +         * Resolves instances being deserialized to the predefined constants.
  1.1141 +         *
  1.1142 +         * @throws InvalidObjectException if the constant could not be
  1.1143 +         *         resolved.
  1.1144 +         * @return resolved MessageFormat.Field constant
  1.1145 +         */
  1.1146 +        protected Object readResolve() throws InvalidObjectException {
  1.1147 +            if (this.getClass() != MessageFormat.Field.class) {
  1.1148 +                throw new InvalidObjectException("subclass didn't correctly implement readResolve");
  1.1149 +            }
  1.1150 +
  1.1151 +            return ARGUMENT;
  1.1152 +        }
  1.1153 +
  1.1154 +        //
  1.1155 +        // The constants
  1.1156 +        //
  1.1157 +
  1.1158 +        /**
  1.1159 +         * Constant identifying a portion of a message that was generated
  1.1160 +         * from an argument passed into <code>formatToCharacterIterator</code>.
  1.1161 +         * The value associated with the key will be an <code>Integer</code>
  1.1162 +         * indicating the index in the <code>arguments</code> array of the
  1.1163 +         * argument from which the text was generated.
  1.1164 +         */
  1.1165 +        public final static Field ARGUMENT =
  1.1166 +                           new Field("message argument field");
  1.1167 +    }
  1.1168 +
  1.1169 +    // ===========================privates============================
  1.1170 +
  1.1171 +    /**
  1.1172 +     * The locale to use for formatting numbers and dates.
  1.1173 +     * @serial
  1.1174 +     */
  1.1175 +    private Locale locale;
  1.1176 +
  1.1177 +    /**
  1.1178 +     * The string that the formatted values are to be plugged into.  In other words, this
  1.1179 +     * is the pattern supplied on construction with all of the {} expressions taken out.
  1.1180 +     * @serial
  1.1181 +     */
  1.1182 +    private String pattern = "";
  1.1183 +
  1.1184 +    /** The initially expected number of subformats in the format */
  1.1185 +    private static final int INITIAL_FORMATS = 10;
  1.1186 +
  1.1187 +    /**
  1.1188 +     * An array of formatters, which are used to format the arguments.
  1.1189 +     * @serial
  1.1190 +     */
  1.1191 +    private Format[] formats = new Format[INITIAL_FORMATS];
  1.1192 +
  1.1193 +    /**
  1.1194 +     * The positions where the results of formatting each argument are to be inserted
  1.1195 +     * into the pattern.
  1.1196 +     * @serial
  1.1197 +     */
  1.1198 +    private int[] offsets = new int[INITIAL_FORMATS];
  1.1199 +
  1.1200 +    /**
  1.1201 +     * The argument numbers corresponding to each formatter.  (The formatters are stored
  1.1202 +     * in the order they occur in the pattern, not in the order in which the arguments
  1.1203 +     * are specified.)
  1.1204 +     * @serial
  1.1205 +     */
  1.1206 +    private int[] argumentNumbers = new int[INITIAL_FORMATS];
  1.1207 +
  1.1208 +    /**
  1.1209 +     * One less than the number of entries in <code>offsets</code>.  Can also be thought of
  1.1210 +     * as the index of the highest-numbered element in <code>offsets</code> that is being used.
  1.1211 +     * All of these arrays should have the same number of elements being used as <code>offsets</code>
  1.1212 +     * does, and so this variable suffices to tell us how many entries are in all of them.
  1.1213 +     * @serial
  1.1214 +     */
  1.1215 +    private int maxOffset = -1;
  1.1216 +
  1.1217 +    /**
  1.1218 +     * Internal routine used by format. If <code>characterIterators</code> is
  1.1219 +     * non-null, AttributedCharacterIterator will be created from the
  1.1220 +     * subformats as necessary. If <code>characterIterators</code> is null
  1.1221 +     * and <code>fp</code> is non-null and identifies
  1.1222 +     * <code>Field.MESSAGE_ARGUMENT</code>, the location of
  1.1223 +     * the first replaced argument will be set in it.
  1.1224 +     *
  1.1225 +     * @exception IllegalArgumentException if an argument in the
  1.1226 +     *            <code>arguments</code> array is not of the type
  1.1227 +     *            expected by the format element(s) that use it.
  1.1228 +     */
  1.1229 +    private StringBuffer subformat(Object[] arguments, StringBuffer result,
  1.1230 +                                   FieldPosition fp, List characterIterators) {
  1.1231 +        // note: this implementation assumes a fast substring & index.
  1.1232 +        // if this is not true, would be better to append chars one by one.
  1.1233 +        int lastOffset = 0;
  1.1234 +        int last = result.length();
  1.1235 +        for (int i = 0; i <= maxOffset; ++i) {
  1.1236 +            result.append(pattern.substring(lastOffset, offsets[i]));
  1.1237 +            lastOffset = offsets[i];
  1.1238 +            int argumentNumber = argumentNumbers[i];
  1.1239 +            if (arguments == null || argumentNumber >= arguments.length) {
  1.1240 +                result.append('{').append(argumentNumber).append('}');
  1.1241 +                continue;
  1.1242 +            }
  1.1243 +            // int argRecursion = ((recursionProtection >> (argumentNumber*2)) & 0x3);
  1.1244 +            if (false) { // if (argRecursion == 3){
  1.1245 +                // prevent loop!!!
  1.1246 +                result.append('\uFFFD');
  1.1247 +            } else {
  1.1248 +                Object obj = arguments[argumentNumber];
  1.1249 +                String arg = null;
  1.1250 +                Format subFormatter = null;
  1.1251 +                if (obj == null) {
  1.1252 +                    arg = "null";
  1.1253 +                } else if (formats[i] != null) {
  1.1254 +                    subFormatter = formats[i];
  1.1255 +                    if (subFormatter instanceof ChoiceFormat) {
  1.1256 +                        arg = formats[i].format(obj);
  1.1257 +                        if (arg.indexOf('{') >= 0) {
  1.1258 +                            subFormatter = new MessageFormat(arg, locale);
  1.1259 +                            obj = arguments;
  1.1260 +                            arg = null;
  1.1261 +                        }
  1.1262 +                    }
  1.1263 +                } else if (obj instanceof Number) {
  1.1264 +                    // format number if can
  1.1265 +                    subFormatter = NumberFormat.getInstance(locale);
  1.1266 +                } else if (obj instanceof Date) {
  1.1267 +                    // format a Date if can
  1.1268 +                    subFormatter = DateFormat.getDateTimeInstance(
  1.1269 +                             DateFormat.SHORT, DateFormat.SHORT, locale);//fix
  1.1270 +                } else if (obj instanceof String) {
  1.1271 +                    arg = (String) obj;
  1.1272 +
  1.1273 +                } else {
  1.1274 +                    arg = obj.toString();
  1.1275 +                    if (arg == null) arg = "null";
  1.1276 +                }
  1.1277 +
  1.1278 +                // At this point we are in two states, either subFormatter
  1.1279 +                // is non-null indicating we should format obj using it,
  1.1280 +                // or arg is non-null and we should use it as the value.
  1.1281 +
  1.1282 +                if (characterIterators != null) {
  1.1283 +                    // If characterIterators is non-null, it indicates we need
  1.1284 +                    // to get the CharacterIterator from the child formatter.
  1.1285 +                    if (last != result.length()) {
  1.1286 +                        characterIterators.add(
  1.1287 +                            createAttributedCharacterIterator(result.substring
  1.1288 +                                                              (last)));
  1.1289 +                        last = result.length();
  1.1290 +                    }
  1.1291 +                    if (subFormatter != null) {
  1.1292 +                        AttributedCharacterIterator subIterator =
  1.1293 +                                   subFormatter.formatToCharacterIterator(obj);
  1.1294 +
  1.1295 +                        append(result, subIterator);
  1.1296 +                        if (last != result.length()) {
  1.1297 +                            characterIterators.add(
  1.1298 +                                         createAttributedCharacterIterator(
  1.1299 +                                         subIterator, Field.ARGUMENT,
  1.1300 +                                         Integer.valueOf(argumentNumber)));
  1.1301 +                            last = result.length();
  1.1302 +                        }
  1.1303 +                        arg = null;
  1.1304 +                    }
  1.1305 +                    if (arg != null && arg.length() > 0) {
  1.1306 +                        result.append(arg);
  1.1307 +                        characterIterators.add(
  1.1308 +                                 createAttributedCharacterIterator(
  1.1309 +                                 arg, Field.ARGUMENT,
  1.1310 +                                 Integer.valueOf(argumentNumber)));
  1.1311 +                        last = result.length();
  1.1312 +                    }
  1.1313 +                }
  1.1314 +                else {
  1.1315 +                    if (subFormatter != null) {
  1.1316 +                        arg = subFormatter.format(obj);
  1.1317 +                    }
  1.1318 +                    last = result.length();
  1.1319 +                    result.append(arg);
  1.1320 +                    if (i == 0 && fp != null && Field.ARGUMENT.equals(
  1.1321 +                                  fp.getFieldAttribute())) {
  1.1322 +                        fp.setBeginIndex(last);
  1.1323 +                        fp.setEndIndex(result.length());
  1.1324 +                    }
  1.1325 +                    last = result.length();
  1.1326 +                }
  1.1327 +            }
  1.1328 +        }
  1.1329 +        result.append(pattern.substring(lastOffset, pattern.length()));
  1.1330 +        if (characterIterators != null && last != result.length()) {
  1.1331 +            characterIterators.add(createAttributedCharacterIterator(
  1.1332 +                                   result.substring(last)));
  1.1333 +        }
  1.1334 +        return result;
  1.1335 +    }
  1.1336 +
  1.1337 +    /**
  1.1338 +     * Convenience method to append all the characters in
  1.1339 +     * <code>iterator</code> to the StringBuffer <code>result</code>.
  1.1340 +     */
  1.1341 +    private void append(StringBuffer result, CharacterIterator iterator) {
  1.1342 +        if (iterator.first() != CharacterIterator.DONE) {
  1.1343 +            char aChar;
  1.1344 +
  1.1345 +            result.append(iterator.first());
  1.1346 +            while ((aChar = iterator.next()) != CharacterIterator.DONE) {
  1.1347 +                result.append(aChar);
  1.1348 +            }
  1.1349 +        }
  1.1350 +    }
  1.1351 +
  1.1352 +    // Indices for segments
  1.1353 +    private static final int SEG_RAW      = 0;
  1.1354 +    private static final int SEG_INDEX    = 1;
  1.1355 +    private static final int SEG_TYPE     = 2;
  1.1356 +    private static final int SEG_MODIFIER = 3; // modifier or subformat
  1.1357 +
  1.1358 +    // Indices for type keywords
  1.1359 +    private static final int TYPE_NULL    = 0;
  1.1360 +    private static final int TYPE_NUMBER  = 1;
  1.1361 +    private static final int TYPE_DATE    = 2;
  1.1362 +    private static final int TYPE_TIME    = 3;
  1.1363 +    private static final int TYPE_CHOICE  = 4;
  1.1364 +
  1.1365 +    private static final String[] TYPE_KEYWORDS = {
  1.1366 +        "",
  1.1367 +        "number",
  1.1368 +        "date",
  1.1369 +        "time",
  1.1370 +        "choice"
  1.1371 +    };
  1.1372 +
  1.1373 +    // Indices for number modifiers
  1.1374 +    private static final int MODIFIER_DEFAULT  = 0; // common in number and date-time
  1.1375 +    private static final int MODIFIER_CURRENCY = 1;
  1.1376 +    private static final int MODIFIER_PERCENT  = 2;
  1.1377 +    private static final int MODIFIER_INTEGER  = 3;
  1.1378 +
  1.1379 +    private static final String[] NUMBER_MODIFIER_KEYWORDS = {
  1.1380 +        "",
  1.1381 +        "currency",
  1.1382 +        "percent",
  1.1383 +        "integer"
  1.1384 +    };
  1.1385 +
  1.1386 +    // Indices for date-time modifiers
  1.1387 +    private static final int MODIFIER_SHORT   = 1;
  1.1388 +    private static final int MODIFIER_MEDIUM  = 2;
  1.1389 +    private static final int MODIFIER_LONG    = 3;
  1.1390 +    private static final int MODIFIER_FULL    = 4;
  1.1391 +
  1.1392 +    private static final String[] DATE_TIME_MODIFIER_KEYWORDS = {
  1.1393 +        "",
  1.1394 +        "short",
  1.1395 +        "medium",
  1.1396 +        "long",
  1.1397 +        "full"
  1.1398 +    };
  1.1399 +
  1.1400 +    // Date-time style values corresponding to the date-time modifiers.
  1.1401 +    private static final int[] DATE_TIME_MODIFIERS = {
  1.1402 +        DateFormat.DEFAULT,
  1.1403 +        DateFormat.SHORT,
  1.1404 +        DateFormat.MEDIUM,
  1.1405 +        DateFormat.LONG,
  1.1406 +        DateFormat.FULL,
  1.1407 +    };
  1.1408 +
  1.1409 +    private void makeFormat(int position, int offsetNumber,
  1.1410 +                            StringBuilder[] textSegments)
  1.1411 +    {
  1.1412 +        String[] segments = new String[textSegments.length];
  1.1413 +        for (int i = 0; i < textSegments.length; i++) {
  1.1414 +            StringBuilder oneseg = textSegments[i];
  1.1415 +            segments[i] = (oneseg != null) ? oneseg.toString() : "";
  1.1416 +        }
  1.1417 +
  1.1418 +        // get the argument number
  1.1419 +        int argumentNumber;
  1.1420 +        try {
  1.1421 +            argumentNumber = Integer.parseInt(segments[SEG_INDEX]); // always unlocalized!
  1.1422 +        } catch (NumberFormatException e) {
  1.1423 +            throw new IllegalArgumentException("can't parse argument number: "
  1.1424 +                                               + segments[SEG_INDEX], e);
  1.1425 +        }
  1.1426 +        if (argumentNumber < 0) {
  1.1427 +            throw new IllegalArgumentException("negative argument number: "
  1.1428 +                                               + argumentNumber);
  1.1429 +        }
  1.1430 +
  1.1431 +        // resize format information arrays if necessary
  1.1432 +        if (offsetNumber >= formats.length) {
  1.1433 +            int newLength = formats.length * 2;
  1.1434 +            Format[] newFormats = new Format[newLength];
  1.1435 +            int[] newOffsets = new int[newLength];
  1.1436 +            int[] newArgumentNumbers = new int[newLength];
  1.1437 +            System.arraycopy(formats, 0, newFormats, 0, maxOffset + 1);
  1.1438 +            System.arraycopy(offsets, 0, newOffsets, 0, maxOffset + 1);
  1.1439 +            System.arraycopy(argumentNumbers, 0, newArgumentNumbers, 0, maxOffset + 1);
  1.1440 +            formats = newFormats;
  1.1441 +            offsets = newOffsets;
  1.1442 +            argumentNumbers = newArgumentNumbers;
  1.1443 +        }
  1.1444 +        int oldMaxOffset = maxOffset;
  1.1445 +        maxOffset = offsetNumber;
  1.1446 +        offsets[offsetNumber] = segments[SEG_RAW].length();
  1.1447 +        argumentNumbers[offsetNumber] = argumentNumber;
  1.1448 +
  1.1449 +        // now get the format
  1.1450 +        Format newFormat = null;
  1.1451 +        if (segments[SEG_TYPE].length() != 0) {
  1.1452 +            int type = findKeyword(segments[SEG_TYPE], TYPE_KEYWORDS);
  1.1453 +            switch (type) {
  1.1454 +            case TYPE_NULL:
  1.1455 +                // Type "" is allowed. e.g., "{0,}", "{0,,}", and "{0,,#}"
  1.1456 +                // are treated as "{0}".
  1.1457 +                break;
  1.1458 +
  1.1459 +            case TYPE_NUMBER:
  1.1460 +                switch (findKeyword(segments[SEG_MODIFIER], NUMBER_MODIFIER_KEYWORDS)) {
  1.1461 +                case MODIFIER_DEFAULT:
  1.1462 +                    newFormat = NumberFormat.getInstance(locale);
  1.1463 +                    break;
  1.1464 +                case MODIFIER_CURRENCY:
  1.1465 +                    newFormat = NumberFormat.getCurrencyInstance(locale);
  1.1466 +                    break;
  1.1467 +                case MODIFIER_PERCENT:
  1.1468 +                    newFormat = NumberFormat.getPercentInstance(locale);
  1.1469 +                    break;
  1.1470 +                case MODIFIER_INTEGER:
  1.1471 +                    newFormat = NumberFormat.getIntegerInstance(locale);
  1.1472 +                    break;
  1.1473 +                default: // DecimalFormat pattern
  1.1474 +                    try {
  1.1475 +                        newFormat = new DecimalFormat(segments[SEG_MODIFIER],
  1.1476 +                                                      DecimalFormatSymbols.getInstance(locale));
  1.1477 +                    } catch (IllegalArgumentException e) {
  1.1478 +                        maxOffset = oldMaxOffset;
  1.1479 +                        throw e;
  1.1480 +                    }
  1.1481 +                    break;
  1.1482 +                }
  1.1483 +                break;
  1.1484 +
  1.1485 +            case TYPE_DATE:
  1.1486 +            case TYPE_TIME:
  1.1487 +                int mod = findKeyword(segments[SEG_MODIFIER], DATE_TIME_MODIFIER_KEYWORDS);
  1.1488 +                if (mod >= 0 && mod < DATE_TIME_MODIFIER_KEYWORDS.length) {
  1.1489 +                    if (type == TYPE_DATE) {
  1.1490 +                        newFormat = DateFormat.getDateInstance(DATE_TIME_MODIFIERS[mod],
  1.1491 +                                                               locale);
  1.1492 +                    } else {
  1.1493 +                        newFormat = DateFormat.getTimeInstance(DATE_TIME_MODIFIERS[mod],
  1.1494 +                                                               locale);
  1.1495 +                    }
  1.1496 +                } else {
  1.1497 +                    // SimpleDateFormat pattern
  1.1498 +                    try {
  1.1499 +                        newFormat = new SimpleDateFormat(segments[SEG_MODIFIER], locale);
  1.1500 +                    } catch (IllegalArgumentException e) {
  1.1501 +                        maxOffset = oldMaxOffset;
  1.1502 +                        throw e;
  1.1503 +                    }
  1.1504 +                }
  1.1505 +                break;
  1.1506 +
  1.1507 +            case TYPE_CHOICE:
  1.1508 +                try {
  1.1509 +                    // ChoiceFormat pattern
  1.1510 +                    newFormat = new ChoiceFormat(segments[SEG_MODIFIER]);
  1.1511 +                } catch (Exception e) {
  1.1512 +                    maxOffset = oldMaxOffset;
  1.1513 +                    throw new IllegalArgumentException("Choice Pattern incorrect: "
  1.1514 +                                                       + segments[SEG_MODIFIER], e);
  1.1515 +                }
  1.1516 +                break;
  1.1517 +
  1.1518 +            default:
  1.1519 +                maxOffset = oldMaxOffset;
  1.1520 +                throw new IllegalArgumentException("unknown format type: " +
  1.1521 +                                                   segments[SEG_TYPE]);
  1.1522 +            }
  1.1523 +        }
  1.1524 +        formats[offsetNumber] = newFormat;
  1.1525 +    }
  1.1526 +
  1.1527 +    private static final int findKeyword(String s, String[] list) {
  1.1528 +        for (int i = 0; i < list.length; ++i) {
  1.1529 +            if (s.equals(list[i]))
  1.1530 +                return i;
  1.1531 +        }
  1.1532 +
  1.1533 +        // Try trimmed lowercase.
  1.1534 +        String ls = s.trim().toLowerCase(Locale.ROOT);
  1.1535 +        if (ls != s) {
  1.1536 +            for (int i = 0; i < list.length; ++i) {
  1.1537 +                if (ls.equals(list[i]))
  1.1538 +                    return i;
  1.1539 +            }
  1.1540 +        }
  1.1541 +        return -1;
  1.1542 +    }
  1.1543 +
  1.1544 +    private static final void copyAndFixQuotes(String source, int start, int end,
  1.1545 +                                               StringBuilder target) {
  1.1546 +        boolean quoted = false;
  1.1547 +
  1.1548 +        for (int i = start; i < end; ++i) {
  1.1549 +            char ch = source.charAt(i);
  1.1550 +            if (ch == '{') {
  1.1551 +                if (!quoted) {
  1.1552 +                    target.append('\'');
  1.1553 +                    quoted = true;
  1.1554 +                }
  1.1555 +                target.append(ch);
  1.1556 +            } else if (ch == '\'') {
  1.1557 +                target.append("''");
  1.1558 +            } else {
  1.1559 +                if (quoted) {
  1.1560 +                    target.append('\'');
  1.1561 +                    quoted = false;
  1.1562 +                }
  1.1563 +                target.append(ch);
  1.1564 +            }
  1.1565 +        }
  1.1566 +        if (quoted) {
  1.1567 +            target.append('\'');
  1.1568 +        }
  1.1569 +    }
  1.1570 +
  1.1571 +    /**
  1.1572 +     * After reading an object from the input stream, do a simple verification
  1.1573 +     * to maintain class invariants.
  1.1574 +     * @throws InvalidObjectException if the objects read from the stream is invalid.
  1.1575 +     */
  1.1576 +    private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
  1.1577 +        in.defaultReadObject();
  1.1578 +        boolean isValid = maxOffset >= -1
  1.1579 +                && formats.length > maxOffset
  1.1580 +                && offsets.length > maxOffset
  1.1581 +                && argumentNumbers.length > maxOffset;
  1.1582 +        if (isValid) {
  1.1583 +            int lastOffset = pattern.length() + 1;
  1.1584 +            for (int i = maxOffset; i >= 0; --i) {
  1.1585 +                if ((offsets[i] < 0) || (offsets[i] > lastOffset)) {
  1.1586 +                    isValid = false;
  1.1587 +                    break;
  1.1588 +                } else {
  1.1589 +                    lastOffset = offsets[i];
  1.1590 +                }
  1.1591 +            }
  1.1592 +        }
  1.1593 +        if (!isValid) {
  1.1594 +            throw new InvalidObjectException("Could not reconstruct MessageFormat from corrupt stream.");
  1.1595 +        }
  1.1596 +    }
  1.1597 +}