KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > ibm > icu > text > NFRule


1 /*
2  *******************************************************************************
3  * Copyright (C) 1996-2004, International Business Machines Corporation and *
4  * others. All Rights Reserved. *
5  *******************************************************************************
6  */

7 package com.ibm.icu.text;
8
9 import com.ibm.icu.impl.UCharacterProperty;
10
11 import java.text.*;
12
13 /**
14  * A class represnting a single rule in a RuleBasedNumberFormat. A rule
15  * inserts its text into the result string and then passes control to its
16  * substitutions, which do the same thing.
17  */

18 final class NFRule {
19     //-----------------------------------------------------------------------
20
// constants
21
//-----------------------------------------------------------------------
22

23     /**
24      * Puts a copyright in the .class file
25      */

26     private static final String JavaDoc copyrightNotice
27         = "Copyright \u00a91997-1998 IBM Corp. All rights reserved.";
28
29     /**
30      * Special base value used to identify a negative-number rule
31      */

32     public static final int NEGATIVE_NUMBER_RULE = -1;
33
34     /**
35      * Special base value used to identify an improper fraction (x.x) rule
36      */

37     public static final int IMPROPER_FRACTION_RULE = -2;
38
39     /**
40      * Special base value used to identify a proper fraction (0.x) rule
41      */

42     public static final int PROPER_FRACTION_RULE = -3;
43
44     /**
45      * Special base value used to identify a master rule
46      */

47     public static final int MASTER_RULE = -4;
48
49     //-----------------------------------------------------------------------
50
// data members
51
//-----------------------------------------------------------------------
52

53     /**
54      * The rule's base value
55      */

56     private long baseValue;
57
58     /**
59      * The rule's radix (the radix to the power of the exponent equals
60      * the rule's divisor)
61      */

62     private int radix = 10;
63
64     /**
65      * The rule's exponent (the radx rased to the power of the exponsnt
66      * equals the rule's divisor)
67      */

68     private short exponent = 0;
69
70     /**
71      * The rule's rule text. When formatting a number, the rule's text
72      * is inserted into the result string, and then the text from any
73      * substitutions is inserted into the result string
74      */

75     private String JavaDoc ruleText = null;
76
77     /**
78      * The rule's first substitution (the one with the lower offset
79      * into the rule text)
80      */

81     private NFSubstitution sub1 = null;
82
83     /**
84      * The rule's second substitution (the one with the higher offset
85      * into the rule text)
86      */

87     private NFSubstitution sub2 = null;
88
89     /**
90      * The RuleBasedNumberFormat that owns this rule
91      */

92     private RuleBasedNumberFormat formatter = null;
93
94     //-----------------------------------------------------------------------
95
// construction
96
//-----------------------------------------------------------------------
97

98     /**
99      * Creates one or more rules based on the description passed in.
100      * @param description The description of the rule(s).
101      * @param owner The rule set containing the new rule(s).
102      * @param predecessor The rule that precedes the new one(s) in "owner"'s
103      * rule list
104      * @param ownersOwner The RuleBasedNumberFormat that owns the
105      * rule set that owns the new rule(s)
106      * @return An instance of NFRule, or an array of NFRules
107      */

108     public static Object JavaDoc makeRules(String JavaDoc description,
109                                    NFRuleSet owner,
110                                    NFRule predecessor,
111                                    RuleBasedNumberFormat ownersOwner) {
112         // we know we're making at least one rule, so go ahead and
113
// new it up and initialize its basevalue and divisor
114
// (this also strips the rule descriptor, if any, off the
115
// descripton string)
116
NFRule rule1 = new NFRule(ownersOwner);
117         description = rule1.parseRuleDescriptor(description);
118
119         // check the description to see whether there's text enclosed
120
// in brackets
121
int brack1 = description.indexOf("[");
122         int brack2 = description.indexOf("]");
123
124         // if the description doesn't contain a matched pair of brackets,
125
// or if it's of a type that doesn't recognize bracketed text,
126
// then leave the description alone, initialize the rule's
127
// rule text and substitutions, and return that rule
128
if (brack1 == -1 || brack2 == -1 || brack1 > brack2
129             || rule1.getBaseValue() == PROPER_FRACTION_RULE
130             || rule1.getBaseValue() == NEGATIVE_NUMBER_RULE) {
131             rule1.ruleText = description;
132             rule1.extractSubstitutions(owner, predecessor, ownersOwner);
133             return rule1;
134         } else {
135             // if the description does contain a matched pair of brackets,
136
// then it's really shorthand for two rules (with one exception)
137
NFRule rule2 = null;
138             StringBuffer JavaDoc sbuf = new StringBuffer JavaDoc();
139
140             // we'll actually only split the rule into two rules if its
141
// base value is an even multiple of its divisor (or it's one
142
// of the special rules)
143
if ((rule1.baseValue > 0
144                  && rule1.baseValue % (Math.pow(rule1.radix, rule1.exponent)) == 0)
145                 || rule1.baseValue == IMPROPER_FRACTION_RULE
146                 || rule1.baseValue == MASTER_RULE) {
147
148                 // if it passes that test, new up the second rule. If the
149
// rule set both rules will belong to is a fraction rule
150
// set, they both have the same base value; otherwise,
151
// increment the original rule's base value ("rule1" actually
152
// goes SECOND in the rule set's rule list)
153
rule2 = new NFRule(ownersOwner);
154                 if (rule1.baseValue >= 0) {
155                     rule2.baseValue = rule1.baseValue;
156                     if (!owner.isFractionSet()) {
157                         ++rule1.baseValue;
158                     }
159                 }
160
161                 // if the description began with "x.x" and contains bracketed
162
// text, it describes both the improper fraction rule and
163
// the proper fraction rule
164
else if (rule1.baseValue == IMPROPER_FRACTION_RULE) {
165                     rule2.baseValue = PROPER_FRACTION_RULE;
166                 }
167
168                 // if the description began with "x.0" and contains bracketed
169
// text, it describes both the master rule and the
170
// improper fraction rule
171
else if (rule1.baseValue == MASTER_RULE) {
172                     rule2.baseValue = rule1.baseValue;
173                     rule1.baseValue = IMPROPER_FRACTION_RULE;
174                 }
175
176                 // both rules have the same radix and exponent (i.e., the
177
// same divisor)
178
rule2.radix = rule1.radix;
179                 rule2.exponent = rule1.exponent;
180
181                 // rule2's rule text omits the stuff in brackets: initalize
182
// its rule text and substitutions accordingly
183
sbuf.append(description.substring(0, brack1));
184                 if (brack2 + 1 < description.length()) {
185                     sbuf.append(description.substring(brack2 + 1));
186                 }
187                 rule2.ruleText = sbuf.toString();
188                 rule2.extractSubstitutions(owner, predecessor, ownersOwner);
189             }
190
191             // rule1's text includes the text in the brackets but omits
192
// the brackets themselves: initialize _its_ rule text and
193
// substitutions accordingly
194
sbuf.setLength(0);
195             sbuf.append(description.substring(0, brack1));
196             sbuf.append(description.substring(brack1 + 1, brack2));
197             if (brack2 + 1 < description.length()) {
198                 sbuf.append(description.substring(brack2 + 1));
199             }
200             rule1.ruleText = sbuf.toString();
201             rule1.extractSubstitutions(owner, predecessor, ownersOwner);
202
203             // if we only have one rule, return it; if we have two, return
204
// a two-element array containing them (notice that rule2 goes
205
// BEFORE rule1 in the list: in all cases, rule2 OMITS the
206
// material in the brackets and rule1 INCLUDES the material
207
// in the brackets)
208
if (rule2 == null) {
209                 return rule1;
210             } else {
211                 return new NFRule[] { rule2, rule1 };
212             }
213         }
214     }
215
216     /**
217      * Nominal constructor for NFRule. Most of the work of constructing
218      * an NFRule is actually performed by makeRules().
219      */

220     public NFRule(RuleBasedNumberFormat formatter) {
221         this.formatter = formatter;
222     }
223
224     /**
225      * This function parses the rule's rule descriptor (i.e., the base
226      * value and/or other tokens that precede the rule's rule text
227      * in the description) and sets the rule's base value, radix, and
228      * exponent according to the descriptor. (If the description doesn't
229      * include a rule descriptor, then this function sets everything to
230      * default values and the rule set sets the rule's real base value).
231      * @param description The rule's description
232      * @return If "description" included a rule descriptor, this is
233      * "description" with the descriptor and any trailing whitespace
234      * stripped off. Otherwise; it's "descriptor" unchangd.
235      */

236     private String JavaDoc parseRuleDescriptor(String JavaDoc description) {
237         String JavaDoc descriptor;
238
239         // the description consists of a rule descriptor and a rule body,
240
// separated by a colon. The rule descriptor is optional. If
241
// it's omitted, just set the base value to 0.
242
int p = description.indexOf(":");
243         if (p == -1) {
244             setBaseValue(0);
245         } else {
246             // copy the descriptor out into its own string and strip it,
247
// along with any trailing whitespace, out of the original
248
// description
249
descriptor = description.substring(0, p);
250             ++p;
251             while (p < description.length() && UCharacterProperty.isRuleWhiteSpace(description.charAt(p)))
252                 ++p;
253             description = description.substring(p);
254
255             // check first to see if the rule descriptor matches the token
256
// for one of the special rules. If it does, set the base
257
// value to the correct identfier value
258
if (descriptor.equals("-x")) {
259                 setBaseValue(NEGATIVE_NUMBER_RULE);
260             }
261             else if (descriptor.equals("x.x")) {
262                 setBaseValue(IMPROPER_FRACTION_RULE);
263             }
264             else if (descriptor.equals("0.x")) {
265                 setBaseValue(PROPER_FRACTION_RULE);
266             }
267             else if (descriptor.equals("x.0")) {
268                 setBaseValue(MASTER_RULE);
269             }
270
271             // if the rule descriptor begins with a digit, it's a descriptor
272
// for a normal rule
273
else if (descriptor.charAt(0) >= '0' && descriptor.charAt(0) <= '9') {
274                 StringBuffer JavaDoc tempValue = new StringBuffer JavaDoc();
275                 p = 0;
276                 char c = ' ';
277
278                 // begin parsing the descriptor: copy digits
279
// into "tempValue", skip periods, commas, and spaces,
280
// stop on a slash or > sign (or at the end of the string),
281
// and throw an exception on any other character
282
while (p < descriptor.length()) {
283                     c = descriptor.charAt(p);
284                     if (c >= '0' && c <= '9') {
285                         tempValue.append(c);
286                     }
287                     else if (c == '/' || c == '>') {
288                         break;
289                     }
290                     else if (UCharacterProperty.isRuleWhiteSpace(c) || c == ',' || c == '.') {
291                     }
292                     else {
293                         throw new IllegalArgumentException JavaDoc("Illegal character in rule descriptor");
294                     }
295                     ++p;
296                 }
297
298                 // tempValue now contains a string representation of the
299
// rule's base value with the punctuation stripped out.
300
// Set the rule's base value accordingly
301
setBaseValue(Long.parseLong(tempValue.toString()));
302
303                 // if we stopped the previous loop on a slash, we're
304
// now parsing the rule's radix. Again, accumulate digits
305
// in tempValue, skip punctuation, stop on a > mark, and
306
// throw an exception on anything else
307
if (c == '/') {
308                     tempValue.setLength(0);
309                     ++p;
310                     while (p < descriptor.length()) {
311                         c = descriptor.charAt(p);
312                         if (c >= '0' && c <= '9') {
313                             tempValue.append(c);
314                         }
315                         else if (c == '>') {
316                             break;
317                         }
318                         else if (UCharacterProperty.isRuleWhiteSpace(c) || c == ',' || c == '.') {
319                         }
320                         else {
321                             throw new IllegalArgumentException JavaDoc("Illegal character is rule descriptor");
322                         }
323                         ++p;
324                     }
325
326                     // tempValue now contain's the rule's radix. Set it
327
// accordingly, and recalculate the rule's exponent
328
radix = Integer.parseInt(tempValue.toString());
329                     if (radix == 0) {
330                         throw new IllegalArgumentException JavaDoc("Rule can't have radix of 0");
331                     }
332                     exponent = expectedExponent();
333                 }
334
335                 // if we stopped the previous loop on a > sign, then continue
336
// for as long as we still see > signs. For each one,
337
// decrement the exponent (unless the exponent is already 0).
338
// If we see another character before reaching the end of
339
// the descriptor, that's also a syntax error.
340
if (c == '>') {
341                     while (p < descriptor.length()) {
342                         c = descriptor.charAt(p);
343                         if (c == '>' && exponent > 0) {
344                             --exponent;
345                         } else {
346                             throw new IllegalArgumentException JavaDoc("Illegal character in rule descriptor");
347                         }
348                         ++p;
349                     }
350                 }
351             }
352         }
353
354         // finally, if the rule body begins with an apostrophe, strip it off
355
// (this is generally used to put whitespace at the beginning of
356
// a rule's rule text)
357
if (description.length() > 0 && description.charAt(0) == '\'') {
358             description = description.substring(1);
359         }
360
361         // return the description with all the stuff we've just waded through
362
// stripped off the front. It now contains just the rule body.
363
return description;
364     }
365
366     /**
367      * Searches the rule's rule text for the substitution tokens,
368      * creates the substitutions, and removes the substitution tokens
369      * from the rule's rule text.
370      * @param owner The rule set containing this rule
371      * @param predecessor The rule preseding this one in "owners" rule list
372      * @param ownersOwner The RuleBasedFormat that owns this rule
373      */

374     private void extractSubstitutions(NFRuleSet owner,
375                                       NFRule predecessor,
376                                       RuleBasedNumberFormat ownersOwner) {
377         sub1 = extractSubstitution(owner, predecessor, ownersOwner);
378         sub2 = extractSubstitution(owner, predecessor, ownersOwner);
379     }
380
381     /**
382      * Searches the rule's rule text for the first substitution token,
383      * creates a substitution based on it, and removes the token from
384      * the rule's rule text.
385      * @param owner The rule set containing this rule
386      * @param predecessor The rule preceding this one in the rule set's
387      * rule list
388      * @param ownersOwner The RuleBasedNumberFormat that owns this rule
389      * @return The newly-created substitution. This is never null; if
390      * the rule text doesn't contain any substitution tokens, this will
391      * be a NullSubstitution.
392      */

393     private NFSubstitution extractSubstitution(NFRuleSet owner,
394                                                NFRule predecessor,
395                                                RuleBasedNumberFormat ownersOwner) {
396         NFSubstitution result = null;
397         int subStart;
398         int subEnd;
399
400         // search the rule's rule text for the first two characters of
401
// a substitution token
402
subStart = indexOfAny(new String JavaDoc[] { "<<", "<%", "<#", "<0",
403                                              ">>", ">%", ">#", ">0",
404                                              "=%", "=#", "=0" } );
405
406         // if we didn't find one, create a null substitution positioned
407
// at the end of the rule text
408
if (subStart == -1) {
409             return NFSubstitution.makeSubstitution(ruleText.length(), this, predecessor,
410                                                    owner, ownersOwner, "");
411         }
412
413         // special-case the ">>>" token, since searching for the > at the
414
// end will actually find the > in the middle
415
if (ruleText.substring(subStart).startsWith(">>>")) {
416             subEnd = subStart + 2;
417
418             // otherwise the substitution token ends with the same character
419
// it began with
420
} else {
421             char c = ruleText.charAt(subStart);
422             subEnd = ruleText.indexOf(c, subStart + 1);
423             // special case for '<%foo<<'
424
if (c == '<' && subEnd != -1 && subEnd < ruleText.length() - 1 && ruleText.charAt(subEnd+1) == c) {
425                 // ordinals use "=#,##0==%abbrev=" as their rule. Notice that the '==' in the middle
426
// occurs because of the juxtaposition of two different rules. The check for '<' is a hack
427
// to get around this. Having the duplicate at the front would cause problems with
428
// rules like "<<%" to format, say, percents...
429
++subEnd;
430             }
431         }
432
433         // if we don't find the end of the token (i.e., if we're on a single,
434
// unmatched token character), create a null substitution positioned
435
// at the end of the rule
436
if (subEnd == -1) {
437             return NFSubstitution.makeSubstitution(ruleText.length(), this, predecessor,
438                                                    owner, ownersOwner, "");
439         }
440
441         // if we get here, we have a real substitution token (or at least
442
// some text bounded by substitution token characters). Use
443
// makeSubstitution() to create the right kind of substitution
444
result = NFSubstitution.makeSubstitution(subStart, this, predecessor, owner,
445                                                  ownersOwner, ruleText.substring(subStart, subEnd + 1));
446
447         // remove the substitution from the rule text
448
ruleText = ruleText.substring(0, subStart) + ruleText.substring(subEnd + 1);
449         return result;
450     }
451
452     /**
453      * Sets the rule's base value, and causes the radix and exponent
454      * to be recalculated. This is used during construction when we
455      * don't know the rule's base value until after it's been
456      * constructed. It should not be used at any other time.
457      * @param The new base value for the rule.
458      */

459     public final void setBaseValue(long newBaseValue) {
460         // set the base value
461
baseValue = newBaseValue;
462
463         // if this isn't a special rule, recalculate the radix and exponent
464
// (the radix always defaults to 10; if it's supposed to be something
465
// else, it's cleaned up by the caller and the exponent is
466
// recalculated again-- the only function that does this is
467
// NFRule.parseRuleDescriptor() )
468
if (baseValue >= 1) {
469             radix = 10;
470             exponent = expectedExponent();
471
472             // this function gets called on a fully-constructed rule whose
473
// description didn't specify a base value. This means it
474
// has substitutions, and some substitutions hold on to copies
475
// of the rule's divisor. Fix their copies of the divisor.
476
if (sub1 != null) {
477                 sub1.setDivisor(radix, exponent);
478             }
479             if (sub2 != null) {
480                 sub2.setDivisor(radix, exponent);
481             }
482
483             // if this is a special rule, its radix and exponent are basically
484
// ignored. Set them to "safe" default values
485
} else {
486             radix = 10;
487             exponent = 0;
488         }
489     }
490
491     /**
492      * This calculates the rule's exponent based on its radix and base
493      * value. This will be the highest power the radix can be raised to
494      * and still produce a result less than or equal to the base value.
495      */

496     private short expectedExponent() {
497         // since the log of 0, or the log base 0 of something, causes an
498
// error, declare the exponent in these cases to be 0 (we also
499
// deal with the special-rule identifiers here)
500
if (radix == 0 || baseValue < 1) {
501             return 0;
502         }
503
504         // we get rounding error in some cases-- for example, log 1000 / log 10
505
// gives us 1.9999999996 instead of 2. The extra logic here is to take
506
// that into account
507
short tempResult = (short)(Math.log(baseValue) / Math.log(radix));
508         if (Math.pow(radix, tempResult + 1) <= baseValue) {
509             return (short)(tempResult + 1);
510         } else {
511             return tempResult;
512         }
513     }
514
515     /**
516      * Searches the rule's rule text for any of the specified strings.
517      * @param strings An array of strings to search the rule's rule
518      * text for
519      * @return The index of the first match in the rule's rule text
520      * (i.e., the first substring in the rule's rule text that matches
521      * _any_ of the strings in "strings"). If none of the strings in
522      * "strings" is found in the rule's rule text, returns -1.
523      */

524     private int indexOfAny(String JavaDoc[] strings) {
525         int pos;
526         int result = -1;
527         for (int i = 0; i < strings.length; i++) {
528             pos = ruleText.indexOf(strings[i]);
529             if (pos != -1 && (result == -1 || pos < result)) {
530                 result = pos;
531             }
532         }
533         return result;
534     }
535
536     //-----------------------------------------------------------------------
537
// boilerplate
538
//-----------------------------------------------------------------------
539

540     /**
541      * Tests two rules for equality.
542      * @param that The rule to compare this one against
543      * @return True if the two rules are functionally equivalent
544      */

545     public boolean equals(Object JavaDoc that) {
546         if (that instanceof NFRule) {
547             NFRule that2 = (NFRule)that;
548
549             return baseValue == that2.baseValue
550                 && radix == that2.radix
551                 && exponent == that2.exponent
552                 && ruleText.equals(that2.ruleText)
553                 && sub1.equals(that2.sub1)
554                 && sub2.equals(that2.sub2);
555         }
556         return false;
557     }
558
559     /**
560      * Returns a textual representation of the rule. This won't
561      * necessarily be the same as the description that this rule
562      * was created with, but it will produce the same result.
563      * @return A textual description of the rule
564      */

565     public String JavaDoc toString() {
566         StringBuffer JavaDoc result = new StringBuffer JavaDoc();
567
568         // start with the rule descriptor. Special-case the special rules
569
if (baseValue == NEGATIVE_NUMBER_RULE) {
570             result.append("-x: ");
571         }
572         else if (baseValue == IMPROPER_FRACTION_RULE) {
573             result.append("x.x: ");
574         }
575         else if (baseValue == PROPER_FRACTION_RULE) {
576             result.append("0.x: ");
577         }
578         else if (baseValue == MASTER_RULE) {
579             result.append("x.0: ");
580         }
581
582         // for a normal rule, write out its base value, and if the radix is
583
// something other than 10, write out the radix (with the preceding
584
// slash, of course). Then calculate the expected exponent and if
585
// if isn't the same as the actual exponent, write an appropriate
586
// number of > signs. Finally, terminate the whole thing with
587
// a colon.
588
else {
589             result.append(String.valueOf(baseValue));
590             if (radix != 10) {
591                 result.append('/');
592                 result.append(String.valueOf(radix));
593             }
594             int numCarets = expectedExponent() - exponent;
595             for (int i = 0; i < numCarets; i++)
596                 result.append('>');
597             result.append(": ");
598         }
599
600         // if the rule text begins with a space, write an apostrophe
601
// (whitespace after the rule descriptor is ignored; the
602
// apostrophe is used to make the whitespace significant)
603
if (ruleText.startsWith(" ") && (sub1 == null || sub1.getPos() != 0)) {
604             result.append("\'");
605         }
606
607         // now, write the rule's rule text, inserting appropriate
608
// substitution tokens in the appropriate places
609
StringBuffer JavaDoc ruleTextCopy = new StringBuffer JavaDoc(ruleText);
610         ruleTextCopy.insert(sub2.getPos(), sub2.toString());
611         ruleTextCopy.insert(sub1.getPos(), sub1.toString());
612         result.append(ruleTextCopy.toString());
613
614         // and finally, top the whole thing off with a semicolon and
615
// return the result
616
result.append(';');
617         return result.toString();
618     }
619
620     //-----------------------------------------------------------------------
621
// simple accessors
622
//-----------------------------------------------------------------------
623

624     /**
625      * Returns the rule's base value
626      * @return The rule's base value
627      */

628     public final long getBaseValue() {
629         return baseValue;
630     }
631
632     /**
633      * Returns the rule's divisor (the value that cotrols the behavior
634      * of its substitutions)
635      * @return The rule's divisor
636      */

637     public double getDivisor() {
638         return Math.pow(radix, exponent);
639     }
640
641     //-----------------------------------------------------------------------
642
// formatting
643
//-----------------------------------------------------------------------
644

645     /**
646      * Formats the number, and inserts the resulting text into
647      * toInsertInto.
648      * @param number The number being formatted
649      * @param toInsertInto The string where the resultant text should
650      * be inserted
651      * @param pos The position in toInsertInto where the resultant text
652      * should be inserted
653      */

654     public void doFormat(long number, StringBuffer JavaDoc toInsertInto, int pos) {
655         // first, insert the rule's rule text into toInsertInto at the
656
// specified position, then insert the results of the substitutions
657
// into the right places in toInsertInto (notice we do the
658
// substitutions in reverse order so that the offsets don't get
659
// messed up)
660
toInsertInto.insert(pos, ruleText);
661         sub2.doSubstitution(number, toInsertInto, pos);
662         sub1.doSubstitution(number, toInsertInto, pos);
663     }
664
665     /**
666      * Formats the number, and inserts the resulting text into
667      * toInsertInto.
668      * @param number The number being formatted
669      * @param toInsertInto The string where the resultant text should
670      * be inserted
671      * @param pos The position in toInsertInto where the resultant text
672      * should be inserted
673      */

674     public void doFormat(double number, StringBuffer JavaDoc toInsertInto, int pos) {
675         // first, insert the rule's rule text into toInsertInto at the
676
// specified position, then insert the results of the substitutions
677
// into the right places in toInsertInto
678
// [again, we have two copies of this routine that do the same thing
679
// so that we don't sacrifice precision in a long by casting it
680
// to a double]
681
toInsertInto.insert(pos, ruleText);
682         sub2.doSubstitution(number, toInsertInto, pos);
683         sub1.doSubstitution(number, toInsertInto, pos);
684     }
685
686     /**
687      * Used by the owning rule set to determine whether to invoke the
688      * rollback rule (i.e., whether this rule or the one that precedes
689      * it in the rule set's list should be used to format the number)
690      * @param The number being formatted
691      * @return True if the rule set should use the rule that precedes
692      * this one in its list; false if it should use this rule
693      */

694     public boolean shouldRollBack(double number) {
695         // we roll back if the rule contains a modulus substitution,
696
// the number being formatted is an even multiple of the rule's
697
// divisor, and the rule's base value is NOT an even multiple
698
// of its divisor
699
// In other words, if the original description had
700
// 100: << hundred[ >>];
701
// that expands into
702
// 100: << hundred;
703
// 101: << hundred >>;
704
// internally. But when we're formatting 200, if we use the rule
705
// at 101, which would normally apply, we get "two hundred zero".
706
// To prevent this, we roll back and use the rule at 100 instead.
707
// This is the logic that makes this happen: the rule at 101 has
708
// a modulus substitution, its base value isn't an even multiple
709
// of 100, and the value we're trying to format _is_ an even
710
// multiple of 100. This is called the "rollback rule."
711
if ((sub1.isModulusSubstitution()) || (sub2.isModulusSubstitution())) {
712             return (number % Math.pow(radix, exponent)) == 0
713                 && (baseValue % Math.pow(radix, exponent)) != 0;
714         }
715         return false;
716     }
717
718     //-----------------------------------------------------------------------
719
// parsing
720
//-----------------------------------------------------------------------
721

722     /**
723      * Attempts to parse the string with this rule.
724      * @param text The string being parsed
725      * @param parsePosition On entry, the value is ignored and assumed to
726      * be 0. On exit, this has been updated with the position of the first
727      * character not consumed by matching the text against this rule
728      * (if this rule doesn't match the text at all, the parse position
729      * if left unchanged (presumably at 0) and the function returns
730      * new Long(0)).
731      * @param isFractionRule True if this rule is contained within a
732      * fraction rule set. This is only used if the rule has no
733      * substitutions.
734      * @return If this rule matched the text, this is the rule's base value
735      * combined appropriately with the results of parsing the substitutions.
736      * If nothing matched, this is new Long(0) and the parse position is
737      * left unchanged. The result will be an instance of Long if the
738      * result is an integer and Double otherwise. The result is never null.
739      */

740     public Number JavaDoc doParse(String JavaDoc text, ParsePosition parsePosition, boolean isFractionRule,
741                           double upperBound) {
742
743         // internally we operate on a copy of the string being parsed
744
// (because we're going to change it) and use our own ParsePosition
745
ParsePosition pp = new ParsePosition(0);
746         String JavaDoc workText = new String JavaDoc(text);
747
748         // check to see whether the text before the first substitution
749
// matches the text at the beginning of the string being
750
// parsed. If it does, strip that off the front of workText;
751
// otherwise, dump out with a mismatch
752
workText = stripPrefix(workText, ruleText.substring(0, sub1.getPos()), pp);
753         int prefixLength = text.length() - workText.length();
754
755         if (pp.getIndex() == 0 && sub1.getPos() != 0) {
756             // commented out because ParsePosition doesn't have error index in 1.1.x
757
// parsePosition.setErrorIndex(pp.getErrorIndex());
758
return new Long JavaDoc(0);
759         }
760
761         // this is the fun part. The basic guts of the rule-matching
762
// logic is matchToDelimiter(), which is called twice. The first
763
// time it searches the input string for the rule text BETWEEN
764
// the substitutions and tries to match the intervening text
765
// in the input string with the first substitution. If that
766
// succeeds, it then calls it again, this time to look for the
767
// rule text after the second substitution and to match the
768
// intervening input text against the second substitution.
769
//
770
// For example, say we have a rule that looks like this:
771
// first << middle >> last;
772
// and input text that looks like this:
773
// first one middle two last
774
// First we use stripPrefix() to match "first " in both places and
775
// strip it off the front, leaving
776
// one middle two last
777
// Then we use matchToDelimiter() to match " middle " and try to
778
// match "one" against a substitution. If it's successful, we now
779
// have
780
// two last
781
// We use matchToDelimiter() a second time to match " last" and
782
// try to match "two" against a substitution. If "two" matches
783
// the substitution, we have a successful parse.
784
//
785
// Since it's possible in many cases to find multiple instances
786
// of each of these pieces of rule text in the input string,
787
// we need to try all the possible combinations of these
788
// locations. This prevents us from prematurely declaring a mismatch,
789
// and makes sure we match as much input text as we can.
790
int highWaterMark = 0;
791         double result = 0;
792         int start = 0;
793         double tempBaseValue = Math.max(0, baseValue);
794
795         do {
796             // our partial parse result starts out as this rule's base
797
// value. If it finds a successful match, matchToDelimiter()
798
// will compose this in some way with what it gets back from
799
// the substitution, giving us a new partial parse result
800
pp.setIndex(0);
801             double partialResult = matchToDelimiter(workText, start, tempBaseValue,
802                                                     ruleText.substring(sub1.getPos(), sub2.getPos()), pp, sub1,
803                                                     upperBound).doubleValue();
804
805             // if we got a successful match (or were trying to match a
806
// null substitution), pp is now pointing at the first unmatched
807
// character. Take note of that, and try matchToDelimiter()
808
// on the input text again
809
if (pp.getIndex() != 0 || sub1.isNullSubstitution()) {
810                 start = pp.getIndex();
811
812                 String JavaDoc workText2 = workText.substring(pp.getIndex());
813                 ParsePosition pp2 = new ParsePosition(0);
814
815                 // the second matchToDelimiter() will compose our previous
816
// partial result with whatever it gets back from its
817
// substitution if there's a successful match, giving us
818
// a real result
819
partialResult = matchToDelimiter(workText2, 0, partialResult,
820                                                  ruleText.substring(sub2.getPos()), pp2, sub2,
821                                                  upperBound).doubleValue();
822
823                 // if we got a successful match on this second
824
// matchToDelimiter() call, update the high-water mark
825
// and result (if necessary)
826
if (pp2.getIndex() != 0 || sub2.isNullSubstitution()) {
827                     if (prefixLength + pp.getIndex() + pp2.getIndex() > highWaterMark) {
828                         highWaterMark = prefixLength + pp.getIndex() + pp2.getIndex();
829                         result = partialResult;
830                     }
831                 }
832                 // commented out because ParsePosition doesn't have error index in 1.1.x
833
// else {
834
// int temp = pp2.getErrorIndex() + sub1.getPos() + pp.getIndex();
835
// if (temp> parsePosition.getErrorIndex()) {
836
// parsePosition.setErrorIndex(temp);
837
// }
838
// }
839
}
840             // commented out because ParsePosition doesn't have error index in 1.1.x
841
// else {
842
// int temp = sub1.getPos() + pp.getErrorIndex();
843
// if (temp > parsePosition.getErrorIndex()) {
844
// parsePosition.setErrorIndex(temp);
845
// }
846
// }
847
// keep trying to match things until the outer matchToDelimiter()
848
// call fails to make a match (each time, it picks up where it
849
// left off the previous time)
850
} while (sub1.getPos() != sub2.getPos() && pp.getIndex() > 0 && pp.getIndex()
851                  < workText.length() && pp.getIndex() != start);
852
853         // update the caller's ParsePosition with our high-water mark
854
// (i.e., it now points at the first character this function
855
// didn't match-- the ParsePosition is therefore unchanged if
856
// we didn't match anything)
857
parsePosition.setIndex(highWaterMark);
858         // commented out because ParsePosition doesn't have error index in 1.1.x
859
// if (highWaterMark > 0) {
860
// parsePosition.setErrorIndex(0);
861
// }
862

863         // this is a hack for one unusual condition: Normally, whether this
864
// rule belong to a fraction rule set or not is handled by its
865
// substitutions. But if that rule HAS NO substitutions, then
866
// we have to account for it here. By definition, if the matching
867
// rule in a fraction rule set has no substitutions, its numerator
868
// is 1, and so the result is the reciprocal of its base value.
869
if (isFractionRule && highWaterMark > 0 && sub1.isNullSubstitution()) {
870             result = 1 / result;
871         }
872
873         // return the result as a Long if possible, or as a Double
874
if (result == (long)result) {
875             return new Long JavaDoc((long)result);
876         } else {
877             return new Double JavaDoc(result);
878         }
879     }
880
881     /**
882      * This function is used by parse() to match the text being parsed
883      * against a possible prefix string. This function
884      * matches characters from the beginning of the string being parsed
885      * to characters from the prospective prefix. If they match, pp is
886      * updated to the first character not matched, and the result is
887      * the unparsed part of the string. If they don't match, the whole
888      * string is returned, and pp is left unchanged.
889      * @param text The string being parsed
890      * @param prefix The text to match against
891      * @param pp On entry, ignored and assumed to be 0. On exit, points
892      * to the first unmatched character (assuming the whole prefix matched),
893      * or is unchanged (if the whole prefix didn't match).
894      * @return If things match, this is the unparsed part of "text";
895      * if they didn't match, this is "text".
896      */

897     private String JavaDoc stripPrefix(String JavaDoc text, String JavaDoc prefix, ParsePosition pp) {
898         // if the prefix text is empty, dump out without doing anything
899
if (prefix.length() == 0) {
900             return text;
901         } else {
902             // otherwise, use prefixLength() to match the beginning of
903
// "text" against "prefix". This function returns the
904
// number of characters from "text" that matched (or 0 if
905
// we didn't match the whole prefix)
906
int pfl = prefixLength(text, prefix);
907             if (pfl != 0) {
908                 // if we got a successful match, update the parse position
909
// and strip the prefix off of "text"
910
pp.setIndex(pp.getIndex() + pfl);
911                 return text.substring(pfl);
912
913                 // if we didn't get a successful match, leave everything alone
914
} else {
915                 return text;
916             }
917         }
918     }
919
920     /**
921      * Used by parse() to match a substitution and any following text.
922      * "text" is searched for instances of "delimiter". For each instance
923      * of delimiter, the intervening text is tested to see whether it
924      * matches the substitution. The longest match wins.
925      * @param text The string being parsed
926      * @param startPos The position in "text" where we should start looking
927      * for "delimiter".
928      * @param baseValue A partial parse result (often the rule's base value),
929      * which is combined with the result from matching the substitution
930      * @param delimiter The string to search "text" for.
931      * @param pp Ignored and presumed to be 0 on entry. If there's a match,
932      * on exit this will point to the first unmatched character.
933      * @param sub If we find "delimiter" in "text", this substitution is used
934      * to match the text between the beginning of the string and the
935      * position of "delimiter." (If "delimiter" is the empty string, then
936      * this function just matches against this substitution and updates
937      * everything accordingly.)
938      * @param upperBound When matching the substitution, it will only
939      * consider rules with base values lower than this value.
940      * @return If there's a match, this is the result of composing
941      * baseValue with the result of matching the substitution. Otherwise,
942      * this is new Long(0). It's never null. If the result is an integer,
943      * this will be an instance of Long; otherwise, it's an instance of
944      * Double.
945      */

946     private Number JavaDoc matchToDelimiter(String JavaDoc text, int startPos, double baseValue,
947                                     String JavaDoc delimiter, ParsePosition pp, NFSubstitution sub, double upperBound) {
948         // if "delimiter" contains real (i.e., non-ignorable) text, search
949
// it for "delimiter" beginning at "start". If that succeeds, then
950
// use "sub"'s doParse() method to match the text before the
951
// instance of "delimiter" we just found.
952
if (!allIgnorable(delimiter)) {
953             ParsePosition tempPP = new ParsePosition(0);
954             Number JavaDoc tempResult;
955
956             // use findText() to search for "delimiter". It returns a two-
957
// element array: element 0 is the position of the match, and
958
// element 1 is the number of characters that matched
959
// "delimiter".
960
int[] temp = findText(text, delimiter, startPos);
961             int dPos = temp[0];
962             int dLen = temp[1];
963
964             // if findText() succeeded, isolate the text preceding the
965
// match, and use "sub" to match that text
966
while (dPos >= 0) {
967                 String JavaDoc subText = text.substring(0, dPos);
968                 if (subText.length() > 0) {
969                     tempResult = sub.doParse(subText, tempPP, baseValue, upperBound,
970                                              formatter.lenientParseEnabled());
971
972                     // if the substitution could match all the text up to
973
// where we found "delimiter", then this function has
974
// a successful match. Bump the caller's parse position
975
// to point to the first character after the text
976
// that matches "delimiter", and return the result
977
// we got from parsing the substitution.
978
if (tempPP.getIndex() == dPos) {
979                         pp.setIndex(dPos + dLen);
980                         return tempResult;
981                     }
982                     // commented out because ParsePosition doesn't have error index in 1.1.x
983
// else {
984
// if (tempPP.getErrorIndex() > 0) {
985
// pp.setErrorIndex(tempPP.getErrorIndex());
986
// } else {
987
// pp.setErrorIndex(tempPP.getIndex());
988
// }
989
// }
990
}
991
992                 // if we didn't match the substitution, search for another
993
// copy of "delimiter" in "text" and repeat the loop if
994
// we find it
995
tempPP.setIndex(0);
996                 temp = findText(text, delimiter, dPos + dLen);
997                 dPos = temp[0];
998                 dLen = temp[1];
999             }
1000            // if we make it here, this was an unsuccessful match, and we
1001
// leave pp unchanged and return 0
1002
pp.setIndex(0);
1003            return new Long JavaDoc(0);
1004
1005            // if "delimiter" is empty, or consists only of ignorable characters
1006
// (i.e., is semantically empty), thwe we obviously can't search
1007
// for "delimiter". Instead, just use "sub" to parse as much of
1008
// "text" as possible.
1009
} else {
1010            ParsePosition tempPP = new ParsePosition(0);
1011            Number JavaDoc result = new Long JavaDoc(0);
1012            Number JavaDoc tempResult;
1013
1014            // try to match the whole string against the substitution
1015
tempResult = sub.doParse(text, tempPP, baseValue, upperBound,
1016                                     formatter.lenientParseEnabled());
1017            if (tempPP.getIndex() != 0 || sub.isNullSubstitution()) {
1018                // if there's a successful match (or it's a null
1019
// substitution), update pp to point to the first
1020
// character we didn't match, and pass the result from
1021
// sub.doParse() on through to the caller
1022
pp.setIndex(tempPP.getIndex());
1023                if (tempResult != null) {
1024                    result = tempResult;
1025                }
1026            }
1027            // commented out because ParsePosition doesn't have error index in 1.1.x
1028
// else {
1029
// pp.setErrorIndex(tempPP.getErrorIndex());
1030
// }
1031

1032            // and if we get to here, then nothing matched, so we return
1033
// 0 and leave pp alone
1034
return result;
1035        }
1036    }
1037
1038    /**
1039     * Used by stripPrefix() to match characters. If lenient parse mode
1040     * is off, this just calls startsWith(). If lenient parse mode is on,
1041     * this function uses CollationElementIterators to match characters in
1042     * the strings (only primary-order differences are significant in
1043     * determining whether there's a match).
1044     * @param str The string being tested
1045     * @param prefix The text we're hoping to see at the beginning
1046     * of "str"
1047     * @return If "prefix" is found at the beginning of "str", this
1048     * is the number of characters in "str" that were matched (this
1049     * isn't necessarily the same as the length of "prefix" when matching
1050     * text with a collator). If there's no match, this is 0.
1051     */

1052    private int prefixLength(String JavaDoc str, String JavaDoc prefix) {
1053        // if we're looking for an empty prefix, it obviously matches
1054
// zero characters. Just go ahead and return 0.
1055
if (prefix.length() == 0) {
1056            return 0;
1057        }
1058
1059        // go through all this grief if we're in lenient-parse mode
1060
if (formatter.lenientParseEnabled()) {
1061            // get the formatter's collator and use it to create two
1062
// collation element iterators, one over the target string
1063
// and another over the prefix (right now, we'll throw an
1064
// exception if the collator we get back from the formatter
1065
// isn't a RuleBasedCollator, because RuleBasedCollator defines
1066
// the CollationElementIteratoer protocol. Hopefully, this
1067
// will change someday.)
1068
//
1069
// Previous code was matching "fifty-" against " fifty" and leaving
1070
// the number " fifty-7" to parse as 43 (50 - 7).
1071
// Also it seems that if we consume the entire prefix, that's ok even
1072
// if we've consumed the entire string, so I switched the logic to
1073
// reflect this.
1074
RuleBasedCollator collator = (RuleBasedCollator)formatter.getCollator();
1075            CollationElementIterator strIter = collator.getCollationElementIterator(str);
1076            CollationElementIterator prefixIter = collator.getCollationElementIterator(prefix);
1077
1078            // match collation elements between the strings
1079
int oStr = strIter.next();
1080            int oPrefix = prefixIter.next();
1081
1082            while (oPrefix != CollationElementIterator.NULLORDER) {
1083                // skip over ignorable characters in the target string
1084
while (CollationElementIterator.primaryOrder(oStr) == 0 && oStr !=
1085                       CollationElementIterator.NULLORDER) {
1086                    oStr = strIter.next();
1087                }
1088
1089                // skip over ignorable characters in the prefix
1090
while (CollationElementIterator.primaryOrder(oPrefix) == 0 && oPrefix !=
1091                       CollationElementIterator.NULLORDER) {
1092                    oPrefix = prefixIter.next();
1093                }
1094
1095                // if skipping over ignorables brought to the end of
1096
// the prefix, we DID match: drop out of the loop
1097
if (oPrefix == CollationElementIterator.NULLORDER) {
1098                    break;
1099                }
1100
1101                // if skipping over ignorables brought us to the end
1102
// of the target string, we didn't match and return 0
1103
if (oStr == CollationElementIterator.NULLORDER) {
1104                    return 0;
1105                }
1106
1107                // match collation elements from the two strings
1108
// (considering only primary differences). If we
1109
// get a mismatch, dump out and return 0
1110
if (CollationElementIterator.primaryOrder(oStr) != CollationElementIterator.
1111                    primaryOrder(oPrefix)) {
1112                    return 0;
1113                }
1114                // otherwise, advance to the next character in each string
1115
// and loop (we drop out of the loop when we exhaust
1116
// collation elements in the prefix)
1117

1118                oStr = strIter.next();
1119                oPrefix = prefixIter.next();
1120            }
1121
1122            // we are not compatible with jdk 1.1 any longer
1123
int result = strIter.getOffset();
1124            if (oStr != CollationElementIterator.NULLORDER) {
1125                --result;
1126            }
1127            return result;
1128
1129            /*
1130              //----------------------------------------------------------------
1131              // JDK 1.2-specific API call
1132              // return strIter.getOffset();
1133              //----------------------------------------------------------------
1134              // JDK 1.1 HACK (take out for 1.2-specific code)
1135
1136              // if we make it to here, we have a successful match. Now we
1137              // have to find out HOW MANY characters from the target string
1138              // matched the prefix (there isn't necessarily a one-to-one
1139              // mapping between collation elements and characters).
1140              // In JDK 1.2, there's a simple getOffset() call we can use.
1141              // In JDK 1.1, on the other hand, we have to go through some
1142              // ugly contortions. First, use the collator to compare the
1143              // same number of characters from the prefix and target string.
1144              // If they're equal, we're done.
1145              collator.setStrength(Collator.PRIMARY);
1146              if (str.length() >= prefix.length()
1147              && collator.equals(str.substring(0, prefix.length()), prefix)) {
1148              return prefix.length();
1149              }
1150
1151              // if they're not equal, then we have to compare successively
1152              // larger and larger substrings of the target string until we
1153              // get to one that matches the prefix. At that point, we know
1154              // how many characters matched the prefix, and we can return.
1155              int p = 1;
1156              while (p <= str.length()) {
1157              if (collator.equals(str.substring(0, p), prefix)) {
1158              return p;
1159              } else {
1160              ++p;
1161              }
1162              }
1163
1164              // SHOULKD NEVER GET HERE!!!
1165              return 0;
1166              //----------------------------------------------------------------
1167            */

1168
1169            // If lenient parsing is turned off, forget all that crap above.
1170
// Just use String.startsWith() and be done with it.
1171
} else {
1172            if (str.startsWith(prefix)) {
1173                return prefix.length();
1174            } else {
1175                return 0;
1176            }
1177        }
1178    }
1179
1180    /**
1181     * Searches a string for another string. If lenient parsing is off,
1182     * this just calls indexOf(). If lenient parsing is on, this function
1183     * uses CollationElementIterator to match characters, and only
1184     * primary-order differences are significant in determining whether
1185     * there's a match.
1186     * @param str The string to search
1187     * @param key The string to search "str" for
1188     * @return A two-element array of ints. Element 0 is the position
1189     * of the match, or -1 if there was no match. Element 1 is the
1190     * number of characters in "str" that matched (which isn't necessarily
1191     * the same as the length of "key")
1192     */

1193    private int[] findText(String JavaDoc str, String JavaDoc key) {
1194        return findText(str, key, 0);
1195    }
1196
1197    /**
1198     * Searches a string for another string. If lenient parsing is off,
1199     * this just calls indexOf(). If lenient parsing is on, this function
1200     * uses CollationElementIterator to match characters, and only
1201     * primary-order differences are significant in determining whether
1202     * there's a match.
1203     * @param str The string to search
1204     * @param key The string to search "str" for
1205     * @param startingAt The index into "str" where the search is to
1206     * begin
1207     * @return A two-element array of ints. Element 0 is the position
1208     * of the match, or -1 if there was no match. Element 1 is the
1209     * number of characters in "str" that matched (which isn't necessarily
1210     * the same as the length of "key")
1211     */

1212    private int[] findText(String JavaDoc str, String JavaDoc key, int startingAt) {
1213        // if lenient parsing is turned off, this is easy: just call
1214
// String.indexOf() and we're done
1215
if (!formatter.lenientParseEnabled()) {
1216            return new int[] { str.indexOf(key, startingAt), key.length() };
1217
1218            // but if lenient parsing is turned ON, we've got some work
1219
// ahead of us
1220
} else {
1221            //----------------------------------------------------------------
1222
// JDK 1.1 HACK (take out of 1.2-specific code)
1223

1224            // in JDK 1.2, CollationElementIterator provides us with an
1225
// API to map between character offsets and collation elements
1226
// and we can do this by marching through the string comparing
1227
// collation elements. We can't do that in JDK 1.1. Insted,
1228
// we have to go through this horrible slow mess:
1229
int p = startingAt;
1230            int keyLen = 0;
1231
1232            // basically just isolate smaller and smaller substrings of
1233
// the target string (each running to the end of the string,
1234
// and with the first one running from startingAt to the end)
1235
// and then use prefixLength() to see if the search key is at
1236
// the beginning of each substring. This is excruciatingly
1237
// slow, but it will locate the key and tell use how long the
1238
// matching text was.
1239
while (p < str.length() && keyLen == 0) {
1240                keyLen = prefixLength(str.substring(p), key);
1241                if (keyLen != 0) {
1242                    return new int[] { p, keyLen };
1243                }
1244                ++p;
1245            }
1246            // if we make it to here, we didn't find it. Return -1 for the
1247
// location. The length should be ignored, but set it to 0,
1248
// which should be "safe"
1249
return new int[] { -1, 0 };
1250
1251            //----------------------------------------------------------------
1252
// JDK 1.2 version of this routine
1253
//RuleBasedCollator collator = (RuleBasedCollator)formatter.getCollator();
1254
//
1255
//CollationElementIterator strIter = collator.getCollationElementIterator(str);
1256
//CollationElementIterator keyIter = collator.getCollationElementIterator(key);
1257
//
1258
//int keyStart = -1;
1259
//
1260
//str.setOffset(startingAt);
1261
//
1262
//int oStr = strIter.next();
1263
//int oKey = keyIter.next();
1264
//while (oKey != CollationElementIterator.NULLORDER) {
1265
// while (oStr != CollationElementIterator.NULLORDER &&
1266
// CollationElementIterator.primaryOrder(oStr) == 0)
1267
// oStr = strIter.next();
1268
//
1269
// while (oKey != CollationElementIterator.NULLORDER &&
1270
// CollationElementIterator.primaryOrder(oKey) == 0)
1271
// oKey = keyIter.next();
1272
//
1273
// if (oStr == CollationElementIterator.NULLORDER) {
1274
// return new int[] { -1, 0 };
1275
// }
1276
//
1277
// if (oKey == CollationElementIterator.NULLORDER) {
1278
// break;
1279
// }
1280
//
1281
// if (CollationElementIterator.primaryOrder(oStr) ==
1282
// CollationElementIterator.primaryOrder(oKey)) {
1283
// keyStart = strIter.getOffset();
1284
// oStr = strIter.next();
1285
// oKey = keyIter.next();
1286
// } else {
1287
// if (keyStart != -1) {
1288
// keyStart = -1;
1289
// keyIter.reset();
1290
// } else {
1291
// oStr = strIter.next();
1292
// }
1293
// }
1294
//}
1295
//
1296
//if (oKey == CollationElementIterator.NULLORDER) {
1297
// return new int[] { keyStart, strIter.getOffset() - keyStart };
1298
//} else {
1299
// return new int[] { -1, 0 };
1300
//}
1301
}
1302    }
1303
1304    /**
1305     * Checks to see whether a string consists entirely of ignorable
1306     * characters.
1307     * @param str The string to test.
1308     * @return true if the string is empty of consists entirely of
1309     * characters that the number formatter's collator says are
1310     * ignorable at the primary-order level. false otherwise.
1311     */

1312    private boolean allIgnorable(String JavaDoc str) {
1313        // if the string is empty, we can just return true
1314
if (str.length() == 0) {
1315            return true;
1316        }
1317
1318        // if lenient parsing is turned on, walk through the string with
1319
// a collation element iterator and make sure each collation
1320
// element is 0 (ignorable) at the primary level
1321
if (formatter.lenientParseEnabled()) {
1322            RuleBasedCollator collator = (RuleBasedCollator)(formatter.getCollator());
1323            CollationElementIterator iter = collator.getCollationElementIterator(str);
1324
1325            int o = iter.next();
1326            while (o != CollationElementIterator.NULLORDER
1327                   && CollationElementIterator.primaryOrder(o) == 0) {
1328                o = iter.next();
1329            }
1330            return o == CollationElementIterator.NULLORDER;
1331            // if lenient parsing is turned off, there is no such thing as
1332
// an ignorable character: return true only if the string is empty
1333
} else {
1334            return false;
1335        }
1336    }
1337}
1338
Popular Tags