-//##header\r
-/*\r
- *******************************************************************************\r
- * Copyright (C) 1996-2009, International Business Machines Corporation and *\r
- * others. All Rights Reserved. *\r
- *******************************************************************************\r
- */\r
-\r
-package com.ibm.icu.text;\r
-\r
-import com.ibm.icu.impl.ICUDebug;\r
-import com.ibm.icu.impl.ICUResourceBundle;\r
-import com.ibm.icu.impl.UCharacterProperty;\r
-import com.ibm.icu.impl.Utility;\r
-import com.ibm.icu.util.ULocale;\r
-import com.ibm.icu.util.UResourceBundle;\r
-import com.ibm.icu.util.UResourceBundleIterator;\r
-\r
-import java.math.BigInteger;\r
-import java.text.FieldPosition;\r
-import java.text.ParsePosition;\r
-import java.util.Arrays;\r
-import java.util.HashMap;\r
-import java.util.Locale;\r
-import java.util.Map;\r
-import java.util.MissingResourceException;\r
-import java.util.Set;\r
-\r
-\r
-/**\r
- * <p>A class that formats numbers according to a set of rules. This number formatter is\r
- * typically used for spelling out numeric values in words (e.g., 25,3476 as\r
- * "twenty-five thousand three hundred seventy-six" or "vingt-cinq mille trois\r
- * cents soixante-seize" or\r
- * "funfundzwanzigtausenddreihundertsechsundsiebzig"), but can also be used for\r
- * other complicated formatting tasks, such as formatting a number of seconds as hours,\r
- * minutes and seconds (e.g., 3,730 as "1:02:10").</p>\r
- *\r
- * <p>The resources contain three predefined formatters for each locale: spellout, which\r
- * spells out a value in words (123 is "one hundred twenty-three"); ordinal, which\r
- * appends an ordinal suffix to the end of a numeral (123 is "123rd"); and\r
- * duration, which shows a duration in seconds as hours, minutes, and seconds (123 is\r
- * "2:03"). The client can also define more specialized <tt>RuleBasedNumberFormat</tt>s\r
- * by supplying programmer-defined rule sets.</p>\r
- *\r
- * <p>The behavior of a <tt>RuleBasedNumberFormat</tt> is specified by a textual description\r
- * that is either passed to the constructor as a <tt>String</tt> or loaded from a resource\r
- * bundle. In its simplest form, the description consists of a semicolon-delimited list of <em>rules.</em>\r
- * Each rule has a string of output text and a value or range of values it is applicable to.\r
- * In a typical spellout rule set, the first twenty rules are the words for the numbers from\r
- * 0 to 19:</p>\r
- *\r
- * <pre>zero; one; two; three; four; five; six; seven; eight; nine;\r
- * ten; eleven; twelve; thirteen; fourteen; fifteen; sixteen; seventeen; eighteen; nineteen;</pre>\r
- *\r
- * <p>For larger numbers, we can use the preceding set of rules to format the ones place, and\r
- * we only have to supply the words for the multiples of 10:</p>\r
- *\r
- * <pre>20: twenty[->>];\r
- * 30: thirty{->>];\r
- * 40: forty[->>];\r
- * 50: fifty[->>];\r
- * 60: sixty[->>];\r
- * 70: seventy[->>];\r
- * 80: eighty[->>];\r
- * 90: ninety[->>];</pre>\r
- *\r
- * <p>In these rules, the <em>base value</em> is spelled out explicitly and set off from the\r
- * rule's output text with a colon. The rules are in a sorted list, and a rule is applicable\r
- * to all numbers from its own base value to one less than the next rule's base value. The\r
- * ">>" token is called a <em>substitution</em> and tells the fomatter to\r
- * isolate the number's ones digit, format it using this same set of rules, and place the\r
- * result at the position of the ">>" token. Text in brackets is omitted if\r
- * the number being formatted is an even multiple of 10 (the hyphen is a literal hyphen; 24\r
- * is "twenty-four," not "twenty four").</p>\r
- *\r
- * <p>For even larger numbers, we can actually look up several parts of the number in the\r
- * list:</p>\r
- *\r
- * <pre>100: << hundred[ >>];</pre>\r
- *\r
- * <p>The "<<" represents a new kind of substitution. The << isolates\r
- * the hundreds digit (and any digits to its left), formats it using this same rule set, and\r
- * places the result where the "<<" was. Notice also that the meaning of\r
- * >> has changed: it now refers to both the tens and the ones digits. The meaning of\r
- * both substitutions depends on the rule's base value. The base value determines the rule's <em>divisor,</em>\r
- * which is the highest power of 10 that is less than or equal to the base value (the user\r
- * can change this). To fill in the substitutions, the formatter divides the number being\r
- * formatted by the divisor. The integral quotient is used to fill in the <<\r
- * substitution, and the remainder is used to fill in the >> substitution. The meaning\r
- * of the brackets changes similarly: text in brackets is omitted if the value being\r
- * formatted is an even multiple of the rule's divisor. The rules are applied recursively, so\r
- * if a substitution is filled in with text that includes another substitution, that\r
- * substitution is also filled in.</p>\r
- *\r
- * <p>This rule covers values up to 999, at which point we add another rule:</p>\r
- *\r
- * <pre>1000: << thousand[ >>];</pre>\r
- *\r
- * <p>Again, the meanings of the brackets and substitution tokens shift because the rule's\r
- * base value is a higher power of 10, changing the rule's divisor. This rule can actually be\r
- * used all the way up to 999,999. This allows us to finish out the rules as follows:</p>\r
- *\r
- * <pre>1,000,000: << million[ >>];\r
- * 1,000,000,000: << billion[ >>];\r
- * 1,000,000,000,000: << trillion[ >>];\r
- * 1,000,000,000,000,000: OUT OF RANGE!;</pre>\r
- *\r
- * <p>Commas, periods, and spaces can be used in the base values to improve legibility and\r
- * are ignored by the rule parser. The last rule in the list is customarily treated as an\r
- * "overflow rule," applying to everything from its base value on up, and often (as\r
- * in this example) being used to print out an error message or default representation.\r
- * Notice also that the size of the major groupings in large numbers is controlled by the\r
- * spacing of the rules: because in English we group numbers by thousand, the higher rules\r
- * are separated from each other by a factor of 1,000.</p>\r
- *\r
- * <p>To see how these rules actually work in practice, consider the following example:\r
- * Formatting 25,430 with this rule set would work like this:</p>\r
- *\r
- * <table border="0" width="630">\r
- * <tr>\r
- * <td width="21"></td>\r
- * <td width="257" valign="top"><strong><< thousand >></strong></td>\r
- * <td width="340" valign="top">[the rule whose base value is 1,000 is applicable to 25,340]</td>\r
- * </tr>\r
- * <tr>\r
- * <td width="21"></td>\r
- * <td width="257" valign="top"><strong>twenty->></strong> thousand >></td>\r
- * <td width="340" valign="top">[25,340 over 1,000 is 25. The rule for 20 applies.]</td>\r
- * </tr>\r
- * <tr>\r
- * <td width="21"></td>\r
- * <td width="257" valign="top">twenty-<strong>five</strong> thousand >></td>\r
- * <td width="340" valign="top">[25 mod 10 is 5. The rule for 5 is "five."</td>\r
- * </tr>\r
- * <tr>\r
- * <td width="21"></td>\r
- * <td width="257" valign="top">twenty-five thousand <strong><< hundred >></strong></td>\r
- * <td width="340" valign="top">[25,340 mod 1,000 is 340. The rule for 100 applies.]</td>\r
- * </tr>\r
- * <tr>\r
- * <td width="21"></td>\r
- * <td width="257" valign="top">twenty-five thousand <strong>three</strong> hundred >></td>\r
- * <td width="340" valign="top">[340 over 100 is 3. The rule for 3 is "three."]</td>\r
- * </tr>\r
- * <tr>\r
- * <td width="21"></td>\r
- * <td width="257" valign="top">twenty-five thousand three hundred <strong>forty</strong></td>\r
- * <td width="340" valign="top">[340 mod 100 is 40. The rule for 40 applies. Since 40 divides\r
- * evenly by 10, the hyphen and substitution in the brackets are omitted.]</td>\r
- * </tr>\r
- * </table>\r
- *\r
- * <p>The above syntax suffices only to format positive integers. To format negative numbers,\r
- * we add a special rule:</p>\r
- *\r
- * <pre>-x: minus >>;</pre>\r
- *\r
- * <p>This is called a <em>negative-number rule,</em> and is identified by "-x"\r
- * where the base value would be. This rule is used to format all negative numbers. the\r
- * >> token here means "find the number's absolute value, format it with these\r
- * rules, and put the result here."</p>\r
- *\r
- * <p>We also add a special rule called a <em>fraction rule </em>for numbers with fractional\r
- * parts:</p>\r
- *\r
- * <pre>x.x: << point >>;</pre>\r
- *\r
- * <p>This rule is used for all positive non-integers (negative non-integers pass through the\r
- * negative-number rule first and then through this rule). Here, the << token refers to\r
- * the number's integral part, and the >> to the number's fractional part. The\r
- * fractional part is formatted as a series of single-digit numbers (e.g., 123.456 would be\r
- * formatted as "one hundred twenty-three point four five six").</p>\r
- *\r
- * <p>To see how this rule syntax is applied to various languages, examine the resource data.</p>\r
- *\r
- * <p>There is actually much more flexibility built into the rule language than the\r
- * description above shows. A formatter may own multiple rule sets, which can be selected by\r
- * the caller, and which can use each other to fill in their substitutions. Substitutions can\r
- * also be filled in with digits, using a DecimalFormat object. There is syntax that can be\r
- * used to alter a rule's divisor in various ways. And there is provision for much more\r
- * flexible fraction handling. A complete description of the rule syntax follows:</p>\r
- *\r
- * <hr>\r
- *\r
- * <p>The description of a <tt>RuleBasedNumberFormat</tt>'s behavior consists of one or more <em>rule\r
- * sets.</em> Each rule set consists of a name, a colon, and a list of <em>rules.</em> A rule\r
- * set name must begin with a % sign. Rule sets with names that begin with a single % sign\r
- * are <em>public:</em> the caller can specify that they be used to format and parse numbers.\r
- * Rule sets with names that begin with %% are <em>private:</em> they exist only for the use\r
- * of other rule sets. If a formatter only has one rule set, the name may be omitted.</p>\r
- *\r
- * <p>The user can also specify a special "rule set" named <tt>%%lenient-parse</tt>.\r
- * The body of <tt>%%lenient-parse</tt> isn't a set of number-formatting rules, but a <tt>RuleBasedCollator</tt>\r
- * description which is used to define equivalences for lenient parsing. For more information\r
- * on the syntax, see <tt>RuleBasedCollator</tt>. For more information on lenient parsing,\r
- * see <tt>setLenientParse()</tt>. <em>Note:</em> symbols that have syntactic meaning\r
- * in collation rules, such as '&', have no particular meaning when appearing outside\r
- * of the <tt>lenient-parse</tt> rule set.</p>\r
- *\r
- * <p>The body of a rule set consists of an ordered, semicolon-delimited list of <em>rules.</em>\r
- * Internally, every rule has a base value, a divisor, rule text, and zero, one, or two <em>substitutions.</em>\r
- * These parameters are controlled by the description syntax, which consists of a <em>rule\r
- * descriptor,</em> a colon, and a <em>rule body.</em></p>\r
- *\r
- * <p>A rule descriptor can take one of the following forms (text in <em>italics</em> is the\r
- * name of a token):</p>\r
- *\r
- * <table border="0" width="100%">\r
- * <tr>\r
- * <td width="5%" valign="top"></td>\r
- * <td width="8%" valign="top"><em>bv</em>:</td>\r
- * <td valign="top"><em>bv</em> specifies the rule's base value. <em>bv</em> is a decimal\r
- * number expressed using ASCII digits. <em>bv</em> may contain spaces, period, and commas,\r
- * which are irgnored. The rule's divisor is the highest power of 10 less than or equal to\r
- * the base value.</td>\r
- * </tr>\r
- * <tr>\r
- * <td width="5%" valign="top"></td>\r
- * <td width="8%" valign="top"><em>bv</em>/<em>rad</em>:</td>\r
- * <td valign="top"><em>bv</em> specifies the rule's base value. The rule's divisor is the\r
- * highest power of <em>rad</em> less than or equal to the base value.</td>\r
- * </tr>\r
- * <tr>\r
- * <td width="5%" valign="top"></td>\r
- * <td width="8%" valign="top"><em>bv</em>>:</td>\r
- * <td valign="top"><em>bv</em> specifies the rule's base value. To calculate the divisor,\r
- * let the radix be 10, and the exponent be the highest exponent of the radix that yields a\r
- * result less than or equal to the base value. Every > character after the base value\r
- * decreases the exponent by 1. If the exponent is positive or 0, the divisor is the radix\r
- * raised to the power of the exponent; otherwise, the divisor is 1.</td>\r
- * </tr>\r
- * <tr>\r
- * <td width="5%" valign="top"></td>\r
- * <td width="8%" valign="top"><em>bv</em>/<em>rad</em>>:</td>\r
- * <td valign="top"><em>bv</em> specifies the rule's base value. To calculate the divisor,\r
- * let the radix be <em>rad</em>, and the exponent be the highest exponent of the radix that\r
- * yields a result less than or equal to the base value. Every > character after the radix\r
- * decreases the exponent by 1. If the exponent is positive or 0, the divisor is the radix\r
- * raised to the power of the exponent; otherwise, the divisor is 1.</td>\r
- * </tr>\r
- * <tr>\r
- * <td width="5%" valign="top"></td>\r
- * <td width="8%" valign="top">-x:</td>\r
- * <td valign="top">The rule is a negative-number rule.</td>\r
- * </tr>\r
- * <tr>\r
- * <td width="5%" valign="top"></td>\r
- * <td width="8%" valign="top">x.x:</td>\r
- * <td valign="top">The rule is an <em>improper fraction rule.</em></td>\r
- * </tr>\r
- * <tr>\r
- * <td width="5%" valign="top"></td>\r
- * <td width="8%" valign="top">0.x:</td>\r
- * <td valign="top">The rule is a <em>proper fraction rule.</em></td>\r
- * </tr>\r
- * <tr>\r
- * <td width="5%" valign="top"></td>\r
- * <td width="8%" valign="top">x.0:</td>\r
- * <td valign="top">The rule is a <em>master rule.</em></td>\r
- * </tr>\r
- * <tr>\r
- * <td width="5%" valign="top"></td>\r
- * <td width="8%" valign="top"><em>nothing</em></td>\r
- * <td valign="top">If the rule's rule descriptor is left out, the base value is one plus the\r
- * preceding rule's base value (or zero if this is the first rule in the list) in a normal\r
- * rule set. In a fraction rule set, the base value is the same as the preceding rule's\r
- * base value.</td>\r
- * </tr>\r
- * </table>\r
- *\r
- * <p>A rule set may be either a regular rule set or a <em>fraction rule set,</em> depending\r
- * on whether it is used to format a number's integral part (or the whole number) or a\r
- * number's fractional part. Using a rule set to format a rule's fractional part makes it a\r
- * fraction rule set.</p>\r
- *\r
- * <p>Which rule is used to format a number is defined according to one of the following\r
- * algorithms: If the rule set is a regular rule set, do the following:\r
- *\r
- * <ul>\r
- * <li>If the rule set includes a master rule (and the number was passed in as a <tt>double</tt>),\r
- * use the master rule. (If the number being formatted was passed in as a <tt>long</tt>,\r
- * the master rule is ignored.)</li>\r
- * <li>If the number is negative, use the negative-number rule.</li>\r
- * <li>If the number has a fractional part and is greater than 1, use the improper fraction\r
- * rule.</li>\r
- * <li>If the number has a fractional part and is between 0 and 1, use the proper fraction\r
- * rule.</li>\r
- * <li>Binary-search the rule list for the rule with the highest base value less than or equal\r
- * to the number. If that rule has two substitutions, its base value is not an even multiple\r
- * of its divisor, and the number <em>is</em> an even multiple of the rule's divisor, use the\r
- * rule that precedes it in the rule list. Otherwise, use the rule itself.</li>\r
- * </ul>\r
- *\r
- * <p>If the rule set is a fraction rule set, do the following:\r
- *\r
- * <ul>\r
- * <li>Ignore negative-number and fraction rules.</li>\r
- * <li>For each rule in the list, multiply the number being formatted (which will always be\r
- * between 0 and 1) by the rule's base value. Keep track of the distance between the result\r
- * the nearest integer.</li>\r
- * <li>Use the rule that produced the result closest to zero in the above calculation. In the\r
- * event of a tie or a direct hit, use the first matching rule encountered. (The idea here is\r
- * to try each rule's base value as a possible denominator of a fraction. Whichever\r
- * denominator produces the fraction closest in value to the number being formatted wins.) If\r
- * the rule following the matching rule has the same base value, use it if the numerator of\r
- * the fraction is anything other than 1; if the numerator is 1, use the original matching\r
- * rule. (This is to allow singular and plural forms of the rule text without a lot of extra\r
- * hassle.)</li>\r
- * </ul>\r
- *\r
- * <p>A rule's body consists of a string of characters terminated by a semicolon. The rule\r
- * may include zero, one, or two <em>substitution tokens,</em> and a range of text in\r
- * brackets. The brackets denote optional text (and may also include one or both\r
- * substitutions). The exact meanings of the substitution tokens, and under what conditions\r
- * optional text is omitted, depend on the syntax of the substitution token and the context.\r
- * The rest of the text in a rule body is literal text that is output when the rule matches\r
- * the number being formatted.</p>\r
- *\r
- * <p>A substitution token begins and ends with a <em>token character.</em> The token\r
- * character and the context together specify a mathematical operation to be performed on the\r
- * number being formatted. An optional <em>substitution descriptor </em>specifies how the\r
- * value resulting from that operation is used to fill in the substitution. The position of\r
- * the substitution token in the rule body specifies the location of the resultant text in\r
- * the original rule text.</p>\r
- *\r
- * <p>The meanings of the substitution token characters are as follows:</p>\r
- *\r
- * <table border="0" width="100%">\r
- * <tr>\r
- * <td width="37"></td>\r
- * <td width="23">>></td>\r
- * <td width="165" valign="top">in normal rule</td>\r
- * <td>Divide the number by the rule's divisor and format the remainder</td>\r
- * </tr>\r
- * <tr>\r
- * <td width="37"></td>\r
- * <td width="23"></td>\r
- * <td width="165" valign="top">in negative-number rule</td>\r
- * <td>Find the absolute value of the number and format the result</td>\r
- * </tr>\r
- * <tr>\r
- * <td width="37"></td>\r
- * <td width="23"></td>\r
- * <td width="165" valign="top">in fraction or master rule</td>\r
- * <td>Isolate the number's fractional part and format it.</td>\r
- * </tr>\r
- * <tr>\r
- * <td width="37"></td>\r
- * <td width="23"></td>\r
- * <td width="165" valign="top">in rule in fraction rule set</td>\r
- * <td>Not allowed.</td>\r
- * </tr>\r
- * <tr>\r
- * <td width="37"></td>\r
- * <td width="23">>>></td>\r
- * <td width="165" valign="top">in normal rule</td>\r
- * <td>Divide the number by the rule's divisor and format the remainder,\r
- * but bypass the normal rule-selection process and just use the\r
- * rule that precedes this one in this rule list.</td>\r
- * </tr>\r
- * <tr>\r
- * <td width="37"></td>\r
- * <td width="23"></td>\r
- * <td width="165" valign="top">in all other rules</td>\r
- * <td>Not allowed.</td>\r
- * </tr>\r
- * <tr>\r
- * <td width="37"></td>\r
- * <td width="23"><<</td>\r
- * <td width="165" valign="top">in normal rule</td>\r
- * <td>Divide the number by the rule's divisor and format the quotient</td>\r
- * </tr>\r
- * <tr>\r
- * <td width="37"></td>\r
- * <td width="23"></td>\r
- * <td width="165" valign="top">in negative-number rule</td>\r
- * <td>Not allowed.</td>\r
- * </tr>\r
- * <tr>\r
- * <td width="37"></td>\r
- * <td width="23"></td>\r
- * <td width="165" valign="top">in fraction or master rule</td>\r
- * <td>Isolate the number's integral part and format it.</td>\r
- * </tr>\r
- * <tr>\r
- * <td width="37"></td>\r
- * <td width="23"></td>\r
- * <td width="165" valign="top">in rule in fraction rule set</td>\r
- * <td>Multiply the number by the rule's base value and format the result.</td>\r
- * </tr>\r
- * <tr>\r
- * <td width="37"></td>\r
- * <td width="23">==</td>\r
- * <td width="165" valign="top">in all rule sets</td>\r
- * <td>Format the number unchanged</td>\r
- * </tr>\r
- * <tr>\r
- * <td width="37"></td>\r
- * <td width="23">[]</td>\r
- * <td width="165" valign="top">in normal rule</td>\r
- * <td>Omit the optional text if the number is an even multiple of the rule's divisor</td>\r
- * </tr>\r
- * <tr>\r
- * <td width="37"></td>\r
- * <td width="23"></td>\r
- * <td width="165" valign="top">in negative-number rule</td>\r
- * <td>Not allowed.</td>\r
- * </tr>\r
- * <tr>\r
- * <td width="37"></td>\r
- * <td width="23"></td>\r
- * <td width="165" valign="top">in improper-fraction rule</td>\r
- * <td>Omit the optional text if the number is between 0 and 1 (same as specifying both an\r
- * x.x rule and a 0.x rule)</td>\r
- * </tr>\r
- * <tr>\r
- * <td width="37"></td>\r
- * <td width="23"></td>\r
- * <td width="165" valign="top">in master rule</td>\r
- * <td>Omit the optional text if the number is an integer (same as specifying both an x.x\r
- * rule and an x.0 rule)</td>\r
- * </tr>\r
- * <tr>\r
- * <td width="37"></td>\r
- * <td width="23"></td>\r
- * <td width="165" valign="top">in proper-fraction rule</td>\r
- * <td>Not allowed.</td>\r
- * </tr>\r
- * <tr>\r
- * <td width="37"></td>\r
- * <td width="23"></td>\r
- * <td width="165" valign="top">in rule in fraction rule set</td>\r
- * <td>Omit the optional text if multiplying the number by the rule's base value yields 1.</td>\r
- * </tr>\r
- * </table>\r
- *\r
- * <p>The substitution descriptor (i.e., the text between the token characters) may take one\r
- * of three forms:</p>\r
- *\r
- * <table border="0" width="100%">\r
- * <tr>\r
- * <td width="42"></td>\r
- * <td width="166" valign="top">a rule set name</td>\r
- * <td>Perform the mathematical operation on the number, and format the result using the\r
- * named rule set.</td>\r
- * </tr>\r
- * <tr>\r
- * <td width="42"></td>\r
- * <td width="166" valign="top">a DecimalFormat pattern</td>\r
- * <td>Perform the mathematical operation on the number, and format the result using a\r
- * DecimalFormat with the specified pattern. The pattern must begin with 0 or #.</td>\r
- * </tr>\r
- * <tr>\r
- * <td width="42"></td>\r
- * <td width="166" valign="top">nothing</td>\r
- * <td>Perform the mathematical operation on the number, and format the result using the rule\r
- * set containing the current rule, except:<ul>\r
- * <li>You can't have an empty substitution descriptor with a == substitution.</li>\r
- * <li>If you omit the substitution descriptor in a >> substitution in a fraction rule,\r
- * format the result one digit at a time using the rule set containing the current rule.</li>\r
- * <li>If you omit the substitution descriptor in a << substitution in a rule in a\r
- * fraction rule set, format the result using the default rule set for this formatter.</li>\r
- * </ul>\r
- * </td>\r
- * </tr>\r
- * </table>\r
- *\r
- * <p>Whitespace is ignored between a rule set name and a rule set body, between a rule\r
- * descriptor and a rule body, or between rules. If a rule body begins with an apostrophe,\r
- * the apostrophe is ignored, but all text after it becomes significant (this is how you can\r
- * have a rule's rule text begin with whitespace). There is no escape function: the semicolon\r
- * is not allowed in rule set names or in rule text, and the colon is not allowed in rule set\r
- * names. The characters beginning a substitution token are always treated as the beginning\r
- * of a substitution token.</p>\r
- *\r
- * <p>See the resource data and the demo program for annotated examples of real rule sets\r
- * using these features.</p>\r
- *\r
- * @author Richard Gillam\r
- * @see NumberFormat\r
- * @see DecimalFormat\r
- * @stable ICU 2.0\r
- */\r
-public class RuleBasedNumberFormat extends NumberFormat {\r
-\r
- //-----------------------------------------------------------------------\r
- // constants\r
- //-----------------------------------------------------------------------\r
-\r
- // Generated by serialver from JDK 1.4.1_01\r
- static final long serialVersionUID = -7664252765575395068L;\r
- \r
- /**\r
- * Selector code that tells the constructor to create a spellout formatter\r
- * @stable ICU 2.0\r
- */\r
- public static final int SPELLOUT = 1;\r
-\r
- /**\r
- * Selector code that tells the constructor to create an ordinal formatter\r
- * @stable ICU 2.0\r
- */\r
- public static final int ORDINAL = 2;\r
-\r
- /**\r
- * Selector code that tells the constructor to create a duration formatter\r
- * @stable ICU 2.0\r
- */\r
- public static final int DURATION = 3;\r
-\r
- /**\r
- * Selector code that tells the constructor to create a numbering system formatter\r
- * @draft ICU 4.2\r
- * @provisional This API might change or be removed in a future release.\r
- */\r
- public static final int NUMBERING_SYSTEM = 4;\r
-\r
- //-----------------------------------------------------------------------\r
- // data members\r
- //-----------------------------------------------------------------------\r
-\r
- /**\r
- * The formatter's rule sets.\r
- */\r
- private transient NFRuleSet[] ruleSets = null;\r
-\r
- /**\r
- * A pointer to the formatter's default rule set. This is always included\r
- * in ruleSets.\r
- */\r
- private transient NFRuleSet defaultRuleSet = null;\r
-\r
- /**\r
- * The formatter's locale. This is used to create DecimalFormatSymbols and\r
- * Collator objects.\r
- * @serial\r
- */\r
- private ULocale locale = null;\r
-\r
- /**\r
- * Collator to be used in lenient parsing. This variable is lazy-evaluated:\r
- * the collator is actually created the first time the client does a parse\r
- * with lenient-parse mode turned on.\r
- */\r
- private transient Collator collator = null;\r
-\r
- /**\r
- * The DecimalFormatSymbols object that any DecimalFormat objects this\r
- * formatter uses should use. This variable is lazy-evaluated: it isn't\r
- * filled in if the rule set never uses a DecimalFormat pattern.\r
- */\r
- private transient DecimalFormatSymbols decimalFormatSymbols = null;\r
- \r
- /**\r
- * The NumberFormat used when lenient parsing numbers. This needs to reflect\r
- * the locale. This is lazy-evaluated, like decimalFormatSymbols. It is\r
- * here so it can be shared by different NFSubstitutions.\r
- */\r
- private transient DecimalFormat decimalFormat = null;\r
-\r
- /**\r
- * Flag specifying whether lenient parse mode is on or off. Off by default.\r
- * @serial\r
- */\r
- private boolean lenientParse = false;\r
-\r
- /**\r
- * If the description specifies lenient-parse rules, they're stored here until\r
- * the collator is created.\r
- */\r
- private transient String lenientParseRules;\r
-\r
- /**\r
- * If the description specifies post-process rules, they're stored here until\r
- * post-processing is required.\r
- */\r
- private transient String postProcessRules;\r
-\r
- /**\r
- * Post processor lazily constructed from the postProcessRules.\r
- */\r
- private transient RBNFPostProcessor postProcessor;\r
-\r
- /**\r
- * Localizations for rule set names.\r
- * @serial\r
- */\r
- private Map ruleSetDisplayNames;\r
-\r
- /**\r
- * The public rule set names;\r
- * @serial\r
- */\r
- private String[] publicRuleSetNames;\r
- \r
- private static final boolean DEBUG = ICUDebug.enabled("rbnf");\r
-\r
- // Temporary workaround - when noParse is true, do noting in parse.\r
- // TODO: We need a real fix - see #6895/#6896\r
- private boolean noParse;\r
- private static final String[] NO_SPELLOUT_PARSE_LANGUAGES = { "ga" };\r
-\r
- //-----------------------------------------------------------------------\r
- // constructors\r
- //-----------------------------------------------------------------------\r
-\r
- /**\r
- * Creates a RuleBasedNumberFormat that behaves according to the description\r
- * passed in. The formatter uses the default locale.\r
- * @param description A description of the formatter's desired behavior.\r
- * See the class documentation for a complete explanation of the description\r
- * syntax.\r
- * @stable ICU 2.0\r
- */\r
- public RuleBasedNumberFormat(String description) {\r
- locale = ULocale.getDefault();\r
- init(description, null);\r
- }\r
-\r
- /**\r
- * Creates a RuleBasedNumberFormat that behaves according to the description\r
- * passed in. The formatter uses the default locale.\r
- * <p>\r
- * The localizations data provides information about the public\r
- * rule sets and their localized display names for different\r
- * locales. The first element in the list is an array of the names\r
- * of the public rule sets. The first element in this array is\r
- * the initial default ruleset. The remaining elements in the\r
- * list are arrays of localizations of the names of the public\r
- * rule sets. Each of these is one longer than the initial array,\r
- * with the first String being the ULocale ID, and the remaining\r
- * Strings being the localizations of the rule set names, in the\r
- * same order as the initial array.\r
- * @param description A description of the formatter's desired behavior.\r
- * See the class documentation for a complete explanation of the description\r
- * syntax.\r
- * @param localizations a list of localizations for the rule set\r
- * names in the description.\r
- * @stable ICU 3.2\r
- */\r
- public RuleBasedNumberFormat(String description, String[][] localizations) {\r
- locale = ULocale.getDefault();\r
- init(description, localizations);\r
- }\r
-\r
- /**\r
- * Creates a RuleBasedNumberFormat that behaves according to the description\r
- * passed in. The formatter uses the specified locale to determine the\r
- * characters to use when formatting in numerals, and to define equivalences\r
- * for lenient parsing.\r
- * @param description A description of the formatter's desired behavior.\r
- * See the class documentation for a complete explanation of the description\r
- * syntax.\r
- * @param locale A locale, which governs which characters are used for\r
- * formatting values in numerals, and which characters are equivalent in\r
- * lenient parsing.\r
- * @stable ICU 2.0\r
- */\r
- public RuleBasedNumberFormat(String description, Locale locale) {\r
- this(description, ULocale.forLocale(locale));\r
- }\r
-\r
- /**\r
- * Creates a RuleBasedNumberFormat that behaves according to the description\r
- * passed in. The formatter uses the specified locale to determine the\r
- * characters to use when formatting in numerals, and to define equivalences\r
- * for lenient parsing.\r
- * @param description A description of the formatter's desired behavior.\r
- * See the class documentation for a complete explanation of the description\r
- * syntax.\r
- * @param locale A locale, which governs which characters are used for\r
- * formatting values in numerals, and which characters are equivalent in\r
- * lenient parsing.\r
- * @stable ICU 3.2\r
- */\r
- public RuleBasedNumberFormat(String description, ULocale locale) {\r
- this.locale = locale;\r
- init(description, null);\r
- }\r
-\r
- /**\r
- * Creates a RuleBasedNumberFormat that behaves according to the description\r
- * passed in. The formatter uses the specified locale to determine the\r
- * characters to use when formatting in numerals, and to define equivalences\r
- * for lenient parsing.\r
- * <p>\r
- * The localizations data provides information about the public\r
- * rule sets and their localized display names for different\r
- * locales. The first element in the list is an array of the names\r
- * of the public rule sets. The first element in this array is\r
- * the initial default ruleset. The remaining elements in the\r
- * list are arrays of localizations of the names of the public\r
- * rule sets. Each of these is one longer than the initial array,\r
- * with the first String being the ULocale ID, and the remaining\r
- * Strings being the localizations of the rule set names, in the\r
- * same order as the initial array.\r
- * @param description A description of the formatter's desired behavior.\r
- * See the class documentation for a complete explanation of the description\r
- * syntax.\r
- * @param localizations a list of localizations for the rule set names in the description.\r
- * @param locale A ulocale that governs which characters are used for\r
- * formatting values in numerals, and determines which characters are equivalent in\r
- * lenient parsing.\r
- * @stable ICU 3.2\r
- */\r
- public RuleBasedNumberFormat(String description, String[][] localizations, ULocale locale) {\r
- this.locale = locale;\r
- init(description, localizations);\r
- }\r
-\r
- /**\r
- * Creates a RuleBasedNumberFormat from a predefined description. The selector\r
- * code choosed among three possible predefined formats: spellout, ordinal,\r
- * and duration.\r
- * @param locale The locale for the formatter.\r
- * @param format A selector code specifying which kind of formatter to create for that\r
- * locale. There are three legal values: SPELLOUT, which creates a formatter that\r
- * spells out a value in words in the desired language, ORDINAL, which attaches\r
- * an ordinal suffix from the desired language to the end of a number (e.g. "123rd"),\r
- * and DURATION, which formats a duration in seconds as hours, minutes, and seconds.\r
- * @stable ICU 2.0\r
- */\r
- public RuleBasedNumberFormat(Locale locale, int format) {\r
- this(ULocale.forLocale(locale), format);\r
- }\r
-\r
- /**\r
- * Creates a RuleBasedNumberFormat from a predefined description. The selector\r
- * code choosed among three possible predefined formats: spellout, ordinal,\r
- * and duration.\r
- * @param locale The locale for the formatter.\r
- * @param format A selector code specifying which kind of formatter to create for that\r
- * locale. There are four legal values: SPELLOUT, which creates a formatter that\r
- * spells out a value in words in the desired language, ORDINAL, which attaches\r
- * an ordinal suffix from the desired language to the end of a number (e.g. "123rd"),\r
- * DURATION, which formats a duration in seconds as hours, minutes, and seconds, and\r
- * NUMBERING_SYSTEM, which is used to invoke rules for alternate numbering\r
- * systems such as the Hebrew numbering system, or for Roman numerals, etc..\r
- * @stable ICU 3.2\r
- */\r
- public RuleBasedNumberFormat(ULocale locale, int format) {\r
- this.locale = locale;\r
-\r
- ICUResourceBundle bundle = (ICUResourceBundle)UResourceBundle.\r
- getBundleInstance(ICUResourceBundle.ICU_RBNF_BASE_NAME, locale);\r
-\r
- // TODO: determine correct actual/valid locale. Note ambiguity\r
- // here -- do actual/valid refer to pattern, DecimalFormatSymbols,\r
- // or Collator?\r
- ULocale uloc = bundle.getULocale();\r
- setLocale(uloc, uloc);\r
-\r
- String description = "";\r
- String[][] localizations = null;\r
-\r
- try {\r
- // For backwards compatability - If we have a pre-4.2 style RBNF resource, attempt to read it.\r
- description = bundle.getString(rulenames[format-1]);\r
- }\r
- catch (MissingResourceException e) {\r
- try {\r
- ICUResourceBundle rules = bundle.getWithFallback("RBNFRules/"+rulenames[format-1]);\r
- UResourceBundleIterator it = rules.getIterator(); \r
- while (it.hasNext()) {\r
- description = description.concat(it.nextString());\r
- }\r
- }\r
- catch (MissingResourceException e1) {\r
- } \r
- }\r
-\r
- try {\r
- UResourceBundle locb = bundle.get(locnames[format-1]);\r
- localizations = new String[locb.getSize()][];\r
- for (int i = 0; i < localizations.length; ++i) {\r
- localizations[i] = locb.get(i).getStringArray();\r
- }\r
- }\r
- catch (MissingResourceException e) {\r
- // might have description and no localizations, or no description...\r
- }\r
-\r
- init(description, localizations);\r
-\r
- //TODO: we need a real fix - see #6895 / #6896\r
- noParse = false;\r
- if (locnames[format-1].equals("SpelloutLocalizations")) {\r
- String lang = locale.getLanguage();\r
- for (int i = 0; i < NO_SPELLOUT_PARSE_LANGUAGES.length; i++) {\r
- if (NO_SPELLOUT_PARSE_LANGUAGES[i].equals(lang)) {\r
- noParse = true;\r
- break;\r
- }\r
- }\r
- }\r
- }\r
-\r
- private static final String[] rulenames = {\r
- "SpelloutRules", "OrdinalRules", "DurationRules", "NumberingSystemRules",\r
- };\r
- private static final String[] locnames = {\r
- "SpelloutLocalizations", "OrdinalLocalizations", "DurationLocalizations", "NumberingSystemLocalizations",\r
- };\r
-\r
- /**\r
- * Creates a RuleBasedNumberFormat from a predefined description. Uses the\r
- * default locale.\r
- * @param format A selector code specifying which kind of formatter to create.\r
- * There are three legal values: SPELLOUT, which creates a formatter that spells\r
- * out a value in words in the default locale's langyage, ORDINAL, which attaches\r
- * an ordinal suffix from the default locale's language to a numeral, and\r
- * DURATION, which formats a duration in seconds as hours, minutes, and seconds.\r
- * or NUMBERING_SYSTEM, which is used for alternate numbering systems such as Hebrew.\r
- * @stable ICU 2.0\r
- */\r
- public RuleBasedNumberFormat(int format) {\r
- this(ULocale.getDefault(), format);\r
- }\r
-\r
- //-----------------------------------------------------------------------\r
- // boilerplate\r
- //-----------------------------------------------------------------------\r
-\r
- /**\r
- * Duplicates this formatter.\r
- * @return A RuleBasedNumberFormat that is equal to this one.\r
- * @stable ICU 2.0\r
- */\r
- public Object clone() {\r
- return super.clone();\r
- }\r
-\r
- /**\r
- * Tests two RuleBasedNumberFormats for equality.\r
- * @param that The formatter to compare against this one.\r
- * @return true if the two formatters have identical behavior.\r
- * @stable ICU 2.0\r
- */\r
- public boolean equals(Object that) {\r
- // if the other object isn't a RuleBasedNumberFormat, that's\r
- // all we need to know\r
- if (!(that instanceof RuleBasedNumberFormat)) {\r
- return false;\r
- } else {\r
- // cast the other object's pointer to a pointer to a\r
- // RuleBasedNumberFormat\r
- RuleBasedNumberFormat that2 = (RuleBasedNumberFormat)that;\r
-\r
- // compare their locales and lenient-parse modes\r
- if (!locale.equals(that2.locale) || lenientParse != that2.lenientParse) {\r
- return false;\r
- }\r
-\r
- // if that succeeds, then compare their rule set lists\r
- if (ruleSets.length != that2.ruleSets.length) {\r
- return false;\r
- }\r
- for (int i = 0; i < ruleSets.length; i++) {\r
- if (!ruleSets[i].equals(that2.ruleSets[i])) {\r
- return false;\r
- }\r
- }\r
-\r
- return true;\r
- }\r
- }\r
-\r
- /**\r
- * Generates a textual description of this formatter.\r
- * @return a String containing a rule set that will produce a RuleBasedNumberFormat\r
- * with identical behavior to this one. This won't necessarily be identical\r
- * to the rule set description that was originally passed in, but will produce\r
- * the same result.\r
- * @stable ICU 2.0\r
- */\r
- public String toString() {\r
-\r
- // accumulate the descriptions of all the rule sets in a\r
- // StringBuffer, then cast it to a String and return it\r
- StringBuffer result = new StringBuffer();\r
- for (int i = 0; i < ruleSets.length; i++) {\r
- result.append(ruleSets[i].toString());\r
- }\r
- return result.toString();\r
- }\r
-\r
- /**\r
- * Writes this object to a stream.\r
- * @param out The stream to write to.\r
- */\r
- private void writeObject(java.io.ObjectOutputStream out)\r
- throws java.io.IOException {\r
- // we just write the textual description to the stream, so we\r
- // have an implementation-independent streaming format\r
- out.writeUTF(this.toString());\r
- out.writeObject(this.locale);\r
- }\r
-\r
- /**\r
- * Reads this object in from a stream.\r
- * @param in The stream to read from.\r
- */\r
- private void readObject(java.io.ObjectInputStream in)\r
- throws java.io.IOException {\r
-\r
- // read the description in from the stream\r
- String description = in.readUTF();\r
- ULocale loc;\r
- \r
- try {\r
- loc = (ULocale) in.readObject();\r
- } catch (Exception e) {\r
- loc = ULocale.getDefault();\r
- }\r
-\r
- // build a brand-new RuleBasedNumberFormat from the description,\r
- // then steal its substructure. This object's substructure and\r
- // the temporary RuleBasedNumberFormat drop on the floor and\r
- // get swept up by the garbage collector\r
- RuleBasedNumberFormat temp = new RuleBasedNumberFormat(description, loc);\r
- ruleSets = temp.ruleSets;\r
- defaultRuleSet = temp.defaultRuleSet;\r
- publicRuleSetNames = temp.publicRuleSetNames;\r
- decimalFormatSymbols = temp.decimalFormatSymbols;\r
- decimalFormat = temp.decimalFormat;\r
- locale = temp.locale;\r
- }\r
-\r
-\r
- //-----------------------------------------------------------------------\r
- // public API functions\r
- //-----------------------------------------------------------------------\r
-\r
- /**\r
- * Returns a list of the names of all of this formatter's public rule sets.\r
- * @return A list of the names of all of this formatter's public rule sets.\r
- * @stable ICU 2.0\r
- */\r
- public String[] getRuleSetNames() {\r
- return (String[])publicRuleSetNames.clone();\r
- }\r
-\r
- /**\r
- * Return a list of locales for which there are locale-specific display names\r
- * for the rule sets in this formatter. If there are no localized display names, return null.\r
- * @return an array of the ulocales for which there is rule set display name information\r
- * @stable ICU 3.2\r
- */\r
- public ULocale[] getRuleSetDisplayNameLocales() {\r
- if (ruleSetDisplayNames != null) {\r
- Set s = ruleSetDisplayNames.keySet();\r
- String[] locales = (String[])s.toArray(new String[s.size()]);\r
- Arrays.sort(locales, String.CASE_INSENSITIVE_ORDER);\r
- ULocale[] result = new ULocale[locales.length];\r
- for (int i = 0; i < locales.length; ++i) {\r
- result[i] = new ULocale(locales[i]);\r
- }\r
- return result;\r
- }\r
- return null;\r
- }\r
-\r
- private String[] getNameListForLocale(ULocale loc) {\r
- if (loc != null && ruleSetDisplayNames != null) {\r
- String[] localeNames = { loc.getBaseName(), ULocale.getDefault().getBaseName() };\r
- for (int i = 0; i < localeNames.length; ++i) {\r
- String lname = localeNames[i];\r
- while (lname.length() > 0) {\r
- String[] names = (String[])ruleSetDisplayNames.get(lname);\r
- if (names != null) {\r
- return names;\r
- }\r
- lname = ULocale.getFallback(lname);\r
- }\r
- }\r
- }\r
- return null;\r
- }\r
-\r
- /**\r
- * Return the rule set display names for the provided locale. These are in the same order\r
- * as those returned by getRuleSetNames. The locale is matched against the locales for\r
- * which there is display name data, using normal fallback rules. If no locale matches,\r
- * the default display names are returned. (These are the internal rule set names minus\r
- * the leading '%'.)\r
- * @return an array of the locales that have display name information\r
- * @see #getRuleSetNames\r
- * @stable ICU 3.2\r
- */\r
- public String[] getRuleSetDisplayNames(ULocale loc) {\r
- String[] names = getNameListForLocale(loc);\r
- if (names != null) {\r
- return (String[])names.clone();\r
- }\r
- names = getRuleSetNames();\r
- for (int i = 0; i < names.length; ++i) {\r
- names[i] = names[i].substring(1);\r
- }\r
- return names;\r
- }\r
-\r
- /**\r
- * Return the rule set display names for the current default locale.\r
- * @return an array of the display names\r
- * @see #getRuleSetDisplayNames(ULocale)\r
- * @stable ICU 3.2\r
- */\r
- public String[] getRuleSetDisplayNames() {\r
- return getRuleSetDisplayNames(ULocale.getDefault());\r
- }\r
-\r
- /**\r
- * Return the rule set display name for the provided rule set and locale.\r
- * The locale is matched against the locales for which there is display name data, using\r
- * normal fallback rules. If no locale matches, the default display name is returned.\r
- * @return the display name for the rule set\r
- * @see #getRuleSetDisplayNames\r
- * @throws IllegalArgumentException if ruleSetName is not a valid rule set name for this format\r
- * @stable ICU 3.2\r
- */\r
- public String getRuleSetDisplayName(String ruleSetName, ULocale loc) {\r
- String[] rsnames = publicRuleSetNames;\r
- for (int ix = 0; ix < rsnames.length; ++ix) {\r
- if (rsnames[ix].equals(ruleSetName)) {\r
- String[] names = getNameListForLocale(loc);\r
- if (names != null) {\r
- return names[ix];\r
- }\r
- return rsnames[ix].substring(1);\r
- }\r
- }\r
- throw new IllegalArgumentException("unrecognized rule set name: " + ruleSetName);\r
- }\r
-\r
- /**\r
- * Return the rule set display name for the provided rule set in the current default locale.\r
- * @return the display name for the rule set\r
- * @see #getRuleSetDisplayName(String,ULocale)\r
- * @stable ICU 3.2\r
- */\r
- public String getRuleSetDisplayName(String ruleSetName) {\r
- return getRuleSetDisplayName(ruleSetName, ULocale.getDefault());\r
- }\r
-\r
- /**\r
- * Formats the specified number according to the specified rule set.\r
- * @param number The number to format.\r
- * @param ruleSet The name of the rule set to format the number with.\r
- * This must be the name of a valid public rule set for this formatter.\r
- * @return A textual representation of the number.\r
- * @stable ICU 2.0\r
- */\r
- public String format(double number, String ruleSet) throws IllegalArgumentException {\r
- if (ruleSet.startsWith("%%")) {\r
- throw new IllegalArgumentException("Can't use internal rule set");\r
- }\r
- return format(number, findRuleSet(ruleSet));\r
- }\r
-\r
- /**\r
- * Formats the specified number according to the specified rule set.\r
- * (If the specified rule set specifies a master ["x.0"] rule, this function\r
- * ignores it. Convert the number to a double first if you ned it.) This\r
- * function preserves all the precision in the long-- it doesn't convert it\r
- * to a double.\r
- * @param number The number to format.\r
- * @param ruleSet The name of the rule set to format the number with.\r
- * This must be the name of a valid public rule set for this formatter.\r
- * @return A textual representation of the number.\r
- * @stable ICU 2.0\r
- */\r
- public String format(long number, String ruleSet) throws IllegalArgumentException {\r
- if (ruleSet.startsWith("%%")) {\r
- throw new IllegalArgumentException("Can't use internal rule set");\r
- }\r
- return format(number, findRuleSet(ruleSet));\r
- }\r
-\r
- /**\r
- * Formats the specified number using the formatter's default rule set.\r
- * (The default rule set is the last public rule set defined in the description.)\r
- * @param number The number to format.\r
- * @param toAppendTo A StringBuffer that the result should be appended to.\r
- * @param ignore This function doesn't examine or update the field position.\r
- * @return toAppendTo\r
- * @stable ICU 2.0\r
- */\r
- public StringBuffer format(double number,\r
- StringBuffer toAppendTo,\r
- FieldPosition ignore) {\r
- // this is one of the inherited format() methods. Since it doesn't\r
- // have a way to select the rule set to use, it just uses the\r
- // default one\r
- toAppendTo.append(format(number, defaultRuleSet));\r
- return toAppendTo;\r
- }\r
-\r
- /**\r
- * Formats the specified number using the formatter's default rule set.\r
- * (The default rule set is the last public rule set defined in the description.)\r
- * (If the specified rule set specifies a master ["x.0"] rule, this function\r
- * ignores it. Convert the number to a double first if you ned it.) This\r
- * function preserves all the precision in the long-- it doesn't convert it\r
- * to a double.\r
- * @param number The number to format.\r
- * @param toAppendTo A StringBuffer that the result should be appended to.\r
- * @param ignore This function doesn't examine or update the field position.\r
- * @return toAppendTo\r
- * @stable ICU 2.0\r
- */\r
- public StringBuffer format(long number,\r
- StringBuffer toAppendTo,\r
- FieldPosition ignore) {\r
- // this is one of the inherited format() methods. Since it doesn't\r
- // have a way to select the rule set to use, it just uses the\r
- // default one\r
- toAppendTo.append(format(number, defaultRuleSet));\r
- return toAppendTo;\r
- }\r
-\r
- /**\r
- * <strong><font face=helvetica color=red>NEW</font></strong>\r
- * Implement com.ibm.icu.text.NumberFormat:\r
- * Format a BigInteger.\r
- * @stable ICU 2.0\r
- */\r
- public StringBuffer format(BigInteger number,\r
- StringBuffer toAppendTo,\r
- FieldPosition pos) {\r
- return format(new com.ibm.icu.math.BigDecimal(number), toAppendTo, pos);\r
- }\r
-\r
-//#if defined(FOUNDATION10)\r
-//#else\r
- /**\r
- * <strong><font face=helvetica color=red>NEW</font></strong>\r
- * Implement com.ibm.icu.text.NumberFormat:\r
- * Format a BigDecimal.\r
- * @stable ICU 2.0\r
- */\r
- public StringBuffer format(java.math.BigDecimal number,\r
- StringBuffer toAppendTo,\r
- FieldPosition pos) {\r
- return format(new com.ibm.icu.math.BigDecimal(number), toAppendTo, pos);\r
- }\r
-//#endif\r
-\r
- /**\r
- * <strong><font face=helvetica color=red>NEW</font></strong>\r
- * Implement com.ibm.icu.text.NumberFormat:\r
- * Format a BigDecimal.\r
- * @stable ICU 2.0\r
- */\r
- public StringBuffer format(com.ibm.icu.math.BigDecimal number,\r
- StringBuffer toAppendTo,\r
- FieldPosition pos) {\r
- // TEMPORARY:\r
- return format(number.doubleValue(), toAppendTo, pos);\r
- }\r
-\r
- /**\r
- * Parses the specfied string, beginning at the specified position, according\r
- * to this formatter's rules. This will match the string against all of the\r
- * formatter's public rule sets and return the value corresponding to the longest\r
- * parseable substring. This function's behavior is affected by the lenient\r
- * parse mode.\r
- * @param text The string to parse\r
- * @param parsePosition On entry, contains the position of the first character\r
- * in "text" to examine. On exit, has been updated to contain the position\r
- * of the first character in "text" that wasn't consumed by the parse.\r
- * @return The number that corresponds to the parsed text. This will be an\r
- * instance of either Long or Double, depending on whether the result has a\r
- * fractional part.\r
- * @see #setLenientParseMode\r
- * @stable ICU 2.0\r
- */\r
- public Number parse(String text, ParsePosition parsePosition) {\r
-\r
- //TODO: We need a real fix. See #6895 / #6896\r
- if (noParse) {\r
- // skip parsing\r
- return new Long(0);\r
- }\r
-\r
- // parsePosition tells us where to start parsing. We copy the\r
- // text in the string from here to the end inro a new string,\r
- // and create a new ParsePosition and result variable to use\r
- // for the duration of the parse operation\r
- String workingText = text.substring(parsePosition.getIndex());\r
- ParsePosition workingPos = new ParsePosition(0);\r
- Number tempResult = null;\r
-\r
- // keep track of the largest number of characters consumed in\r
- // the various trials, and the result that corresponds to it\r
- Number result = new Long(0);\r
- ParsePosition highWaterMark = new ParsePosition(workingPos.getIndex());\r
-\r
- // iterate over the public rule sets (beginning with the default one)\r
- // and try parsing the text with each of them. Keep track of which\r
- // one consumes the most characters: that's the one that determines\r
- // the result we return\r
- for (int i = ruleSets.length - 1; i >= 0; i--) {\r
- // skip private rule sets\r
- if (!ruleSets[i].isPublic() || !ruleSets[i].isParseable()) {\r
- continue;\r
- }\r
-\r
- // try parsing the string with the rule set. If it gets past the\r
- // high-water mark, update the high-water mark and the result\r
- tempResult = ruleSets[i].parse(workingText, workingPos, Double.MAX_VALUE);\r
- if (workingPos.getIndex() > highWaterMark.getIndex()) {\r
- result = tempResult;\r
- highWaterMark.setIndex(workingPos.getIndex());\r
- }\r
- // commented out because this API on ParsePosition doesn't exist in 1.1.x\r
- // if (workingPos.getErrorIndex() > highWaterMark.getErrorIndex()) {\r
- // highWaterMark.setErrorIndex(workingPos.getErrorIndex());\r
- // }\r
-\r
- // if we manage to use up all the characters in the string,\r
- // we don't have to try any more rule sets\r
- if (highWaterMark.getIndex() == workingText.length()) {\r
- break;\r
- }\r
-\r
- // otherwise, reset our internal parse position to the\r
- // beginning and try again with the next rule set\r
- workingPos.setIndex(0);\r
- }\r
-\r
- // add the high water mark to our original parse position and\r
- // return the result\r
- parsePosition.setIndex(parsePosition.getIndex() + highWaterMark.getIndex());\r
- // commented out because this API on ParsePosition doesn't exist in 1.1.x\r
- // if (highWaterMark.getIndex() == 0) {\r
- // parsePosition.setErrorIndex(parsePosition.getIndex() + highWaterMark.getErrorIndex());\r
- // }\r
- return result;\r
- }\r
-\r
- /**\r
- * Turns lenient parse mode on and off.\r
- *\r
- * When in lenient parse mode, the formatter uses a Collator for parsing the text.\r
- * Only primary differences are treated as significant. This means that case\r
- * differences, accent differences, alternate spellings of the same letter\r
- * (e.g., ae and a-umlaut in German), ignorable characters, etc. are ignored in\r
- * matching the text. In many cases, numerals will be accepted in place of words\r
- * or phrases as well.\r
- *\r
- * For example, all of the following will correctly parse as 255 in English in\r
- * lenient-parse mode:\r
- * <br>"two hundred fifty-five"\r
- * <br>"two hundred fifty five"\r
- * <br>"TWO HUNDRED FIFTY-FIVE"\r
- * <br>"twohundredfiftyfive"\r
- * <br>"2 hundred fifty-5"\r
- *\r
- * The Collator used is determined by the locale that was\r
- * passed to this object on construction. The description passed to this object\r
- * on construction may supply additional collation rules that are appended to the\r
- * end of the default collator for the locale, enabling additional equivalences\r
- * (such as adding more ignorable characters or permitting spelled-out version of\r
- * symbols; see the demo program for examples).\r
- *\r
- * It's important to emphasize that even strict parsing is relatively lenient: it\r
- * will accept some text that it won't produce as output. In English, for example,\r
- * it will correctly parse "two hundred zero" and "fifteen hundred".\r
- *\r
- * @param enabled If true, turns lenient-parse mode on; if false, turns it off.\r
- * @see RuleBasedCollator\r
- * @stable ICU 2.0\r
- */\r
- public void setLenientParseMode(boolean enabled) {\r
- lenientParse = enabled;\r
-\r
- // if we're leaving lenient-parse mode, throw away the collator\r
- // we've been using\r
- if (!enabled) {\r
- collator = null;\r
- }\r
- }\r
-\r
- /**\r
- * Returns true if lenient-parse mode is turned on. Lenient parsing is off\r
- * by default.\r
- * @return true if lenient-parse mode is turned on.\r
- * @see #setLenientParseMode\r
- * @stable ICU 2.0\r
- */\r
- public boolean lenientParseEnabled() {\r
- return lenientParse;\r
- }\r
-\r
- /**\r
- * Override the default rule set to use. If ruleSetName is null, reset\r
- * to the initial default rule set.\r
- * @param ruleSetName the name of the rule set, or null to reset the initial default.\r
- * @throws IllegalArgumentException if ruleSetName is not the name of a public ruleset.\r
- * @stable ICU 2.0\r
- */\r
- public void setDefaultRuleSet(String ruleSetName) {\r
- if (ruleSetName == null) {\r
- if (publicRuleSetNames.length > 0) {\r
- defaultRuleSet = findRuleSet(publicRuleSetNames[0]);\r
- } else {\r
- defaultRuleSet = null;\r
- int n = ruleSets.length;\r
- while (--n >= 0) {\r
- String currentName = ruleSets[n].getName();\r
- if (currentName.equals("%spellout-numbering") || currentName.equals("%digits-ordinal") || currentName.equals("%duration")) {\r
- defaultRuleSet = ruleSets[n];\r
- return;\r
- } \r
- }\r
-\r
- n = ruleSets.length;\r
- while (--n >= 0) {\r
- if (ruleSets[n].isPublic()) {\r
- defaultRuleSet = ruleSets[n];\r
- break;\r
- }\r
- }\r
- }\r
- } else if (ruleSetName.startsWith("%%")) {\r
- throw new IllegalArgumentException("cannot use private rule set: " + ruleSetName);\r
- } else {\r
- defaultRuleSet = findRuleSet(ruleSetName);\r
- }\r
- }\r
-\r
- /**\r
- * Return the name of the current default rule set.\r
- * @return the name of the current default rule set, if it is public, else the empty string.\r
- * @stable ICU 3.0\r
- */\r
- public String getDefaultRuleSetName() {\r
- if (defaultRuleSet != null && defaultRuleSet.isPublic()) {\r
- return defaultRuleSet.getName();\r
- }\r
- return "";\r
- }\r
-\r
- //-----------------------------------------------------------------------\r
- // package-internal API\r
- //-----------------------------------------------------------------------\r
-\r
- /**\r
- * Returns a reference to the formatter's default rule set. The default\r
- * rule set is the last public rule set in the description, or the one\r
- * most recently set by setDefaultRuleSet.\r
- * @return The formatter's default rule set.\r
- */\r
- NFRuleSet getDefaultRuleSet() {\r
- return defaultRuleSet;\r
- }\r
-\r
- /**\r
- * Returns the collator to use for lenient parsing. The collator is lazily created:\r
- * this function creates it the first time it's called.\r
- * @return The collator to use for lenient parsing, or null if lenient parsing\r
- * is turned off.\r
- */\r
- Collator getCollator() {\r
- // lazy-evaulate the collator\r
- if (collator == null && lenientParse) {\r
- try {\r
- // create a default collator based on the formatter's locale,\r
- // then pull out that collator's rules, append any additional\r
- // rules specified in the description, and create a _new_\r
- // collator based on the combinaiton of those rules\r
- RuleBasedCollator temp = (RuleBasedCollator)Collator.getInstance(locale);\r
- String rules = temp.getRules() + (lenientParseRules == null ? "" : lenientParseRules);\r
-\r
- collator = new RuleBasedCollator(rules);\r
- collator.setDecomposition(Collator.CANONICAL_DECOMPOSITION);\r
- }\r
- catch (Exception e) {\r
- // If we get here, it means we have a malformed set of\r
- // collation rules, which hopefully won't happen\r
- if(DEBUG){\r
- e.printStackTrace();\r
- }\r
- collator = null;\r
- }\r
- }\r
-\r
- // if lenient-parse mode is off, this will be null\r
- // (see setLenientParseMode())\r
- return collator;\r
- }\r
-\r
- /**\r
- * Returns the DecimalFormatSymbols object that should be used by all DecimalFormat\r
- * instances owned by this formatter. This object is lazily created: this function\r
- * creates it the first time it's called.\r
- * @return The DecimalFormatSymbols object that should be used by all DecimalFormat\r
- * instances owned by this formatter.\r
- */\r
- DecimalFormatSymbols getDecimalFormatSymbols() {\r
- // lazy-evaluate the DecimalFormatSymbols object. This object\r
- // is shared by all DecimalFormat instances belonging to this\r
- // formatter\r
- if (decimalFormatSymbols == null) {\r
- decimalFormatSymbols = new DecimalFormatSymbols(locale);\r
- }\r
- return decimalFormatSymbols;\r
- }\r
- \r
- DecimalFormat getDecimalFormat() {\r
- if (decimalFormat == null) {\r
- decimalFormat = (DecimalFormat)NumberFormat.getInstance(locale);\r
- }\r
- return decimalFormat;\r
- }\r
-\r
- //-----------------------------------------------------------------------\r
- // construction implementation\r
- //-----------------------------------------------------------------------\r
-\r
- /**\r
- * This extracts the special information from the rule sets before the\r
- * main parsing starts. Extra whitespace must have already been removed\r
- * from the description. If found, the special information is removed from the\r
- * description and returned, otherwise the description is unchanged and null\r
- * is returned. Note: the trailing semicolon at the end of the special\r
- * rules is stripped.\r
- * @param description the rbnf description with extra whitespace removed\r
- * @param specialName the name of the special rule text to extract\r
- * @return the special rule text, or null if the rule was not found\r
- */\r
- private String extractSpecial(StringBuffer description, String specialName) {\r
- String result = null;\r
- int lp = Utility.indexOf(description, specialName);\r
- if (lp != -1) {\r
- // we've got to make sure we're not in the middle of a rule\r
- // (where specialName would actually get treated as\r
- // rule text)\r
- if (lp == 0 || description.charAt(lp - 1) == ';') {\r
- // locate the beginning and end of the actual special\r
- // rules (there may be whitespace between the name and\r
- // the first token in the description)\r
- int lpEnd = Utility.indexOf(description, ";%", lp);\r
-\r
- if (lpEnd == -1) {\r
- lpEnd = description.length() - 1; // later we add 1 back to get the '%'\r
- }\r
- int lpStart = lp + specialName.length();\r
- while (lpStart < lpEnd &&\r
- UCharacterProperty.isRuleWhiteSpace(description.charAt(lpStart))) {\r
- ++lpStart;\r
- }\r
-\r
- // copy out the special rules\r
- result = description.substring(lpStart, lpEnd);\r
-\r
- // remove the special rule from the description\r
- description.delete(lp, lpEnd+1); // delete the semicolon but not the '%'\r
- }\r
- }\r
- return result;\r
- }\r
-\r
- /**\r
- * This function parses the description and uses it to build all of\r
- * internal data structures that the formatter uses to do formatting\r
- * @param description The description of the formatter's desired behavior.\r
- * This is either passed in by the caller or loaded out of a resource\r
- * by one of the constructors, and is in the description format specified\r
- * in the class docs.\r
- */\r
- private void init(String description, String[][] localizations) {\r
- initLocalizations(localizations);\r
-\r
- // start by stripping the trailing whitespace from all the rules\r
- // (this is all the whitespace follwing each semicolon in the\r
- // description). This allows us to look for rule-set boundaries\r
- // by searching for ";%" without having to worry about whitespace\r
- // between the ; and the %\r
- StringBuffer descBuf = stripWhitespace(description);\r
-\r
- // check to see if there's a set of lenient-parse rules. If there\r
- // is, pull them out into our temporary holding place for them,\r
- // and delete them from the description before the real desciption-\r
- // parsing code sees them\r
-\r
- lenientParseRules = extractSpecial(descBuf, "%%lenient-parse:");\r
- postProcessRules = extractSpecial(descBuf, "%%post-process:");\r
-\r
- // pre-flight parsing the description and count the number of\r
- // rule sets (";%" marks the end of one rule set and the beginning\r
- // of the next)\r
- int numRuleSets = 0;\r
- for (int p = Utility.indexOf(descBuf, ";%"); p != -1; p = Utility.indexOf(descBuf, ";%", p)) {\r
- ++numRuleSets;\r
- ++p;\r
- }\r
- ++numRuleSets;\r
-\r
- // our rule list is an array of the apprpriate size\r
- ruleSets = new NFRuleSet[numRuleSets];\r
-\r
- // divide up the descriptions into individual rule-set descriptions\r
- // and store them in a temporary array. At each step, we also\r
- // new up a rule set, but all this does is initialize its name\r
- // and remove it from its description. We can't actually parse\r
- // the rest of the descriptions and finish initializing everything\r
- // because we have to know the names and locations of all the rule\r
- // sets before we can actually set everything up\r
- String[] ruleSetDescriptions = new String[numRuleSets];\r
-\r
- int curRuleSet = 0;\r
- int start = 0;\r
- for (int p = Utility.indexOf(descBuf, ";%"); p != -1; p = Utility.indexOf(descBuf, ";%", start)) {\r
- ruleSetDescriptions[curRuleSet] = descBuf.substring(start, p + 1);\r
- ruleSets[curRuleSet] = new NFRuleSet(ruleSetDescriptions, curRuleSet);\r
- ++curRuleSet;\r
- start = p + 1;\r
- }\r
- ruleSetDescriptions[curRuleSet] = descBuf.substring(start);\r
- ruleSets[curRuleSet] = new NFRuleSet(ruleSetDescriptions, curRuleSet);\r
-\r
- // now we can take note of the formatter's default rule set, which\r
- // is the last public rule set in the description (it's the last\r
- // rather than the first so that a user can create a new formatter\r
- // from an existing formatter and change its default bevhaior just\r
- // by appending more rule sets to the end)\r
-\r
- // {dlf} Initialization of a fraction rule set requires the default rule\r
- // set to be known. For purposes of initialization, this is always the\r
- // last public rule set, no matter what the localization data says.\r
-\r
- // Set the default ruleset to the last public ruleset, unless one of the predefined\r
- // ruleset names %spellout-numbering, %digits-ordinal, or %duration is found\r
-\r
- boolean defaultNameFound = false; \r
- int n = ruleSets.length;\r
- defaultRuleSet = ruleSets[ruleSets.length - 1];\r
-\r
- while (--n >= 0) {\r
- String currentName = ruleSets[n].getName();\r
- if (currentName.equals("%spellout-numbering") || currentName.equals("%digits-ordinal") || currentName.equals("%duration")) {\r
- defaultRuleSet = ruleSets[n];\r
- defaultNameFound = true; \r
- break;\r
- } \r
- }\r
-\r
- if ( !defaultNameFound ) {\r
- for (int i = ruleSets.length - 1; i >= 0; --i) {\r
- if (!ruleSets[i].getName().startsWith("%%")) {\r
- defaultRuleSet = ruleSets[i];\r
- break;\r
- }\r
- }\r
- }\r
-\r
- // finally, we can go back through the temporary descriptions\r
- // list and finish seting up the substructure (and we throw\r
- // away the temporary descriptions as we go)\r
- for (int i = 0; i < ruleSets.length; i++) {\r
- ruleSets[i].parseRules(ruleSetDescriptions[i], this);\r
- ruleSetDescriptions[i] = null;\r
- }\r
-\r
- // Now that the rules are initialized, the 'real' default rule\r
- // set can be adjusted by the localization data.\r
-\r
- // count the number of public rule sets\r
- // (public rule sets have names that begin with % instead of %%)\r
- int publicRuleSetCount = 0;\r
- for (int i = 0; i < ruleSets.length; i++) {\r
- if (!ruleSets[i].getName().startsWith("%%")) {\r
- ++publicRuleSetCount;\r
- }\r
- }\r
-\r
- // prepare an array of the proper size and copy the names into it\r
- String[] publicRuleSetTemp = new String[publicRuleSetCount];\r
- publicRuleSetCount = 0;\r
- for (int i = ruleSets.length - 1; i >= 0; i--) {\r
- if (!ruleSets[i].getName().startsWith("%%")) {\r
- publicRuleSetTemp[publicRuleSetCount++] = ruleSets[i].getName();\r
- }\r
- }\r
-\r
- if (publicRuleSetNames != null) {\r
- // confirm the names, if any aren't in the rules, that's an error\r
- // it is ok if the rules contain public rule sets that are not in this list\r
- loop: for (int i = 0; i < publicRuleSetNames.length; ++i) {\r
- String name = publicRuleSetNames[i];\r
- for (int j = 0; j < publicRuleSetTemp.length; ++j) {\r
- if (name.equals(publicRuleSetTemp[j])) {\r
- continue loop;\r
- }\r
- }\r
- throw new IllegalArgumentException("did not find public rule set: " + name);\r
- }\r
-\r
- defaultRuleSet = findRuleSet(publicRuleSetNames[0]); // might be different\r
- } else {\r
- publicRuleSetNames = publicRuleSetTemp;\r
- }\r
- }\r
-\r
- /**\r
- * Take the localizations array and create a Map from the locale strings to\r
- * the localization arrays.\r
- */\r
- private void initLocalizations(String[][] localizations) {\r
- if (localizations != null) {\r
- publicRuleSetNames = (String[])localizations[0].clone();\r
-\r
- Map m = new HashMap();\r
- for (int i = 1; i < localizations.length; ++i) {\r
- String[] data = localizations[i];\r
- String loc = data[0];\r
- String[] names = new String[data.length-1];\r
- if (names.length != publicRuleSetNames.length) {\r
- throw new IllegalArgumentException("public name length: " + publicRuleSetNames.length +\r
- " != localized names[" + i + "] length: " + names.length);\r
- }\r
- System.arraycopy(data, 1, names, 0, names.length);\r
- m.put(loc, names);\r
- }\r
-\r
- if (!m.isEmpty()) {\r
- ruleSetDisplayNames = m;\r
- }\r
- }\r
- }\r
-\r
- /**\r
- * This function is used by init() to strip whitespace between rules (i.e.,\r
- * after semicolons).\r
- * @param description The formatter description\r
- * @return The description with all the whitespace that follows semicolons\r
- * taken out.\r
- */\r
- private StringBuffer stripWhitespace(String description) {\r
- // since we don't have a method that deletes characters (why?!!)\r
- // create a new StringBuffer to copy the text into\r
- StringBuffer result = new StringBuffer();\r
-\r
- // iterate through the characters...\r
- int start = 0;\r
- while (start != -1 && start < description.length()) {\r
- // seek to the first non-whitespace character...\r
- while (start < description.length()\r
- && UCharacterProperty.isRuleWhiteSpace(description.charAt(start))) {\r
- ++start;\r
- }\r
-\r
- //if the first non-whitespace character is semicolon, skip it and continue\r
- if (start < description.length() && description.charAt(start) == ';') {\r
- start += 1;\r
- continue;\r
- }\r
-\r
- // locate the next semicolon in the text and copy the text from\r
- // our current position up to that semicolon into the result\r
- int p;\r
- p = description.indexOf(';', start);\r
- if (p == -1) {\r
- // or if we don't find a semicolon, just copy the rest of\r
- // the string into the result\r
- result.append(description.substring(start));\r
- start = -1;\r
- }\r
- else if (p < description.length()) {\r
- result.append(description.substring(start, p + 1));\r
- start = p + 1;\r
- }\r
-\r
- // when we get here, we've seeked off the end of the sring, and\r
- // we terminate the loop (we continue until *start* is -1 rather\r
- // than until *p* is -1, because otherwise we'd miss the last\r
- // rule in the description)\r
- else {\r
- start = -1;\r
- }\r
- }\r
- return result;\r
- }\r
-\r
-// /**\r
-// * This function is called ONLY DURING CONSTRUCTION to fill in the\r
-// * defaultRuleSet variable once we've set up all the rule sets.\r
-// * The default rule set is the last public rule set in the description.\r
-// * (It's the last rather than the first so that a caller can append\r
-// * text to the end of an existing formatter description to change its\r
-// * behavior.)\r
-// */\r
-// private void initDefaultRuleSet() {\r
-// // seek backward from the end of the list until we reach a rule set\r
-// // whose name DOESN'T begin with %%. That's the default rule set\r
-// for (int i = ruleSets.length - 1; i >= 0; --i) {\r
-// if (!ruleSets[i].getName().startsWith("%%")) {\r
-// defaultRuleSet = ruleSets[i];\r
-// return;\r
-// }\r
-// }\r
-// defaultRuleSet = ruleSets[ruleSets.length - 1];\r
-// }\r
-\r
- //-----------------------------------------------------------------------\r
- // formatting implementation\r
- //-----------------------------------------------------------------------\r
-\r
- /**\r
- * Bottleneck through which all the public format() methods\r
- * that take a double pass. By the time we get here, we know\r
- * which rule set we're using to do the formatting.\r
- * @param number The number to format\r
- * @param ruleSet The rule set to use to format the number\r
- * @return The text that resulted from formatting the number\r
- */\r
- private String format(double number, NFRuleSet ruleSet) {\r
- // all API format() routines that take a double vector through\r
- // here. Create an empty string buffer where the result will\r
- // be built, and pass it to the rule set (along with an insertion\r
- // position of 0 and the number being formatted) to the rule set\r
- // for formatting\r
- StringBuffer result = new StringBuffer();\r
- ruleSet.format(number, result, 0);\r
- postProcess(result, ruleSet);\r
- return result.toString();\r
- }\r
-\r
- /**\r
- * Bottleneck through which all the public format() methods\r
- * that take a long pass. By the time we get here, we know\r
- * which rule set we're using to do the formatting.\r
- * @param number The number to format\r
- * @param ruleSet The rule set to use to format the number\r
- * @return The text that resulted from formatting the number\r
- */\r
- private String format(long number, NFRuleSet ruleSet) {\r
- // all API format() routines that take a double vector through\r
- // here. We have these two identical functions-- one taking a\r
- // double and one taking a long-- the couple digits of precision\r
- // that long has but double doesn't (both types are 8 bytes long,\r
- // but double has to borrow some of the mantissa bits to hold\r
- // the exponent).\r
- // Create an empty string buffer where the result will\r
- // be built, and pass it to the rule set (along with an insertion\r
- // position of 0 and the number being formatted) to the rule set\r
- // for formatting\r
- StringBuffer result = new StringBuffer();\r
- ruleSet.format(number, result, 0);\r
- postProcess(result, ruleSet);\r
- return result.toString();\r
- }\r
-\r
- /**\r
- * Post-process the rules if we have a post-processor.\r
- */\r
- private void postProcess(StringBuffer result, NFRuleSet ruleSet) {\r
- if (postProcessRules != null) {\r
- if (postProcessor == null) {\r
- int ix = postProcessRules.indexOf(";");\r
- if (ix == -1) {\r
- ix = postProcessRules.length();\r
- }\r
- String ppClassName = postProcessRules.substring(0, ix).trim();\r
- try {\r
- Class cls = Class.forName(ppClassName);\r
- postProcessor = (RBNFPostProcessor)cls.newInstance();\r
- postProcessor.init(this, postProcessRules);\r
- }\r
- catch (Exception e) {\r
- // if debug, print it out\r
- if (DEBUG) System.out.println("could not locate " + ppClassName + ", error " +\r
- e.getClass().getName() + ", " + e.getMessage());\r
- postProcessor = null;\r
- postProcessRules = null; // don't try again\r
- return;\r
- }\r
- }\r
-\r
- postProcessor.process(result, ruleSet);\r
- }\r
- }\r
-\r
- /**\r
- * Returns the named rule set. Throws an IllegalArgumentException\r
- * if this formatter doesn't have a rule set with that name.\r
- * @param name The name of the desired rule set\r
- * @return The rule set with that name\r
- */\r
- NFRuleSet findRuleSet(String name) throws IllegalArgumentException {\r
- for (int i = 0; i < ruleSets.length; i++) {\r
- if (ruleSets[i].getName().equals(name)) {\r
- return ruleSets[i];\r
- }\r
- }\r
- throw new IllegalArgumentException("No rule set named " + name);\r
- }\r
-}\r
+//##header J2SE15
+/*
+ *******************************************************************************
+ * Copyright (C) 1996-2009, International Business Machines Corporation and *
+ * others. All Rights Reserved. *
+ *******************************************************************************
+ */
+
+package com.ibm.icu.text;
+
+import com.ibm.icu.impl.ICUDebug;
+import com.ibm.icu.impl.ICUResourceBundle;
+import com.ibm.icu.impl.UCharacterProperty;
+import com.ibm.icu.impl.Utility;
+import com.ibm.icu.util.ULocale;
+import com.ibm.icu.util.UResourceBundle;
+import com.ibm.icu.util.UResourceBundleIterator;
+
+import java.math.BigInteger;
+import java.text.FieldPosition;
+import java.text.ParsePosition;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.Locale;
+import java.util.Map;
+import java.util.MissingResourceException;
+import java.util.Set;
+
+
+/**
+ * <p>A class that formats numbers according to a set of rules. This number formatter is
+ * typically used for spelling out numeric values in words (e.g., 25,3476 as
+ * "twenty-five thousand three hundred seventy-six" or "vingt-cinq mille trois
+ * cents soixante-seize" or
+ * "funfundzwanzigtausenddreihundertsechsundsiebzig"), but can also be used for
+ * other complicated formatting tasks, such as formatting a number of seconds as hours,
+ * minutes and seconds (e.g., 3,730 as "1:02:10").</p>
+ *
+ * <p>The resources contain three predefined formatters for each locale: spellout, which
+ * spells out a value in words (123 is "one hundred twenty-three"); ordinal, which
+ * appends an ordinal suffix to the end of a numeral (123 is "123rd"); and
+ * duration, which shows a duration in seconds as hours, minutes, and seconds (123 is
+ * "2:03"). The client can also define more specialized <tt>RuleBasedNumberFormat</tt>s
+ * by supplying programmer-defined rule sets.</p>
+ *
+ * <p>The behavior of a <tt>RuleBasedNumberFormat</tt> is specified by a textual description
+ * that is either passed to the constructor as a <tt>String</tt> or loaded from a resource
+ * bundle. In its simplest form, the description consists of a semicolon-delimited list of <em>rules.</em>
+ * Each rule has a string of output text and a value or range of values it is applicable to.
+ * In a typical spellout rule set, the first twenty rules are the words for the numbers from
+ * 0 to 19:</p>
+ *
+ * <pre>zero; one; two; three; four; five; six; seven; eight; nine;
+ * ten; eleven; twelve; thirteen; fourteen; fifteen; sixteen; seventeen; eighteen; nineteen;</pre>
+ *
+ * <p>For larger numbers, we can use the preceding set of rules to format the ones place, and
+ * we only have to supply the words for the multiples of 10:</p>
+ *
+ * <pre>20: twenty[->>];
+ * 30: thirty{->>];
+ * 40: forty[->>];
+ * 50: fifty[->>];
+ * 60: sixty[->>];
+ * 70: seventy[->>];
+ * 80: eighty[->>];
+ * 90: ninety[->>];</pre>
+ *
+ * <p>In these rules, the <em>base value</em> is spelled out explicitly and set off from the
+ * rule's output text with a colon. The rules are in a sorted list, and a rule is applicable
+ * to all numbers from its own base value to one less than the next rule's base value. The
+ * ">>" token is called a <em>substitution</em> and tells the fomatter to
+ * isolate the number's ones digit, format it using this same set of rules, and place the
+ * result at the position of the ">>" token. Text in brackets is omitted if
+ * the number being formatted is an even multiple of 10 (the hyphen is a literal hyphen; 24
+ * is "twenty-four," not "twenty four").</p>
+ *
+ * <p>For even larger numbers, we can actually look up several parts of the number in the
+ * list:</p>
+ *
+ * <pre>100: << hundred[ >>];</pre>
+ *
+ * <p>The "<<" represents a new kind of substitution. The << isolates
+ * the hundreds digit (and any digits to its left), formats it using this same rule set, and
+ * places the result where the "<<" was. Notice also that the meaning of
+ * >> has changed: it now refers to both the tens and the ones digits. The meaning of
+ * both substitutions depends on the rule's base value. The base value determines the rule's <em>divisor,</em>
+ * which is the highest power of 10 that is less than or equal to the base value (the user
+ * can change this). To fill in the substitutions, the formatter divides the number being
+ * formatted by the divisor. The integral quotient is used to fill in the <<
+ * substitution, and the remainder is used to fill in the >> substitution. The meaning
+ * of the brackets changes similarly: text in brackets is omitted if the value being
+ * formatted is an even multiple of the rule's divisor. The rules are applied recursively, so
+ * if a substitution is filled in with text that includes another substitution, that
+ * substitution is also filled in.</p>
+ *
+ * <p>This rule covers values up to 999, at which point we add another rule:</p>
+ *
+ * <pre>1000: << thousand[ >>];</pre>
+ *
+ * <p>Again, the meanings of the brackets and substitution tokens shift because the rule's
+ * base value is a higher power of 10, changing the rule's divisor. This rule can actually be
+ * used all the way up to 999,999. This allows us to finish out the rules as follows:</p>
+ *
+ * <pre>1,000,000: << million[ >>];
+ * 1,000,000,000: << billion[ >>];
+ * 1,000,000,000,000: << trillion[ >>];
+ * 1,000,000,000,000,000: OUT OF RANGE!;</pre>
+ *
+ * <p>Commas, periods, and spaces can be used in the base values to improve legibility and
+ * are ignored by the rule parser. The last rule in the list is customarily treated as an
+ * "overflow rule," applying to everything from its base value on up, and often (as
+ * in this example) being used to print out an error message or default representation.
+ * Notice also that the size of the major groupings in large numbers is controlled by the
+ * spacing of the rules: because in English we group numbers by thousand, the higher rules
+ * are separated from each other by a factor of 1,000.</p>
+ *
+ * <p>To see how these rules actually work in practice, consider the following example:
+ * Formatting 25,430 with this rule set would work like this:</p>
+ *
+ * <table border="0" width="630">
+ * <tr>
+ * <td width="21"></td>
+ * <td width="257" valign="top"><strong><< thousand >></strong></td>
+ * <td width="340" valign="top">[the rule whose base value is 1,000 is applicable to 25,340]</td>
+ * </tr>
+ * <tr>
+ * <td width="21"></td>
+ * <td width="257" valign="top"><strong>twenty->></strong> thousand >></td>
+ * <td width="340" valign="top">[25,340 over 1,000 is 25. The rule for 20 applies.]</td>
+ * </tr>
+ * <tr>
+ * <td width="21"></td>
+ * <td width="257" valign="top">twenty-<strong>five</strong> thousand >></td>
+ * <td width="340" valign="top">[25 mod 10 is 5. The rule for 5 is "five."</td>
+ * </tr>
+ * <tr>
+ * <td width="21"></td>
+ * <td width="257" valign="top">twenty-five thousand <strong><< hundred >></strong></td>
+ * <td width="340" valign="top">[25,340 mod 1,000 is 340. The rule for 100 applies.]</td>
+ * </tr>
+ * <tr>
+ * <td width="21"></td>
+ * <td width="257" valign="top">twenty-five thousand <strong>three</strong> hundred >></td>
+ * <td width="340" valign="top">[340 over 100 is 3. The rule for 3 is "three."]</td>
+ * </tr>
+ * <tr>
+ * <td width="21"></td>
+ * <td width="257" valign="top">twenty-five thousand three hundred <strong>forty</strong></td>
+ * <td width="340" valign="top">[340 mod 100 is 40. The rule for 40 applies. Since 40 divides
+ * evenly by 10, the hyphen and substitution in the brackets are omitted.]</td>
+ * </tr>
+ * </table>
+ *
+ * <p>The above syntax suffices only to format positive integers. To format negative numbers,
+ * we add a special rule:</p>
+ *
+ * <pre>-x: minus >>;</pre>
+ *
+ * <p>This is called a <em>negative-number rule,</em> and is identified by "-x"
+ * where the base value would be. This rule is used to format all negative numbers. the
+ * >> token here means "find the number's absolute value, format it with these
+ * rules, and put the result here."</p>
+ *
+ * <p>We also add a special rule called a <em>fraction rule </em>for numbers with fractional
+ * parts:</p>
+ *
+ * <pre>x.x: << point >>;</pre>
+ *
+ * <p>This rule is used for all positive non-integers (negative non-integers pass through the
+ * negative-number rule first and then through this rule). Here, the << token refers to
+ * the number's integral part, and the >> to the number's fractional part. The
+ * fractional part is formatted as a series of single-digit numbers (e.g., 123.456 would be
+ * formatted as "one hundred twenty-three point four five six").</p>
+ *
+ * <p>To see how this rule syntax is applied to various languages, examine the resource data.</p>
+ *
+ * <p>There is actually much more flexibility built into the rule language than the
+ * description above shows. A formatter may own multiple rule sets, which can be selected by
+ * the caller, and which can use each other to fill in their substitutions. Substitutions can
+ * also be filled in with digits, using a DecimalFormat object. There is syntax that can be
+ * used to alter a rule's divisor in various ways. And there is provision for much more
+ * flexible fraction handling. A complete description of the rule syntax follows:</p>
+ *
+ * <hr>
+ *
+ * <p>The description of a <tt>RuleBasedNumberFormat</tt>'s behavior consists of one or more <em>rule
+ * sets.</em> Each rule set consists of a name, a colon, and a list of <em>rules.</em> A rule
+ * set name must begin with a % sign. Rule sets with names that begin with a single % sign
+ * are <em>public:</em> the caller can specify that they be used to format and parse numbers.
+ * Rule sets with names that begin with %% are <em>private:</em> they exist only for the use
+ * of other rule sets. If a formatter only has one rule set, the name may be omitted.</p>
+ *
+ * <p>The user can also specify a special "rule set" named <tt>%%lenient-parse</tt>.
+ * The body of <tt>%%lenient-parse</tt> isn't a set of number-formatting rules, but a <tt>RuleBasedCollator</tt>
+ * description which is used to define equivalences for lenient parsing. For more information
+ * on the syntax, see <tt>RuleBasedCollator</tt>. For more information on lenient parsing,
+ * see <tt>setLenientParse()</tt>. <em>Note:</em> symbols that have syntactic meaning
+ * in collation rules, such as '&', have no particular meaning when appearing outside
+ * of the <tt>lenient-parse</tt> rule set.</p>
+ *
+ * <p>The body of a rule set consists of an ordered, semicolon-delimited list of <em>rules.</em>
+ * Internally, every rule has a base value, a divisor, rule text, and zero, one, or two <em>substitutions.</em>
+ * These parameters are controlled by the description syntax, which consists of a <em>rule
+ * descriptor,</em> a colon, and a <em>rule body.</em></p>
+ *
+ * <p>A rule descriptor can take one of the following forms (text in <em>italics</em> is the
+ * name of a token):</p>
+ *
+ * <table border="0" width="100%">
+ * <tr>
+ * <td width="5%" valign="top"></td>
+ * <td width="8%" valign="top"><em>bv</em>:</td>
+ * <td valign="top"><em>bv</em> specifies the rule's base value. <em>bv</em> is a decimal
+ * number expressed using ASCII digits. <em>bv</em> may contain spaces, period, and commas,
+ * which are irgnored. The rule's divisor is the highest power of 10 less than or equal to
+ * the base value.</td>
+ * </tr>
+ * <tr>
+ * <td width="5%" valign="top"></td>
+ * <td width="8%" valign="top"><em>bv</em>/<em>rad</em>:</td>
+ * <td valign="top"><em>bv</em> specifies the rule's base value. The rule's divisor is the
+ * highest power of <em>rad</em> less than or equal to the base value.</td>
+ * </tr>
+ * <tr>
+ * <td width="5%" valign="top"></td>
+ * <td width="8%" valign="top"><em>bv</em>>:</td>
+ * <td valign="top"><em>bv</em> specifies the rule's base value. To calculate the divisor,
+ * let the radix be 10, and the exponent be the highest exponent of the radix that yields a
+ * result less than or equal to the base value. Every > character after the base value
+ * decreases the exponent by 1. If the exponent is positive or 0, the divisor is the radix
+ * raised to the power of the exponent; otherwise, the divisor is 1.</td>
+ * </tr>
+ * <tr>
+ * <td width="5%" valign="top"></td>
+ * <td width="8%" valign="top"><em>bv</em>/<em>rad</em>>:</td>
+ * <td valign="top"><em>bv</em> specifies the rule's base value. To calculate the divisor,
+ * let the radix be <em>rad</em>, and the exponent be the highest exponent of the radix that
+ * yields a result less than or equal to the base value. Every > character after the radix
+ * decreases the exponent by 1. If the exponent is positive or 0, the divisor is the radix
+ * raised to the power of the exponent; otherwise, the divisor is 1.</td>
+ * </tr>
+ * <tr>
+ * <td width="5%" valign="top"></td>
+ * <td width="8%" valign="top">-x:</td>
+ * <td valign="top">The rule is a negative-number rule.</td>
+ * </tr>
+ * <tr>
+ * <td width="5%" valign="top"></td>
+ * <td width="8%" valign="top">x.x:</td>
+ * <td valign="top">The rule is an <em>improper fraction rule.</em></td>
+ * </tr>
+ * <tr>
+ * <td width="5%" valign="top"></td>
+ * <td width="8%" valign="top">0.x:</td>
+ * <td valign="top">The rule is a <em>proper fraction rule.</em></td>
+ * </tr>
+ * <tr>
+ * <td width="5%" valign="top"></td>
+ * <td width="8%" valign="top">x.0:</td>
+ * <td valign="top">The rule is a <em>master rule.</em></td>
+ * </tr>
+ * <tr>
+ * <td width="5%" valign="top"></td>
+ * <td width="8%" valign="top"><em>nothing</em></td>
+ * <td valign="top">If the rule's rule descriptor is left out, the base value is one plus the
+ * preceding rule's base value (or zero if this is the first rule in the list) in a normal
+ * rule set. In a fraction rule set, the base value is the same as the preceding rule's
+ * base value.</td>
+ * </tr>
+ * </table>
+ *
+ * <p>A rule set may be either a regular rule set or a <em>fraction rule set,</em> depending
+ * on whether it is used to format a number's integral part (or the whole number) or a
+ * number's fractional part. Using a rule set to format a rule's fractional part makes it a
+ * fraction rule set.</p>
+ *
+ * <p>Which rule is used to format a number is defined according to one of the following
+ * algorithms: If the rule set is a regular rule set, do the following:
+ *
+ * <ul>
+ * <li>If the rule set includes a master rule (and the number was passed in as a <tt>double</tt>),
+ * use the master rule. (If the number being formatted was passed in as a <tt>long</tt>,
+ * the master rule is ignored.)</li>
+ * <li>If the number is negative, use the negative-number rule.</li>
+ * <li>If the number has a fractional part and is greater than 1, use the improper fraction
+ * rule.</li>
+ * <li>If the number has a fractional part and is between 0 and 1, use the proper fraction
+ * rule.</li>
+ * <li>Binary-search the rule list for the rule with the highest base value less than or equal
+ * to the number. If that rule has two substitutions, its base value is not an even multiple
+ * of its divisor, and the number <em>is</em> an even multiple of the rule's divisor, use the
+ * rule that precedes it in the rule list. Otherwise, use the rule itself.</li>
+ * </ul>
+ *
+ * <p>If the rule set is a fraction rule set, do the following:
+ *
+ * <ul>
+ * <li>Ignore negative-number and fraction rules.</li>
+ * <li>For each rule in the list, multiply the number being formatted (which will always be
+ * between 0 and 1) by the rule's base value. Keep track of the distance between the result
+ * the nearest integer.</li>
+ * <li>Use the rule that produced the result closest to zero in the above calculation. In the
+ * event of a tie or a direct hit, use the first matching rule encountered. (The idea here is
+ * to try each rule's base value as a possible denominator of a fraction. Whichever
+ * denominator produces the fraction closest in value to the number being formatted wins.) If
+ * the rule following the matching rule has the same base value, use it if the numerator of
+ * the fraction is anything other than 1; if the numerator is 1, use the original matching
+ * rule. (This is to allow singular and plural forms of the rule text without a lot of extra
+ * hassle.)</li>
+ * </ul>
+ *
+ * <p>A rule's body consists of a string of characters terminated by a semicolon. The rule
+ * may include zero, one, or two <em>substitution tokens,</em> and a range of text in
+ * brackets. The brackets denote optional text (and may also include one or both
+ * substitutions). The exact meanings of the substitution tokens, and under what conditions
+ * optional text is omitted, depend on the syntax of the substitution token and the context.
+ * The rest of the text in a rule body is literal text that is output when the rule matches
+ * the number being formatted.</p>
+ *
+ * <p>A substitution token begins and ends with a <em>token character.</em> The token
+ * character and the context together specify a mathematical operation to be performed on the
+ * number being formatted. An optional <em>substitution descriptor </em>specifies how the
+ * value resulting from that operation is used to fill in the substitution. The position of
+ * the substitution token in the rule body specifies the location of the resultant text in
+ * the original rule text.</p>
+ *
+ * <p>The meanings of the substitution token characters are as follows:</p>
+ *
+ * <table border="0" width="100%">
+ * <tr>
+ * <td width="37"></td>
+ * <td width="23">>></td>
+ * <td width="165" valign="top">in normal rule</td>
+ * <td>Divide the number by the rule's divisor and format the remainder</td>
+ * </tr>
+ * <tr>
+ * <td width="37"></td>
+ * <td width="23"></td>
+ * <td width="165" valign="top">in negative-number rule</td>
+ * <td>Find the absolute value of the number and format the result</td>
+ * </tr>
+ * <tr>
+ * <td width="37"></td>
+ * <td width="23"></td>
+ * <td width="165" valign="top">in fraction or master rule</td>
+ * <td>Isolate the number's fractional part and format it.</td>
+ * </tr>
+ * <tr>
+ * <td width="37"></td>
+ * <td width="23"></td>
+ * <td width="165" valign="top">in rule in fraction rule set</td>
+ * <td>Not allowed.</td>
+ * </tr>
+ * <tr>
+ * <td width="37"></td>
+ * <td width="23">>>></td>
+ * <td width="165" valign="top">in normal rule</td>
+ * <td>Divide the number by the rule's divisor and format the remainder,
+ * but bypass the normal rule-selection process and just use the
+ * rule that precedes this one in this rule list.</td>
+ * </tr>
+ * <tr>
+ * <td width="37"></td>
+ * <td width="23"></td>
+ * <td width="165" valign="top">in all other rules</td>
+ * <td>Not allowed.</td>
+ * </tr>
+ * <tr>
+ * <td width="37"></td>
+ * <td width="23"><<</td>
+ * <td width="165" valign="top">in normal rule</td>
+ * <td>Divide the number by the rule's divisor and format the quotient</td>
+ * </tr>
+ * <tr>
+ * <td width="37"></td>
+ * <td width="23"></td>
+ * <td width="165" valign="top">in negative-number rule</td>
+ * <td>Not allowed.</td>
+ * </tr>
+ * <tr>
+ * <td width="37"></td>
+ * <td width="23"></td>
+ * <td width="165" valign="top">in fraction or master rule</td>
+ * <td>Isolate the number's integral part and format it.</td>
+ * </tr>
+ * <tr>
+ * <td width="37"></td>
+ * <td width="23"></td>
+ * <td width="165" valign="top">in rule in fraction rule set</td>
+ * <td>Multiply the number by the rule's base value and format the result.</td>
+ * </tr>
+ * <tr>
+ * <td width="37"></td>
+ * <td width="23">==</td>
+ * <td width="165" valign="top">in all rule sets</td>
+ * <td>Format the number unchanged</td>
+ * </tr>
+ * <tr>
+ * <td width="37"></td>
+ * <td width="23">[]</td>
+ * <td width="165" valign="top">in normal rule</td>
+ * <td>Omit the optional text if the number is an even multiple of the rule's divisor</td>
+ * </tr>
+ * <tr>
+ * <td width="37"></td>
+ * <td width="23"></td>
+ * <td width="165" valign="top">in negative-number rule</td>
+ * <td>Not allowed.</td>
+ * </tr>
+ * <tr>
+ * <td width="37"></td>
+ * <td width="23"></td>
+ * <td width="165" valign="top">in improper-fraction rule</td>
+ * <td>Omit the optional text if the number is between 0 and 1 (same as specifying both an
+ * x.x rule and a 0.x rule)</td>
+ * </tr>
+ * <tr>
+ * <td width="37"></td>
+ * <td width="23"></td>
+ * <td width="165" valign="top">in master rule</td>
+ * <td>Omit the optional text if the number is an integer (same as specifying both an x.x
+ * rule and an x.0 rule)</td>
+ * </tr>
+ * <tr>
+ * <td width="37"></td>
+ * <td width="23"></td>
+ * <td width="165" valign="top">in proper-fraction rule</td>
+ * <td>Not allowed.</td>
+ * </tr>
+ * <tr>
+ * <td width="37"></td>
+ * <td width="23"></td>
+ * <td width="165" valign="top">in rule in fraction rule set</td>
+ * <td>Omit the optional text if multiplying the number by the rule's base value yields 1.</td>
+ * </tr>
+ * </table>
+ *
+ * <p>The substitution descriptor (i.e., the text between the token characters) may take one
+ * of three forms:</p>
+ *
+ * <table border="0" width="100%">
+ * <tr>
+ * <td width="42"></td>
+ * <td width="166" valign="top">a rule set name</td>
+ * <td>Perform the mathematical operation on the number, and format the result using the
+ * named rule set.</td>
+ * </tr>
+ * <tr>
+ * <td width="42"></td>
+ * <td width="166" valign="top">a DecimalFormat pattern</td>
+ * <td>Perform the mathematical operation on the number, and format the result using a
+ * DecimalFormat with the specified pattern. The pattern must begin with 0 or #.</td>
+ * </tr>
+ * <tr>
+ * <td width="42"></td>
+ * <td width="166" valign="top">nothing</td>
+ * <td>Perform the mathematical operation on the number, and format the result using the rule
+ * set containing the current rule, except:<ul>
+ * <li>You can't have an empty substitution descriptor with a == substitution.</li>
+ * <li>If you omit the substitution descriptor in a >> substitution in a fraction rule,
+ * format the result one digit at a time using the rule set containing the current rule.</li>
+ * <li>If you omit the substitution descriptor in a << substitution in a rule in a
+ * fraction rule set, format the result using the default rule set for this formatter.</li>
+ * </ul>
+ * </td>
+ * </tr>
+ * </table>
+ *
+ * <p>Whitespace is ignored between a rule set name and a rule set body, between a rule
+ * descriptor and a rule body, or between rules. If a rule body begins with an apostrophe,
+ * the apostrophe is ignored, but all text after it becomes significant (this is how you can
+ * have a rule's rule text begin with whitespace). There is no escape function: the semicolon
+ * is not allowed in rule set names or in rule text, and the colon is not allowed in rule set
+ * names. The characters beginning a substitution token are always treated as the beginning
+ * of a substitution token.</p>
+ *
+ * <p>See the resource data and the demo program for annotated examples of real rule sets
+ * using these features.</p>
+ *
+ * @author Richard Gillam
+ * @see NumberFormat
+ * @see DecimalFormat
+ * @stable ICU 2.0
+ */
+public class RuleBasedNumberFormat extends NumberFormat {
+
+ //-----------------------------------------------------------------------
+ // constants
+ //-----------------------------------------------------------------------
+
+ // Generated by serialver from JDK 1.4.1_01
+ static final long serialVersionUID = -7664252765575395068L;
+
+ /**
+ * Selector code that tells the constructor to create a spellout formatter
+ * @stable ICU 2.0
+ */
+ public static final int SPELLOUT = 1;
+
+ /**
+ * Selector code that tells the constructor to create an ordinal formatter
+ * @stable ICU 2.0
+ */
+ public static final int ORDINAL = 2;
+
+ /**
+ * Selector code that tells the constructor to create a duration formatter
+ * @stable ICU 2.0
+ */
+ public static final int DURATION = 3;
+
+ /**
+ * Selector code that tells the constructor to create a numbering system formatter
+ * @draft ICU 4.2
+ * @provisional This API might change or be removed in a future release.
+ */
+ public static final int NUMBERING_SYSTEM = 4;
+
+ //-----------------------------------------------------------------------
+ // data members
+ //-----------------------------------------------------------------------
+
+ /**
+ * The formatter's rule sets.
+ */
+ private transient NFRuleSet[] ruleSets = null;
+
+ /**
+ * A pointer to the formatter's default rule set. This is always included
+ * in ruleSets.
+ */
+ private transient NFRuleSet defaultRuleSet = null;
+
+ /**
+ * The formatter's locale. This is used to create DecimalFormatSymbols and
+ * Collator objects.
+ * @serial
+ */
+ private ULocale locale = null;
+
+ /**
+ * Collator to be used in lenient parsing. This variable is lazy-evaluated:
+ * the collator is actually created the first time the client does a parse
+ * with lenient-parse mode turned on.
+ */
+ private transient Collator collator = null;
+
+ /**
+ * The DecimalFormatSymbols object that any DecimalFormat objects this
+ * formatter uses should use. This variable is lazy-evaluated: it isn't
+ * filled in if the rule set never uses a DecimalFormat pattern.
+ */
+ private transient DecimalFormatSymbols decimalFormatSymbols = null;
+
+ /**
+ * The NumberFormat used when lenient parsing numbers. This needs to reflect
+ * the locale. This is lazy-evaluated, like decimalFormatSymbols. It is
+ * here so it can be shared by different NFSubstitutions.
+ */
+ private transient DecimalFormat decimalFormat = null;
+
+ /**
+ * Flag specifying whether lenient parse mode is on or off. Off by default.
+ * @serial
+ */
+ private boolean lenientParse = false;
+
+ /**
+ * If the description specifies lenient-parse rules, they're stored here until
+ * the collator is created.
+ */
+ private transient String lenientParseRules;
+
+ /**
+ * If the description specifies post-process rules, they're stored here until
+ * post-processing is required.
+ */
+ private transient String postProcessRules;
+
+ /**
+ * Post processor lazily constructed from the postProcessRules.
+ */
+ private transient RBNFPostProcessor postProcessor;
+
+ /**
+ * Localizations for rule set names.
+ * @serial
+ */
+ private Map ruleSetDisplayNames;
+
+ /**
+ * The public rule set names;
+ * @serial
+ */
+ private String[] publicRuleSetNames;
+
+ private static final boolean DEBUG = ICUDebug.enabled("rbnf");
+
+ // Temporary workaround - when noParse is true, do noting in parse.
+ // TODO: We need a real fix - see #6895/#6896
+ private boolean noParse;
+ private static final String[] NO_SPELLOUT_PARSE_LANGUAGES = { "ga" };
+
+ //-----------------------------------------------------------------------
+ // constructors
+ //-----------------------------------------------------------------------
+
+ /**
+ * Creates a RuleBasedNumberFormat that behaves according to the description
+ * passed in. The formatter uses the default locale.
+ * @param description A description of the formatter's desired behavior.
+ * See the class documentation for a complete explanation of the description
+ * syntax.
+ * @stable ICU 2.0
+ */
+ public RuleBasedNumberFormat(String description) {
+ locale = ULocale.getDefault();
+ init(description, null);
+ }
+
+ /**
+ * Creates a RuleBasedNumberFormat that behaves according to the description
+ * passed in. The formatter uses the default locale.
+ * <p>
+ * The localizations data provides information about the public
+ * rule sets and their localized display names for different
+ * locales. The first element in the list is an array of the names
+ * of the public rule sets. The first element in this array is
+ * the initial default ruleset. The remaining elements in the
+ * list are arrays of localizations of the names of the public
+ * rule sets. Each of these is one longer than the initial array,
+ * with the first String being the ULocale ID, and the remaining
+ * Strings being the localizations of the rule set names, in the
+ * same order as the initial array.
+ * @param description A description of the formatter's desired behavior.
+ * See the class documentation for a complete explanation of the description
+ * syntax.
+ * @param localizations a list of localizations for the rule set
+ * names in the description.
+ * @stable ICU 3.2
+ */
+ public RuleBasedNumberFormat(String description, String[][] localizations) {
+ locale = ULocale.getDefault();
+ init(description, localizations);
+ }
+
+ /**
+ * Creates a RuleBasedNumberFormat that behaves according to the description
+ * passed in. The formatter uses the specified locale to determine the
+ * characters to use when formatting in numerals, and to define equivalences
+ * for lenient parsing.
+ * @param description A description of the formatter's desired behavior.
+ * See the class documentation for a complete explanation of the description
+ * syntax.
+ * @param locale A locale, which governs which characters are used for
+ * formatting values in numerals, and which characters are equivalent in
+ * lenient parsing.
+ * @stable ICU 2.0
+ */
+ public RuleBasedNumberFormat(String description, Locale locale) {
+ this(description, ULocale.forLocale(locale));
+ }
+
+ /**
+ * Creates a RuleBasedNumberFormat that behaves according to the description
+ * passed in. The formatter uses the specified locale to determine the
+ * characters to use when formatting in numerals, and to define equivalences
+ * for lenient parsing.
+ * @param description A description of the formatter's desired behavior.
+ * See the class documentation for a complete explanation of the description
+ * syntax.
+ * @param locale A locale, which governs which characters are used for
+ * formatting values in numerals, and which characters are equivalent in
+ * lenient parsing.
+ * @stable ICU 3.2
+ */
+ public RuleBasedNumberFormat(String description, ULocale locale) {
+ this.locale = locale;
+ init(description, null);
+ }
+
+ /**
+ * Creates a RuleBasedNumberFormat that behaves according to the description
+ * passed in. The formatter uses the specified locale to determine the
+ * characters to use when formatting in numerals, and to define equivalences
+ * for lenient parsing.
+ * <p>
+ * The localizations data provides information about the public
+ * rule sets and their localized display names for different
+ * locales. The first element in the list is an array of the names
+ * of the public rule sets. The first element in this array is
+ * the initial default ruleset. The remaining elements in the
+ * list are arrays of localizations of the names of the public
+ * rule sets. Each of these is one longer than the initial array,
+ * with the first String being the ULocale ID, and the remaining
+ * Strings being the localizations of the rule set names, in the
+ * same order as the initial array.
+ * @param description A description of the formatter's desired behavior.
+ * See the class documentation for a complete explanation of the description
+ * syntax.
+ * @param localizations a list of localizations for the rule set names in the description.
+ * @param locale A ulocale that governs which characters are used for
+ * formatting values in numerals, and determines which characters are equivalent in
+ * lenient parsing.
+ * @stable ICU 3.2
+ */
+ public RuleBasedNumberFormat(String description, String[][] localizations, ULocale locale) {
+ this.locale = locale;
+ init(description, localizations);
+ }
+
+ /**
+ * Creates a RuleBasedNumberFormat from a predefined description. The selector
+ * code choosed among three possible predefined formats: spellout, ordinal,
+ * and duration.
+ * @param locale The locale for the formatter.
+ * @param format A selector code specifying which kind of formatter to create for that
+ * locale. There are three legal values: SPELLOUT, which creates a formatter that
+ * spells out a value in words in the desired language, ORDINAL, which attaches
+ * an ordinal suffix from the desired language to the end of a number (e.g. "123rd"),
+ * and DURATION, which formats a duration in seconds as hours, minutes, and seconds.
+ * @stable ICU 2.0
+ */
+ public RuleBasedNumberFormat(Locale locale, int format) {
+ this(ULocale.forLocale(locale), format);
+ }
+
+ /**
+ * Creates a RuleBasedNumberFormat from a predefined description. The selector
+ * code choosed among three possible predefined formats: spellout, ordinal,
+ * and duration.
+ * @param locale The locale for the formatter.
+ * @param format A selector code specifying which kind of formatter to create for that
+ * locale. There are four legal values: SPELLOUT, which creates a formatter that
+ * spells out a value in words in the desired language, ORDINAL, which attaches
+ * an ordinal suffix from the desired language to the end of a number (e.g. "123rd"),
+ * DURATION, which formats a duration in seconds as hours, minutes, and seconds, and
+ * NUMBERING_SYSTEM, which is used to invoke rules for alternate numbering
+ * systems such as the Hebrew numbering system, or for Roman numerals, etc..
+ * @stable ICU 3.2
+ */
+ public RuleBasedNumberFormat(ULocale locale, int format) {
+ this.locale = locale;
+
+ ICUResourceBundle bundle = (ICUResourceBundle)UResourceBundle.
+ getBundleInstance(ICUResourceBundle.ICU_RBNF_BASE_NAME, locale);
+
+ // TODO: determine correct actual/valid locale. Note ambiguity
+ // here -- do actual/valid refer to pattern, DecimalFormatSymbols,
+ // or Collator?
+ ULocale uloc = bundle.getULocale();
+ setLocale(uloc, uloc);
+
+ String description = "";
+ String[][] localizations = null;
+
+ try {
+ // For backwards compatability - If we have a pre-4.2 style RBNF resource, attempt to read it.
+ description = bundle.getString(rulenames[format-1]);
+ }
+ catch (MissingResourceException e) {
+ try {
+ ICUResourceBundle rules = bundle.getWithFallback("RBNFRules/"+rulenames[format-1]);
+ UResourceBundleIterator it = rules.getIterator();
+ while (it.hasNext()) {
+ description = description.concat(it.nextString());
+ }
+ }
+ catch (MissingResourceException e1) {
+ }
+ }
+
+ try {
+ UResourceBundle locb = bundle.get(locnames[format-1]);
+ localizations = new String[locb.getSize()][];
+ for (int i = 0; i < localizations.length; ++i) {
+ localizations[i] = locb.get(i).getStringArray();
+ }
+ }
+ catch (MissingResourceException e) {
+ // might have description and no localizations, or no description...
+ }
+
+ init(description, localizations);
+
+ //TODO: we need a real fix - see #6895 / #6896
+ noParse = false;
+ if (locnames[format-1].equals("SpelloutLocalizations")) {
+ String lang = locale.getLanguage();
+ for (int i = 0; i < NO_SPELLOUT_PARSE_LANGUAGES.length; i++) {
+ if (NO_SPELLOUT_PARSE_LANGUAGES[i].equals(lang)) {
+ noParse = true;
+ break;
+ }
+ }
+ }
+ }
+
+ private static final String[] rulenames = {
+ "SpelloutRules", "OrdinalRules", "DurationRules", "NumberingSystemRules",
+ };
+ private static final String[] locnames = {
+ "SpelloutLocalizations", "OrdinalLocalizations", "DurationLocalizations", "NumberingSystemLocalizations",
+ };
+
+ /**
+ * Creates a RuleBasedNumberFormat from a predefined description. Uses the
+ * default locale.
+ * @param format A selector code specifying which kind of formatter to create.
+ * There are three legal values: SPELLOUT, which creates a formatter that spells
+ * out a value in words in the default locale's langyage, ORDINAL, which attaches
+ * an ordinal suffix from the default locale's language to a numeral, and
+ * DURATION, which formats a duration in seconds as hours, minutes, and seconds.
+ * or NUMBERING_SYSTEM, which is used for alternate numbering systems such as Hebrew.
+ * @stable ICU 2.0
+ */
+ public RuleBasedNumberFormat(int format) {
+ this(ULocale.getDefault(), format);
+ }
+
+ //-----------------------------------------------------------------------
+ // boilerplate
+ //-----------------------------------------------------------------------
+
+ /**
+ * Duplicates this formatter.
+ * @return A RuleBasedNumberFormat that is equal to this one.
+ * @stable ICU 2.0
+ */
+ public Object clone() {
+ return super.clone();
+ }
+
+ /**
+ * Tests two RuleBasedNumberFormats for equality.
+ * @param that The formatter to compare against this one.
+ * @return true if the two formatters have identical behavior.
+ * @stable ICU 2.0
+ */
+ public boolean equals(Object that) {
+ // if the other object isn't a RuleBasedNumberFormat, that's
+ // all we need to know
+ if (!(that instanceof RuleBasedNumberFormat)) {
+ return false;
+ } else {
+ // cast the other object's pointer to a pointer to a
+ // RuleBasedNumberFormat
+ RuleBasedNumberFormat that2 = (RuleBasedNumberFormat)that;
+
+ // compare their locales and lenient-parse modes
+ if (!locale.equals(that2.locale) || lenientParse != that2.lenientParse) {
+ return false;
+ }
+
+ // if that succeeds, then compare their rule set lists
+ if (ruleSets.length != that2.ruleSets.length) {
+ return false;
+ }
+ for (int i = 0; i < ruleSets.length; i++) {
+ if (!ruleSets[i].equals(that2.ruleSets[i])) {
+ return false;
+ }
+ }
+
+ return true;
+ }
+ }
+
+ /**
+ * Generates a textual description of this formatter.
+ * @return a String containing a rule set that will produce a RuleBasedNumberFormat
+ * with identical behavior to this one. This won't necessarily be identical
+ * to the rule set description that was originally passed in, but will produce
+ * the same result.
+ * @stable ICU 2.0
+ */
+ public String toString() {
+
+ // accumulate the descriptions of all the rule sets in a
+ // StringBuffer, then cast it to a String and return it
+ StringBuffer result = new StringBuffer();
+ for (int i = 0; i < ruleSets.length; i++) {
+ result.append(ruleSets[i].toString());
+ }
+ return result.toString();
+ }
+
+ /**
+ * Writes this object to a stream.
+ * @param out The stream to write to.
+ */
+ private void writeObject(java.io.ObjectOutputStream out)
+ throws java.io.IOException {
+ // we just write the textual description to the stream, so we
+ // have an implementation-independent streaming format
+ out.writeUTF(this.toString());
+ out.writeObject(this.locale);
+ }
+
+ /**
+ * Reads this object in from a stream.
+ * @param in The stream to read from.
+ */
+ private void readObject(java.io.ObjectInputStream in)
+ throws java.io.IOException {
+
+ // read the description in from the stream
+ String description = in.readUTF();
+ ULocale loc;
+
+ try {
+ loc = (ULocale) in.readObject();
+ } catch (Exception e) {
+ loc = ULocale.getDefault();
+ }
+
+ // build a brand-new RuleBasedNumberFormat from the description,
+ // then steal its substructure. This object's substructure and
+ // the temporary RuleBasedNumberFormat drop on the floor and
+ // get swept up by the garbage collector
+ RuleBasedNumberFormat temp = new RuleBasedNumberFormat(description, loc);
+ ruleSets = temp.ruleSets;
+ defaultRuleSet = temp.defaultRuleSet;
+ publicRuleSetNames = temp.publicRuleSetNames;
+ decimalFormatSymbols = temp.decimalFormatSymbols;
+ decimalFormat = temp.decimalFormat;
+ locale = temp.locale;
+ }
+
+
+ //-----------------------------------------------------------------------
+ // public API functions
+ //-----------------------------------------------------------------------
+
+ /**
+ * Returns a list of the names of all of this formatter's public rule sets.
+ * @return A list of the names of all of this formatter's public rule sets.
+ * @stable ICU 2.0
+ */
+ public String[] getRuleSetNames() {
+ return (String[])publicRuleSetNames.clone();
+ }
+
+ /**
+ * Return a list of locales for which there are locale-specific display names
+ * for the rule sets in this formatter. If there are no localized display names, return null.
+ * @return an array of the ulocales for which there is rule set display name information
+ * @stable ICU 3.2
+ */
+ public ULocale[] getRuleSetDisplayNameLocales() {
+ if (ruleSetDisplayNames != null) {
+ Set s = ruleSetDisplayNames.keySet();
+ String[] locales = (String[])s.toArray(new String[s.size()]);
+ Arrays.sort(locales, String.CASE_INSENSITIVE_ORDER);
+ ULocale[] result = new ULocale[locales.length];
+ for (int i = 0; i < locales.length; ++i) {
+ result[i] = new ULocale(locales[i]);
+ }
+ return result;
+ }
+ return null;
+ }
+
+ private String[] getNameListForLocale(ULocale loc) {
+ if (loc != null && ruleSetDisplayNames != null) {
+ String[] localeNames = { loc.getBaseName(), ULocale.getDefault().getBaseName() };
+ for (int i = 0; i < localeNames.length; ++i) {
+ String lname = localeNames[i];
+ while (lname.length() > 0) {
+ String[] names = (String[])ruleSetDisplayNames.get(lname);
+ if (names != null) {
+ return names;
+ }
+ lname = ULocale.getFallback(lname);
+ }
+ }
+ }
+ return null;
+ }
+
+ /**
+ * Return the rule set display names for the provided locale. These are in the same order
+ * as those returned by getRuleSetNames. The locale is matched against the locales for
+ * which there is display name data, using normal fallback rules. If no locale matches,
+ * the default display names are returned. (These are the internal rule set names minus
+ * the leading '%'.)
+ * @return an array of the locales that have display name information
+ * @see #getRuleSetNames
+ * @stable ICU 3.2
+ */
+ public String[] getRuleSetDisplayNames(ULocale loc) {
+ String[] names = getNameListForLocale(loc);
+ if (names != null) {
+ return (String[])names.clone();
+ }
+ names = getRuleSetNames();
+ for (int i = 0; i < names.length; ++i) {
+ names[i] = names[i].substring(1);
+ }
+ return names;
+ }
+
+ /**
+ * Return the rule set display names for the current default locale.
+ * @return an array of the display names
+ * @see #getRuleSetDisplayNames(ULocale)
+ * @stable ICU 3.2
+ */
+ public String[] getRuleSetDisplayNames() {
+ return getRuleSetDisplayNames(ULocale.getDefault());
+ }
+
+ /**
+ * Return the rule set display name for the provided rule set and locale.
+ * The locale is matched against the locales for which there is display name data, using
+ * normal fallback rules. If no locale matches, the default display name is returned.
+ * @return the display name for the rule set
+ * @see #getRuleSetDisplayNames
+ * @throws IllegalArgumentException if ruleSetName is not a valid rule set name for this format
+ * @stable ICU 3.2
+ */
+ public String getRuleSetDisplayName(String ruleSetName, ULocale loc) {
+ String[] rsnames = publicRuleSetNames;
+ for (int ix = 0; ix < rsnames.length; ++ix) {
+ if (rsnames[ix].equals(ruleSetName)) {
+ String[] names = getNameListForLocale(loc);
+ if (names != null) {
+ return names[ix];
+ }
+ return rsnames[ix].substring(1);
+ }
+ }
+ throw new IllegalArgumentException("unrecognized rule set name: " + ruleSetName);
+ }
+
+ /**
+ * Return the rule set display name for the provided rule set in the current default locale.
+ * @return the display name for the rule set
+ * @see #getRuleSetDisplayName(String,ULocale)
+ * @stable ICU 3.2
+ */
+ public String getRuleSetDisplayName(String ruleSetName) {
+ return getRuleSetDisplayName(ruleSetName, ULocale.getDefault());
+ }
+
+ /**
+ * Formats the specified number according to the specified rule set.
+ * @param number The number to format.
+ * @param ruleSet The name of the rule set to format the number with.
+ * This must be the name of a valid public rule set for this formatter.
+ * @return A textual representation of the number.
+ * @stable ICU 2.0
+ */
+ public String format(double number, String ruleSet) throws IllegalArgumentException {
+ if (ruleSet.startsWith("%%")) {
+ throw new IllegalArgumentException("Can't use internal rule set");
+ }
+ return format(number, findRuleSet(ruleSet));
+ }
+
+ /**
+ * Formats the specified number according to the specified rule set.
+ * (If the specified rule set specifies a master ["x.0"] rule, this function
+ * ignores it. Convert the number to a double first if you ned it.) This
+ * function preserves all the precision in the long-- it doesn't convert it
+ * to a double.
+ * @param number The number to format.
+ * @param ruleSet The name of the rule set to format the number with.
+ * This must be the name of a valid public rule set for this formatter.
+ * @return A textual representation of the number.
+ * @stable ICU 2.0
+ */
+ public String format(long number, String ruleSet) throws IllegalArgumentException {
+ if (ruleSet.startsWith("%%")) {
+ throw new IllegalArgumentException("Can't use internal rule set");
+ }
+ return format(number, findRuleSet(ruleSet));
+ }
+
+ /**
+ * Formats the specified number using the formatter's default rule set.
+ * (The default rule set is the last public rule set defined in the description.)
+ * @param number The number to format.
+ * @param toAppendTo A StringBuffer that the result should be appended to.
+ * @param ignore This function doesn't examine or update the field position.
+ * @return toAppendTo
+ * @stable ICU 2.0
+ */
+ public StringBuffer format(double number,
+ StringBuffer toAppendTo,
+ FieldPosition ignore) {
+ // this is one of the inherited format() methods. Since it doesn't
+ // have a way to select the rule set to use, it just uses the
+ // default one
+ toAppendTo.append(format(number, defaultRuleSet));
+ return toAppendTo;
+ }
+
+ /**
+ * Formats the specified number using the formatter's default rule set.
+ * (The default rule set is the last public rule set defined in the description.)
+ * (If the specified rule set specifies a master ["x.0"] rule, this function
+ * ignores it. Convert the number to a double first if you ned it.) This
+ * function preserves all the precision in the long-- it doesn't convert it
+ * to a double.
+ * @param number The number to format.
+ * @param toAppendTo A StringBuffer that the result should be appended to.
+ * @param ignore This function doesn't examine or update the field position.
+ * @return toAppendTo
+ * @stable ICU 2.0
+ */
+ public StringBuffer format(long number,
+ StringBuffer toAppendTo,
+ FieldPosition ignore) {
+ // this is one of the inherited format() methods. Since it doesn't
+ // have a way to select the rule set to use, it just uses the
+ // default one
+ toAppendTo.append(format(number, defaultRuleSet));
+ return toAppendTo;
+ }
+
+ /**
+ * <strong><font face=helvetica color=red>NEW</font></strong>
+ * Implement com.ibm.icu.text.NumberFormat:
+ * Format a BigInteger.
+ * @stable ICU 2.0
+ */
+ public StringBuffer format(BigInteger number,
+ StringBuffer toAppendTo,
+ FieldPosition pos) {
+ return format(new com.ibm.icu.math.BigDecimal(number), toAppendTo, pos);
+ }
+
+//#if defined(FOUNDATION10)
+//#else
+ /**
+ * <strong><font face=helvetica color=red>NEW</font></strong>
+ * Implement com.ibm.icu.text.NumberFormat:
+ * Format a BigDecimal.
+ * @stable ICU 2.0
+ */
+ public StringBuffer format(java.math.BigDecimal number,
+ StringBuffer toAppendTo,
+ FieldPosition pos) {
+ return format(new com.ibm.icu.math.BigDecimal(number), toAppendTo, pos);
+ }
+//#endif
+
+ /**
+ * <strong><font face=helvetica color=red>NEW</font></strong>
+ * Implement com.ibm.icu.text.NumberFormat:
+ * Format a BigDecimal.
+ * @stable ICU 2.0
+ */
+ public StringBuffer format(com.ibm.icu.math.BigDecimal number,
+ StringBuffer toAppendTo,
+ FieldPosition pos) {
+ // TEMPORARY:
+ return format(number.doubleValue(), toAppendTo, pos);
+ }
+
+ /**
+ * Parses the specfied string, beginning at the specified position, according
+ * to this formatter's rules. This will match the string against all of the
+ * formatter's public rule sets and return the value corresponding to the longest
+ * parseable substring. This function's behavior is affected by the lenient
+ * parse mode.
+ * @param text The string to parse
+ * @param parsePosition On entry, contains the position of the first character
+ * in "text" to examine. On exit, has been updated to contain the position
+ * of the first character in "text" that wasn't consumed by the parse.
+ * @return The number that corresponds to the parsed text. This will be an
+ * instance of either Long or Double, depending on whether the result has a
+ * fractional part.
+ * @see #setLenientParseMode
+ * @stable ICU 2.0
+ */
+ public Number parse(String text, ParsePosition parsePosition) {
+
+ //TODO: We need a real fix. See #6895 / #6896
+ if (noParse) {
+ // skip parsing
+ return new Long(0);
+ }
+
+ // parsePosition tells us where to start parsing. We copy the
+ // text in the string from here to the end inro a new string,
+ // and create a new ParsePosition and result variable to use
+ // for the duration of the parse operation
+ String workingText = text.substring(parsePosition.getIndex());
+ ParsePosition workingPos = new ParsePosition(0);
+ Number tempResult = null;
+
+ // keep track of the largest number of characters consumed in
+ // the various trials, and the result that corresponds to it
+ Number result = new Long(0);
+ ParsePosition highWaterMark = new ParsePosition(workingPos.getIndex());
+
+ // iterate over the public rule sets (beginning with the default one)
+ // and try parsing the text with each of them. Keep track of which
+ // one consumes the most characters: that's the one that determines
+ // the result we return
+ for (int i = ruleSets.length - 1; i >= 0; i--) {
+ // skip private rule sets
+ if (!ruleSets[i].isPublic() || !ruleSets[i].isParseable()) {
+ continue;
+ }
+
+ // try parsing the string with the rule set. If it gets past the
+ // high-water mark, update the high-water mark and the result
+ tempResult = ruleSets[i].parse(workingText, workingPos, Double.MAX_VALUE);
+ if (workingPos.getIndex() > highWaterMark.getIndex()) {
+ result = tempResult;
+ highWaterMark.setIndex(workingPos.getIndex());
+ }
+ // commented out because this API on ParsePosition doesn't exist in 1.1.x
+ // if (workingPos.getErrorIndex() > highWaterMark.getErrorIndex()) {
+ // highWaterMark.setErrorIndex(workingPos.getErrorIndex());
+ // }
+
+ // if we manage to use up all the characters in the string,
+ // we don't have to try any more rule sets
+ if (highWaterMark.getIndex() == workingText.length()) {
+ break;
+ }
+
+ // otherwise, reset our internal parse position to the
+ // beginning and try again with the next rule set
+ workingPos.setIndex(0);
+ }
+
+ // add the high water mark to our original parse position and
+ // return the result
+ parsePosition.setIndex(parsePosition.getIndex() + highWaterMark.getIndex());
+ // commented out because this API on ParsePosition doesn't exist in 1.1.x
+ // if (highWaterMark.getIndex() == 0) {
+ // parsePosition.setErrorIndex(parsePosition.getIndex() + highWaterMark.getErrorIndex());
+ // }
+ return result;
+ }
+
+ /**
+ * Turns lenient parse mode on and off.
+ *
+ * When in lenient parse mode, the formatter uses a Collator for parsing the text.
+ * Only primary differences are treated as significant. This means that case
+ * differences, accent differences, alternate spellings of the same letter
+ * (e.g., ae and a-umlaut in German), ignorable characters, etc. are ignored in
+ * matching the text. In many cases, numerals will be accepted in place of words
+ * or phrases as well.
+ *
+ * For example, all of the following will correctly parse as 255 in English in
+ * lenient-parse mode:
+ * <br>"two hundred fifty-five"
+ * <br>"two hundred fifty five"
+ * <br>"TWO HUNDRED FIFTY-FIVE"
+ * <br>"twohundredfiftyfive"
+ * <br>"2 hundred fifty-5"
+ *
+ * The Collator used is determined by the locale that was
+ * passed to this object on construction. The description passed to this object
+ * on construction may supply additional collation rules that are appended to the
+ * end of the default collator for the locale, enabling additional equivalences
+ * (such as adding more ignorable characters or permitting spelled-out version of
+ * symbols; see the demo program for examples).
+ *
+ * It's important to emphasize that even strict parsing is relatively lenient: it
+ * will accept some text that it won't produce as output. In English, for example,
+ * it will correctly parse "two hundred zero" and "fifteen hundred".
+ *
+ * @param enabled If true, turns lenient-parse mode on; if false, turns it off.
+ * @see RuleBasedCollator
+ * @stable ICU 2.0
+ */
+ public void setLenientParseMode(boolean enabled) {
+ lenientParse = enabled;
+
+ // if we're leaving lenient-parse mode, throw away the collator
+ // we've been using
+ if (!enabled) {
+ collator = null;
+ }
+ }
+
+ /**
+ * Returns true if lenient-parse mode is turned on. Lenient parsing is off
+ * by default.
+ * @return true if lenient-parse mode is turned on.
+ * @see #setLenientParseMode
+ * @stable ICU 2.0
+ */
+ public boolean lenientParseEnabled() {
+ return lenientParse;
+ }
+
+ /**
+ * Override the default rule set to use. If ruleSetName is null, reset
+ * to the initial default rule set.
+ * @param ruleSetName the name of the rule set, or null to reset the initial default.
+ * @throws IllegalArgumentException if ruleSetName is not the name of a public ruleset.
+ * @stable ICU 2.0
+ */
+ public void setDefaultRuleSet(String ruleSetName) {
+ if (ruleSetName == null) {
+ if (publicRuleSetNames.length > 0) {
+ defaultRuleSet = findRuleSet(publicRuleSetNames[0]);
+ } else {
+ defaultRuleSet = null;
+ int n = ruleSets.length;
+ while (--n >= 0) {
+ String currentName = ruleSets[n].getName();
+ if (currentName.equals("%spellout-numbering") || currentName.equals("%digits-ordinal") || currentName.equals("%duration")) {
+ defaultRuleSet = ruleSets[n];
+ return;
+ }
+ }
+
+ n = ruleSets.length;
+ while (--n >= 0) {
+ if (ruleSets[n].isPublic()) {
+ defaultRuleSet = ruleSets[n];
+ break;
+ }
+ }
+ }
+ } else if (ruleSetName.startsWith("%%")) {
+ throw new IllegalArgumentException("cannot use private rule set: " + ruleSetName);
+ } else {
+ defaultRuleSet = findRuleSet(ruleSetName);
+ }
+ }
+
+ /**
+ * Return the name of the current default rule set.
+ * @return the name of the current default rule set, if it is public, else the empty string.
+ * @stable ICU 3.0
+ */
+ public String getDefaultRuleSetName() {
+ if (defaultRuleSet != null && defaultRuleSet.isPublic()) {
+ return defaultRuleSet.getName();
+ }
+ return "";
+ }
+
+ //-----------------------------------------------------------------------
+ // package-internal API
+ //-----------------------------------------------------------------------
+
+ /**
+ * Returns a reference to the formatter's default rule set. The default
+ * rule set is the last public rule set in the description, or the one
+ * most recently set by setDefaultRuleSet.
+ * @return The formatter's default rule set.
+ */
+ NFRuleSet getDefaultRuleSet() {
+ return defaultRuleSet;
+ }
+
+ /**
+ * Returns the collator to use for lenient parsing. The collator is lazily created:
+ * this function creates it the first time it's called.
+ * @return The collator to use for lenient parsing, or null if lenient parsing
+ * is turned off.
+ */
+ Collator getCollator() {
+ // lazy-evaulate the collator
+ if (collator == null && lenientParse) {
+ try {
+ // create a default collator based on the formatter's locale,
+ // then pull out that collator's rules, append any additional
+ // rules specified in the description, and create a _new_
+ // collator based on the combinaiton of those rules
+ RuleBasedCollator temp = (RuleBasedCollator)Collator.getInstance(locale);
+ String rules = temp.getRules() + (lenientParseRules == null ? "" : lenientParseRules);
+
+ collator = new RuleBasedCollator(rules);
+ collator.setDecomposition(Collator.CANONICAL_DECOMPOSITION);
+ }
+ catch (Exception e) {
+ // If we get here, it means we have a malformed set of
+ // collation rules, which hopefully won't happen
+ if(DEBUG){
+ e.printStackTrace();
+ }
+ collator = null;
+ }
+ }
+
+ // if lenient-parse mode is off, this will be null
+ // (see setLenientParseMode())
+ return collator;
+ }
+
+ /**
+ * Returns the DecimalFormatSymbols object that should be used by all DecimalFormat
+ * instances owned by this formatter. This object is lazily created: this function
+ * creates it the first time it's called.
+ * @return The DecimalFormatSymbols object that should be used by all DecimalFormat
+ * instances owned by this formatter.
+ */
+ DecimalFormatSymbols getDecimalFormatSymbols() {
+ // lazy-evaluate the DecimalFormatSymbols object. This object
+ // is shared by all DecimalFormat instances belonging to this
+ // formatter
+ if (decimalFormatSymbols == null) {
+ decimalFormatSymbols = new DecimalFormatSymbols(locale);
+ }
+ return decimalFormatSymbols;
+ }
+
+ DecimalFormat getDecimalFormat() {
+ if (decimalFormat == null) {
+ decimalFormat = (DecimalFormat)NumberFormat.getInstance(locale);
+ }
+ return decimalFormat;
+ }
+
+ //-----------------------------------------------------------------------
+ // construction implementation
+ //-----------------------------------------------------------------------
+
+ /**
+ * This extracts the special information from the rule sets before the
+ * main parsing starts. Extra whitespace must have already been removed
+ * from the description. If found, the special information is removed from the
+ * description and returned, otherwise the description is unchanged and null
+ * is returned. Note: the trailing semicolon at the end of the special
+ * rules is stripped.
+ * @param description the rbnf description with extra whitespace removed
+ * @param specialName the name of the special rule text to extract
+ * @return the special rule text, or null if the rule was not found
+ */
+ private String extractSpecial(StringBuffer description, String specialName) {
+ String result = null;
+ int lp = Utility.indexOf(description, specialName);
+ if (lp != -1) {
+ // we've got to make sure we're not in the middle of a rule
+ // (where specialName would actually get treated as
+ // rule text)
+ if (lp == 0 || description.charAt(lp - 1) == ';') {
+ // locate the beginning and end of the actual special
+ // rules (there may be whitespace between the name and
+ // the first token in the description)
+ int lpEnd = Utility.indexOf(description, ";%", lp);
+
+ if (lpEnd == -1) {
+ lpEnd = description.length() - 1; // later we add 1 back to get the '%'
+ }
+ int lpStart = lp + specialName.length();
+ while (lpStart < lpEnd &&
+ UCharacterProperty.isRuleWhiteSpace(description.charAt(lpStart))) {
+ ++lpStart;
+ }
+
+ // copy out the special rules
+ result = description.substring(lpStart, lpEnd);
+
+ // remove the special rule from the description
+ description.delete(lp, lpEnd+1); // delete the semicolon but not the '%'
+ }
+ }
+ return result;
+ }
+
+ /**
+ * This function parses the description and uses it to build all of
+ * internal data structures that the formatter uses to do formatting
+ * @param description The description of the formatter's desired behavior.
+ * This is either passed in by the caller or loaded out of a resource
+ * by one of the constructors, and is in the description format specified
+ * in the class docs.
+ */
+ private void init(String description, String[][] localizations) {
+ initLocalizations(localizations);
+
+ // start by stripping the trailing whitespace from all the rules
+ // (this is all the whitespace follwing each semicolon in the
+ // description). This allows us to look for rule-set boundaries
+ // by searching for ";%" without having to worry about whitespace
+ // between the ; and the %
+ StringBuffer descBuf = stripWhitespace(description);
+
+ // check to see if there's a set of lenient-parse rules. If there
+ // is, pull them out into our temporary holding place for them,
+ // and delete them from the description before the real desciption-
+ // parsing code sees them
+
+ lenientParseRules = extractSpecial(descBuf, "%%lenient-parse:");
+ postProcessRules = extractSpecial(descBuf, "%%post-process:");
+
+ // pre-flight parsing the description and count the number of
+ // rule sets (";%" marks the end of one rule set and the beginning
+ // of the next)
+ int numRuleSets = 0;
+ for (int p = Utility.indexOf(descBuf, ";%"); p != -1; p = Utility.indexOf(descBuf, ";%", p)) {
+ ++numRuleSets;
+ ++p;
+ }
+ ++numRuleSets;
+
+ // our rule list is an array of the apprpriate size
+ ruleSets = new NFRuleSet[numRuleSets];
+
+ // divide up the descriptions into individual rule-set descriptions
+ // and store them in a temporary array. At each step, we also
+ // new up a rule set, but all this does is initialize its name
+ // and remove it from its description. We can't actually parse
+ // the rest of the descriptions and finish initializing everything
+ // because we have to know the names and locations of all the rule
+ // sets before we can actually set everything up
+ String[] ruleSetDescriptions = new String[numRuleSets];
+
+ int curRuleSet = 0;
+ int start = 0;
+ for (int p = Utility.indexOf(descBuf, ";%"); p != -1; p = Utility.indexOf(descBuf, ";%", start)) {
+ ruleSetDescriptions[curRuleSet] = descBuf.substring(start, p + 1);
+ ruleSets[curRuleSet] = new NFRuleSet(ruleSetDescriptions, curRuleSet);
+ ++curRuleSet;
+ start = p + 1;
+ }
+ ruleSetDescriptions[curRuleSet] = descBuf.substring(start);
+ ruleSets[curRuleSet] = new NFRuleSet(ruleSetDescriptions, curRuleSet);
+
+ // now we can take note of the formatter's default rule set, which
+ // is the last public rule set in the description (it's the last
+ // rather than the first so that a user can create a new formatter
+ // from an existing formatter and change its default bevhaior just
+ // by appending more rule sets to the end)
+
+ // {dlf} Initialization of a fraction rule set requires the default rule
+ // set to be known. For purposes of initialization, this is always the
+ // last public rule set, no matter what the localization data says.
+
+ // Set the default ruleset to the last public ruleset, unless one of the predefined
+ // ruleset names %spellout-numbering, %digits-ordinal, or %duration is found
+
+ boolean defaultNameFound = false;
+ int n = ruleSets.length;
+ defaultRuleSet = ruleSets[ruleSets.length - 1];
+
+ while (--n >= 0) {
+ String currentName = ruleSets[n].getName();
+ if (currentName.equals("%spellout-numbering") || currentName.equals("%digits-ordinal") || currentName.equals("%duration")) {
+ defaultRuleSet = ruleSets[n];
+ defaultNameFound = true;
+ break;
+ }
+ }
+
+ if ( !defaultNameFound ) {
+ for (int i = ruleSets.length - 1; i >= 0; --i) {
+ if (!ruleSets[i].getName().startsWith("%%")) {
+ defaultRuleSet = ruleSets[i];
+ break;
+ }
+ }
+ }
+
+ // finally, we can go back through the temporary descriptions
+ // list and finish seting up the substructure (and we throw
+ // away the temporary descriptions as we go)
+ for (int i = 0; i < ruleSets.length; i++) {
+ ruleSets[i].parseRules(ruleSetDescriptions[i], this);
+ ruleSetDescriptions[i] = null;
+ }
+
+ // Now that the rules are initialized, the 'real' default rule
+ // set can be adjusted by the localization data.
+
+ // count the number of public rule sets
+ // (public rule sets have names that begin with % instead of %%)
+ int publicRuleSetCount = 0;
+ for (int i = 0; i < ruleSets.length; i++) {
+ if (!ruleSets[i].getName().startsWith("%%")) {
+ ++publicRuleSetCount;
+ }
+ }
+
+ // prepare an array of the proper size and copy the names into it
+ String[] publicRuleSetTemp = new String[publicRuleSetCount];
+ publicRuleSetCount = 0;
+ for (int i = ruleSets.length - 1; i >= 0; i--) {
+ if (!ruleSets[i].getName().startsWith("%%")) {
+ publicRuleSetTemp[publicRuleSetCount++] = ruleSets[i].getName();
+ }
+ }
+
+ if (publicRuleSetNames != null) {
+ // confirm the names, if any aren't in the rules, that's an error
+ // it is ok if the rules contain public rule sets that are not in this list
+ loop: for (int i = 0; i < publicRuleSetNames.length; ++i) {
+ String name = publicRuleSetNames[i];
+ for (int j = 0; j < publicRuleSetTemp.length; ++j) {
+ if (name.equals(publicRuleSetTemp[j])) {
+ continue loop;
+ }
+ }
+ throw new IllegalArgumentException("did not find public rule set: " + name);
+ }
+
+ defaultRuleSet = findRuleSet(publicRuleSetNames[0]); // might be different
+ } else {
+ publicRuleSetNames = publicRuleSetTemp;
+ }
+ }
+
+ /**
+ * Take the localizations array and create a Map from the locale strings to
+ * the localization arrays.
+ */
+ private void initLocalizations(String[][] localizations) {
+ if (localizations != null) {
+ publicRuleSetNames = (String[])localizations[0].clone();
+
+ Map m = new HashMap();
+ for (int i = 1; i < localizations.length; ++i) {
+ String[] data = localizations[i];
+ String loc = data[0];
+ String[] names = new String[data.length-1];
+ if (names.length != publicRuleSetNames.length) {
+ throw new IllegalArgumentException("public name length: " + publicRuleSetNames.length +
+ " != localized names[" + i + "] length: " + names.length);
+ }
+ System.arraycopy(data, 1, names, 0, names.length);
+ m.put(loc, names);
+ }
+
+ if (!m.isEmpty()) {
+ ruleSetDisplayNames = m;
+ }
+ }
+ }
+
+ /**
+ * This function is used by init() to strip whitespace between rules (i.e.,
+ * after semicolons).
+ * @param description The formatter description
+ * @return The description with all the whitespace that follows semicolons
+ * taken out.
+ */
+ private StringBuffer stripWhitespace(String description) {
+ // since we don't have a method that deletes characters (why?!!)
+ // create a new StringBuffer to copy the text into
+ StringBuffer result = new StringBuffer();
+
+ // iterate through the characters...
+ int start = 0;
+ while (start != -1 && start < description.length()) {
+ // seek to the first non-whitespace character...
+ while (start < description.length()
+ && UCharacterProperty.isRuleWhiteSpace(description.charAt(start))) {
+ ++start;
+ }
+
+ //if the first non-whitespace character is semicolon, skip it and continue
+ if (start < description.length() && description.charAt(start) == ';') {
+ start += 1;
+ continue;
+ }
+
+ // locate the next semicolon in the text and copy the text from
+ // our current position up to that semicolon into the result
+ int p;
+ p = description.indexOf(';', start);
+ if (p == -1) {
+ // or if we don't find a semicolon, just copy the rest of
+ // the string into the result
+ result.append(description.substring(start));
+ start = -1;
+ }
+ else if (p < description.length()) {
+ result.append(description.substring(start, p + 1));
+ start = p + 1;
+ }
+
+ // when we get here, we've seeked off the end of the sring, and
+ // we terminate the loop (we continue until *start* is -1 rather
+ // than until *p* is -1, because otherwise we'd miss the last
+ // rule in the description)
+ else {
+ start = -1;
+ }
+ }
+ return result;
+ }
+
+// /**
+// * This function is called ONLY DURING CONSTRUCTION to fill in the
+// * defaultRuleSet variable once we've set up all the rule sets.
+// * The default rule set is the last public rule set in the description.
+// * (It's the last rather than the first so that a caller can append
+// * text to the end of an existing formatter description to change its
+// * behavior.)
+// */
+// private void initDefaultRuleSet() {
+// // seek backward from the end of the list until we reach a rule set
+// // whose name DOESN'T begin with %%. That's the default rule set
+// for (int i = ruleSets.length - 1; i >= 0; --i) {
+// if (!ruleSets[i].getName().startsWith("%%")) {
+// defaultRuleSet = ruleSets[i];
+// return;
+// }
+// }
+// defaultRuleSet = ruleSets[ruleSets.length - 1];
+// }
+
+ //-----------------------------------------------------------------------
+ // formatting implementation
+ //-----------------------------------------------------------------------
+
+ /**
+ * Bottleneck through which all the public format() methods
+ * that take a double pass. By the time we get here, we know
+ * which rule set we're using to do the formatting.
+ * @param number The number to format
+ * @param ruleSet The rule set to use to format the number
+ * @return The text that resulted from formatting the number
+ */
+ private String format(double number, NFRuleSet ruleSet) {
+ // all API format() routines that take a double vector through
+ // here. Create an empty string buffer where the result will
+ // be built, and pass it to the rule set (along with an insertion
+ // position of 0 and the number being formatted) to the rule set
+ // for formatting
+ StringBuffer result = new StringBuffer();
+ ruleSet.format(number, result, 0);
+ postProcess(result, ruleSet);
+ return result.toString();
+ }
+
+ /**
+ * Bottleneck through which all the public format() methods
+ * that take a long pass. By the time we get here, we know
+ * which rule set we're using to do the formatting.
+ * @param number The number to format
+ * @param ruleSet The rule set to use to format the number
+ * @return The text that resulted from formatting the number
+ */
+ private String format(long number, NFRuleSet ruleSet) {
+ // all API format() routines that take a double vector through
+ // here. We have these two identical functions-- one taking a
+ // double and one taking a long-- the couple digits of precision
+ // that long has but double doesn't (both types are 8 bytes long,
+ // but double has to borrow some of the mantissa bits to hold
+ // the exponent).
+ // Create an empty string buffer where the result will
+ // be built, and pass it to the rule set (along with an insertion
+ // position of 0 and the number being formatted) to the rule set
+ // for formatting
+ StringBuffer result = new StringBuffer();
+ ruleSet.format(number, result, 0);
+ postProcess(result, ruleSet);
+ return result.toString();
+ }
+
+ /**
+ * Post-process the rules if we have a post-processor.
+ */
+ private void postProcess(StringBuffer result, NFRuleSet ruleSet) {
+ if (postProcessRules != null) {
+ if (postProcessor == null) {
+ int ix = postProcessRules.indexOf(";");
+ if (ix == -1) {
+ ix = postProcessRules.length();
+ }
+ String ppClassName = postProcessRules.substring(0, ix).trim();
+ try {
+ Class cls = Class.forName(ppClassName);
+ postProcessor = (RBNFPostProcessor)cls.newInstance();
+ postProcessor.init(this, postProcessRules);
+ }
+ catch (Exception e) {
+ // if debug, print it out
+ if (DEBUG) System.out.println("could not locate " + ppClassName + ", error " +
+ e.getClass().getName() + ", " + e.getMessage());
+ postProcessor = null;
+ postProcessRules = null; // don't try again
+ return;
+ }
+ }
+
+ postProcessor.process(result, ruleSet);
+ }
+ }
+
+ /**
+ * Returns the named rule set. Throws an IllegalArgumentException
+ * if this formatter doesn't have a rule set with that name.
+ * @param name The name of the desired rule set
+ * @return The rule set with that name
+ */
+ NFRuleSet findRuleSet(String name) throws IllegalArgumentException {
+ for (int i = 0; i < ruleSets.length; i++) {
+ if (ruleSets[i].getName().equals(name)) {
+ return ruleSets[i];
+ }
+ }
+ throw new IllegalArgumentException("No rule set named " + name);
+ }
+}