KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > java > text > RuleBasedCollator


1 /*
2  * @(#)RuleBasedCollator.java 1.37 03/12/19
3  *
4  * Copyright 2004 Sun Microsystems, Inc. All rights reserved.
5  * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
6  */

7
8 /*
9  * (C) Copyright Taligent, Inc. 1996, 1997 - All Rights Reserved
10  * (C) Copyright IBM Corp. 1996-1998 - All Rights Reserved
11  *
12  * The original version of this source code and documentation is copyrighted
13  * and owned by Taligent, Inc., a wholly-owned subsidiary of IBM. These
14  * materials are provided under terms of a License Agreement between Taligent
15  * and Sun. This technology is protected by multiple US and International
16  * patents. This notice and attribution to Taligent may not be removed.
17  * Taligent is a registered trademark of Taligent, Inc.
18  *
19  */

20
21 package java.text;
22
23 import java.util.Vector JavaDoc;
24 import java.util.Locale JavaDoc;
25 import sun.text.Normalizer;
26 import sun.text.NormalizerUtilities;
27
28 /**
29  * The <code>RuleBasedCollator</code> class is a concrete subclass of
30  * <code>Collator</code> that provides a simple, data-driven, table
31  * collator. With this class you can create a customized table-based
32  * <code>Collator</code>. <code>RuleBasedCollator</code> maps
33  * characters to sort keys.
34  *
35  * <p>
36  * <code>RuleBasedCollator</code> has the following restrictions
37  * for efficiency (other subclasses may be used for more complex languages) :
38  * <ol>
39  * <li>If a special collation rule controlled by a &lt;modifier&gt; is
40       specified it applies to the whole collator object.
41  * <li>All non-mentioned characters are at the end of the
42  * collation order.
43  * </ol>
44  *
45  * <p>
46  * The collation table is composed of a list of collation rules, where each
47  * rule is of one of three forms:
48  * <pre>
49  * &lt;modifier&gt;
50  * &lt;relation&gt; &lt;text-argument&gt;
51  * &lt;reset&gt; &lt;text-argument&gt;
52  * </pre>
53  * The definitions of the rule elements is as follows:
54  * <UL Type=disc>
55  * <LI><strong>Text-Argument</strong>: A text-argument is any sequence of
56  * characters, excluding special characters (that is, common
57  * whitespace characters [0009-000D, 0020] and rule syntax characters
58  * [0021-002F, 003A-0040, 005B-0060, 007B-007E]). If those
59  * characters are desired, you can put them in single quotes
60  * (e.g. ampersand => '&'). Note that unquoted white space characters
61  * are ignored; e.g. <code>b c</code> is treated as <code>bc</code>.
62  * <LI><strong>Modifier</strong>: There are currently two modifiers that
63  * turn on special collation rules.
64  * <UL Type=square>
65  * <LI>'@' : Turns on backwards sorting of accents (secondary
66  * differences), as in French.
67  * <LI>'!' : Turns on Thai/Lao vowel-consonant swapping. If this
68  * rule is in force when a Thai vowel of the range
69  * &#92;U0E40-&#92;U0E44 precedes a Thai consonant of the range
70  * &#92;U0E01-&#92;U0E2E OR a Lao vowel of the range &#92;U0EC0-&#92;U0EC4
71  * precedes a Lao consonant of the range &#92;U0E81-&#92;U0EAE then
72  * the vowel is placed after the consonant for collation
73  * purposes.
74  * </UL>
75  * <p>'@' : Indicates that accents are sorted backwards, as in French.
76  * <LI><strong>Relation</strong>: The relations are the following:
77  * <UL Type=square>
78  * <LI>'&lt;' : Greater, as a letter difference (primary)
79  * <LI>';' : Greater, as an accent difference (secondary)
80  * <LI>',' : Greater, as a case difference (tertiary)
81  * <LI>'=' : Equal
82  * </UL>
83  * <LI><strong>Reset</strong>: There is a single reset
84  * which is used primarily for contractions and expansions, but which
85  * can also be used to add a modification at the end of a set of rules.
86  * <p>'&' : Indicates that the next rule follows the position to where
87  * the reset text-argument would be sorted.
88  * </UL>
89  *
90  * <p>
91  * This sounds more complicated than it is in practice. For example, the
92  * following are equivalent ways of expressing the same thing:
93  * <blockquote>
94  * <pre>
95  * a &lt; b &lt; c
96  * a &lt; b &amp; b &lt; c
97  * a &lt; c &amp; a &lt; b
98  * </pre>
99  * </blockquote>
100  * Notice that the order is important, as the subsequent item goes immediately
101  * after the text-argument. The following are not equivalent:
102  * <blockquote>
103  * <pre>
104  * a &lt; b &amp; a &lt; c
105  * a &lt; c &amp; a &lt; b
106  * </pre>
107  * </blockquote>
108  * Either the text-argument must already be present in the sequence, or some
109  * initial substring of the text-argument must be present. (e.g. "a &lt; b &amp; ae &lt;
110  * e" is valid since "a" is present in the sequence before "ae" is reset). In
111  * this latter case, "ae" is not entered and treated as a single character;
112  * instead, "e" is sorted as if it were expanded to two characters: "a"
113  * followed by an "e". This difference appears in natural languages: in
114  * traditional Spanish "ch" is treated as though it contracts to a single
115  * character (expressed as "c &lt; ch &lt; d"), while in traditional German
116  * a-umlaut is treated as though it expanded to two characters
117  * (expressed as "a,A &lt; b,B ... &amp;ae;&#92;u00e3&amp;AE;&#92;u00c3").
118  * [&#92;u00e3 and &#92;u00c3 are, of course, the escape sequences for a-umlaut.]
119  * <p>
120  * <strong>Ignorable Characters</strong>
121  * <p>
122  * For ignorable characters, the first rule must start with a relation (the
123  * examples we have used above are really fragments; "a &lt; b" really should be
124  * "&lt; a &lt; b"). If, however, the first relation is not "&lt;", then all the all
125  * text-arguments up to the first "&lt;" are ignorable. For example, ", - &lt; a &lt; b"
126  * makes "-" an ignorable character, as we saw earlier in the word
127  * "black-birds". In the samples for different languages, you see that most
128  * accents are ignorable.
129  *
130  * <p><strong>Normalization and Accents</strong>
131  * <p>
132  * <code>RuleBasedCollator</code> automatically processes its rule table to
133  * include both pre-composed and combining-character versions of
134  * accented characters. Even if the provided rule string contains only
135  * base characters and separate combining accent characters, the pre-composed
136  * accented characters matching all canonical combinations of characters from
137  * the rule string will be entered in the table.
138  * <p>
139  * This allows you to use a RuleBasedCollator to compare accented strings
140  * even when the collator is set to NO_DECOMPOSITION. There are two caveats,
141  * however. First, if the strings to be collated contain combining
142  * sequences that may not be in canonical order, you should set the collator to
143  * CANONICAL_DECOMPOSITION or FULL_DECOMPOSITION to enable sorting of
144  * combining sequences. Second, if the strings contain characters with
145  * compatibility decompositions (such as full-width and half-width forms),
146  * you must use FULL_DECOMPOSITION, since the rule tables only include
147  * canonical mappings.
148  *
149  * <p><strong>Errors</strong>
150  * <p>
151  * The following are errors:
152  * <UL Type=disc>
153  * <LI>A text-argument contains unquoted punctuation symbols
154  * (e.g. "a &lt; b-c &lt; d").
155  * <LI>A relation or reset character not followed by a text-argument
156  * (e.g. "a &lt; ,b").
157  * <LI>A reset where the text-argument (or an initial substring of the
158  * text-argument) is not already in the sequence.
159  * (e.g. "a &lt; b &amp; e &lt; f")
160  * </UL>
161  * If you produce one of these errors, a <code>RuleBasedCollator</code> throws
162  * a <code>ParseException</code>.
163  *
164  * <p><strong>Examples</strong>
165  * <p>Simple: "&lt; a &lt; b &lt; c &lt; d"
166  * <p>Norwegian: "&lt; a,A&lt; b,B&lt; c,C&lt; d,D&lt; e,E&lt; f,F&lt; g,G&lt; h,H&lt; i,I&lt; j,J
167  * &lt; k,K&lt; l,L&lt; m,M&lt; n,N&lt; o,O&lt; p,P&lt; q,Q&lt; r,R&lt; s,S&lt; t,T
168  * &lt; u,U&lt; v,V&lt; w,W&lt; x,X&lt; y,Y&lt; z,Z
169  * &lt; &#92;u00E5=a&#92;u030A,&#92;u00C5=A&#92;u030A
170  * ;aa,AA&lt; &#92;u00E6,&#92;u00C6&lt; &#92;u00F8,&#92;u00D8"
171  *
172  * <p>
173  * Normally, to create a rule-based Collator object, you will use
174  * <code>Collator</code>'s factory method <code>getInstance</code>.
175  * However, to create a rule-based Collator object with specialized
176  * rules tailored to your needs, you construct the <code>RuleBasedCollator</code>
177  * with the rules contained in a <code>String</code> object. For example:
178  * <blockquote>
179  * <pre>
180  * String Simple = "&lt; a&lt; b&lt; c&lt; d";
181  * RuleBasedCollator mySimple = new RuleBasedCollator(Simple);
182  * </pre>
183  * </blockquote>
184  * Or:
185  * <blockquote>
186  * <pre>
187  * String Norwegian = "&lt; a,A&lt; b,B&lt; c,C&lt; d,D&lt; e,E&lt; f,F&lt; g,G&lt; h,H&lt; i,I&lt; j,J" +
188  * "&lt; k,K&lt; l,L&lt; m,M&lt; n,N&lt; o,O&lt; p,P&lt; q,Q&lt; r,R&lt; s,S&lt; t,T" +
189  * "&lt; u,U&lt; v,V&lt; w,W&lt; x,X&lt; y,Y&lt; z,Z" +
190  * "&lt; &#92;u00E5=a&#92;u030A,&#92;u00C5=A&#92;u030A" +
191  * ";aa,AA&lt; &#92;u00E6,&#92;u00C6&lt; &#92;u00F8,&#92;u00D8";
192  * RuleBasedCollator myNorwegian = new RuleBasedCollator(Norwegian);
193  * </pre>
194  * </blockquote>
195  *
196  * <p>
197  * Combining <code>Collator</code>s is as simple as concatenating strings.
198  * Here's an example that combines two <code>Collator</code>s from two
199  * different locales:
200  * <blockquote>
201  * <pre>
202  * // Create an en_US Collator object
203  * RuleBasedCollator en_USCollator = (RuleBasedCollator)
204  * Collator.getInstance(new Locale("en", "US", ""));
205  * // Create a da_DK Collator object
206  * RuleBasedCollator da_DKCollator = (RuleBasedCollator)
207  * Collator.getInstance(new Locale("da", "DK", ""));
208  * // Combine the two
209  * // First, get the collation rules from en_USCollator
210  * String en_USRules = en_USCollator.getRules();
211  * // Second, get the collation rules from da_DKCollator
212  * String da_DKRules = da_DKCollator.getRules();
213  * RuleBasedCollator newCollator =
214  * new RuleBasedCollator(en_USRules + da_DKRules);
215  * // newCollator has the combined rules
216  * </pre>
217  * </blockquote>
218  *
219  * <p>
220  * Another more interesting example would be to make changes on an existing
221  * table to create a new <code>Collator</code> object. For example, add
222  * "&amp;C&lt; ch, cH, Ch, CH" to the <code>en_USCollator</code> object to create
223  * your own:
224  * <blockquote>
225  * <pre>
226  * // Create a new Collator object with additional rules
227  * String addRules = "&amp;C&lt; ch, cH, Ch, CH";
228  * RuleBasedCollator myCollator =
229  * new RuleBasedCollator(en_USCollator + addRules);
230  * // myCollator contains the new rules
231  * </pre>
232  * </blockquote>
233  *
234  * <p>
235  * The following example demonstrates how to change the order of
236  * non-spacing accents,
237  * <blockquote>
238  * <pre>
239  * // old rule
240  * String oldRules = "=&#92;u0301;&#92;u0300;&#92;u0302;&#92;u0308" // main accents
241  * + ";&#92;u0327;&#92;u0303;&#92;u0304;&#92;u0305" // main accents
242  * + ";&#92;u0306;&#92;u0307;&#92;u0309;&#92;u030A" // main accents
243  * + ";&#92;u030B;&#92;u030C;&#92;u030D;&#92;u030E" // main accents
244  * + ";&#92;u030F;&#92;u0310;&#92;u0311;&#92;u0312" // main accents
245  * + "&lt; a , A ; ae, AE ; &#92;u00e6 , &#92;u00c6"
246  * + "&lt; b , B &lt; c, C &lt; e, E & C &lt; d, D";
247  * // change the order of accent characters
248  * String addOn = "& &#92;u0300 ; &#92;u0308 ; &#92;u0302";
249  * RuleBasedCollator myCollator = new RuleBasedCollator(oldRules + addOn);
250  * </pre>
251  * </blockquote>
252  *
253  * <p>
254  * The last example shows how to put new primary ordering in before the
255  * default setting. For example, in Japanese <code>Collator</code>, you
256  * can either sort English characters before or after Japanese characters,
257  * <blockquote>
258  * <pre>
259  * // get en_US Collator rules
260  * RuleBasedCollator en_USCollator = (RuleBasedCollator)Collator.getInstance(Locale.US);
261  * // add a few Japanese character to sort before English characters
262  * // suppose the last character before the first base letter 'a' in
263  * // the English collation rule is &#92;u2212
264  * String jaString = "& &#92;u2212 &lt; &#92;u3041, &#92;u3042 &lt; &#92;u3043, &#92;u3044";
265  * RuleBasedCollator myJapaneseCollator = new
266  * RuleBasedCollator(en_USCollator.getRules() + jaString);
267  * </pre>
268  * </blockquote>
269  *
270  * @see Collator
271  * @see CollationElementIterator
272  * @version 1.25 07/24/98
273  * @author Helena Shih, Laura Werner, Richard Gillam
274  */

275 public class RuleBasedCollator extends Collator JavaDoc{
276     // IMPLEMENTATION NOTES: The implementation of the collation algorithm is
277
// divided across three classes: RuleBasedCollator, RBCollationTables, and
278
// CollationElementIterator. RuleBasedCollator contains the collator's
279
// transient state and includes the code that uses the other classes to
280
// implement comparison and sort-key building. RuleBasedCollator also
281
// contains the logic to handle French secondary accent sorting.
282
// A RuleBasedCollator has two CollationElementIterators. State doesn't
283
// need to be preserved in these objects between calls to compare() or
284
// getCollationKey(), but the objects persist anyway to avoid wasting extra
285
// creation time. compare() and getCollationKey() are synchronized to ensure
286
// thread safety with this scheme. The CollationElementIterator is responsible
287
// for generating collation elements from strings and returning one element at
288
// a time (sometimes there's a one-to-many or many-to-one mapping between
289
// characters and collation elements-- this class handles that).
290
// CollationElementIterator depends on RBCollationTables, which contains the
291
// collator's static state. RBCollationTables contains the actual data
292
// tables specifying the collation order of characters for a particular locale
293
// or use. It also contains the base logic that CollationElementIterator
294
// uses to map from characters to collation elements. A single RBCollationTables
295
// object is shared among all RuleBasedCollators for the same locale, and
296
// thus by all the CollationElementIterators they create.
297

298     /**
299      * RuleBasedCollator constructor. This takes the table rules and builds
300      * a collation table out of them. Please see RuleBasedCollator class
301      * description for more details on the collation rule syntax.
302      * @see java.util.Locale
303      * @param rules the collation rules to build the collation table from.
304      * @exception ParseException A format exception
305      * will be thrown if the build process of the rules fails. For
306      * example, build rule "a < ? < d" will cause the constructor to
307      * throw the ParseException because the '?' is not quoted.
308      */

309     public RuleBasedCollator(String JavaDoc rules) throws ParseException JavaDoc {
310         this(rules, Collator.CANONICAL_DECOMPOSITION);
311     }
312
313     /**
314      * RuleBasedCollator constructor. This takes the table rules and builds
315      * a collation table out of them. Please see RuleBasedCollator class
316      * description for more details on the collation rule syntax.
317      * @see java.util.Locale
318      * @param rules the collation rules to build the collation table from.
319      * @param decomp the decomposition strength used to build the
320      * collation table and to perform comparisons.
321      * @exception ParseException A format exception
322      * will be thrown if the build process of the rules fails. For
323      * example, build rule "a < ? < d" will cause the constructor to
324      * throw the ParseException because the '?' is not quoted.
325      */

326     RuleBasedCollator(String JavaDoc rules, int decomp) throws ParseException JavaDoc {
327         setStrength(Collator.TERTIARY);
328         setDecomposition(decomp);
329         tables = new RBCollationTables JavaDoc(rules, decomp);
330     }
331
332     /**
333      * "Copy constructor." Used in clone() for performance.
334      */

335     private RuleBasedCollator(RuleBasedCollator JavaDoc that) {
336         setStrength(that.getStrength());
337         setDecomposition(that.getDecomposition());
338         tables = that.tables;
339     }
340
341     /**
342      * Gets the table-based rules for the collation object.
343      * @return returns the collation rules that the table collation object
344      * was created from.
345      */

346     public String JavaDoc getRules()
347     {
348         return tables.getRules();
349     }
350
351     /**
352      * Return a CollationElementIterator for the given String.
353      * @see java.text.CollationElementIterator
354      */

355     public CollationElementIterator JavaDoc getCollationElementIterator(String JavaDoc source) {
356         return new CollationElementIterator JavaDoc( source, this );
357     }
358
359     /**
360      * Return a CollationElementIterator for the given String.
361      * @see java.text.CollationElementIterator
362      * @since 1.2
363      */

364     public CollationElementIterator JavaDoc getCollationElementIterator(
365                                                 CharacterIterator JavaDoc source) {
366         return new CollationElementIterator JavaDoc( source, this );
367     }
368
369     /**
370      * Compares the character data stored in two different strings based on the
371      * collation rules. Returns information about whether a string is less
372      * than, greater than or equal to another string in a language.
373      * This can be overriden in a subclass.
374      */

375     public synchronized int compare(String JavaDoc source, String JavaDoc target)
376     {
377         // The basic algorithm here is that we use CollationElementIterators
378
// to step through both the source and target strings. We compare each
379
// collation element in the source string against the corresponding one
380
// in the target, checking for differences.
381
//
382
// If a difference is found, we set <result> to LESS or GREATER to
383
// indicate whether the source string is less or greater than the target.
384
//
385
// However, it's not that simple. If we find a tertiary difference
386
// (e.g. 'A' vs. 'a') near the beginning of a string, it can be
387
// overridden by a primary difference (e.g. "A" vs. "B") later in
388
// the string. For example, "AA" < "aB", even though 'A' > 'a'.
389
//
390
// To keep track of this, we use strengthResult to keep track of the
391
// strength of the most significant difference that has been found
392
// so far. When we find a difference whose strength is greater than
393
// strengthResult, it overrides the last difference (if any) that
394
// was found.
395

396         int result = Collator.EQUAL;
397
398         if (sourceCursor == null) {
399             sourceCursor = getCollationElementIterator(source);
400         } else {
401             sourceCursor.setText(source);
402         }
403         if (targetCursor == null) {
404             targetCursor = getCollationElementIterator(target);
405         } else {
406             targetCursor.setText(target);
407         }
408
409         int sOrder = 0, tOrder = 0;
410
411         boolean initialCheckSecTer = getStrength() >= Collator.SECONDARY;
412         boolean checkSecTer = initialCheckSecTer;
413         boolean checkTertiary = getStrength() >= Collator.TERTIARY;
414
415         boolean gets = true, gett = true;
416
417         while(true) {
418             // Get the next collation element in each of the strings, unless
419
// we've been requested to skip it.
420
if (gets) sOrder = sourceCursor.next(); else gets = true;
421             if (gett) tOrder = targetCursor.next(); else gett = true;
422
423             // If we've hit the end of one of the strings, jump out of the loop
424
if ((sOrder == CollationElementIterator.NULLORDER)||
425                 (tOrder == CollationElementIterator.NULLORDER))
426                 break;
427
428             int pSOrder = CollationElementIterator.primaryOrder(sOrder);
429             int pTOrder = CollationElementIterator.primaryOrder(tOrder);
430
431             // If there's no difference at this position, we can skip it
432
if (sOrder == tOrder) {
433                 if (tables.isFrenchSec() && pSOrder != 0) {
434                     if (!checkSecTer) {
435                         // in french, a secondary difference more to the right is stronger,
436
// so accents have to be checked with each base element
437
checkSecTer = initialCheckSecTer;
438                         // but tertiary differences are less important than the first
439
// secondary difference, so checking tertiary remains disabled
440
checkTertiary = false;
441                     }
442                 }
443                 continue;
444             }
445
446             // Compare primary differences first.
447
if ( pSOrder != pTOrder )
448             {
449                 if (sOrder == 0) {
450                     // The entire source element is ignorable.
451
// Skip to the next source element, but don't fetch another target element.
452
gett = false;
453                     continue;
454                 }
455                 if (tOrder == 0) {
456                     gets = false;
457                     continue;
458                 }
459
460                 // The source and target elements aren't ignorable, but it's still possible
461
// for the primary component of one of the elements to be ignorable....
462

463                 if (pSOrder == 0) // primary order in source is ignorable
464
{
465                     // The source's primary is ignorable, but the target's isn't. We treat ignorables
466
// as a secondary difference, so remember that we found one.
467
if (checkSecTer) {
468                         result = Collator.GREATER; // (strength is SECONDARY)
469
checkSecTer = false;
470                     }
471                     // Skip to the next source element, but don't fetch another target element.
472
gett = false;
473                 }
474                 else if (pTOrder == 0)
475                 {
476                     // record differences - see the comment above.
477
if (checkSecTer) {
478                         result = Collator.LESS; // (strength is SECONDARY)
479
checkSecTer = false;
480                     }
481                     // Skip to the next source element, but don't fetch another target element.
482
gets = false;
483                 } else {
484                     // Neither of the orders is ignorable, and we already know that the primary
485
// orders are different because of the (pSOrder != pTOrder) test above.
486
// Record the difference and stop the comparison.
487
if (pSOrder < pTOrder) {
488                         return Collator.LESS; // (strength is PRIMARY)
489
} else {
490                         return Collator.GREATER; // (strength is PRIMARY)
491
}
492                 }
493             } else { // else of if ( pSOrder != pTOrder )
494
// primary order is the same, but complete order is different. So there
495
// are no base elements at this point, only ignorables (Since the strings are
496
// normalized)
497

498                 if (checkSecTer) {
499                     // a secondary or tertiary difference may still matter
500
short secSOrder = CollationElementIterator.secondaryOrder(sOrder);
501                     short secTOrder = CollationElementIterator.secondaryOrder(tOrder);
502                     if (secSOrder != secTOrder) {
503                         // there is a secondary difference
504
result = (secSOrder < secTOrder) ? Collator.LESS : Collator.GREATER;
505                                                 // (strength is SECONDARY)
506
checkSecTer = false;
507                         // (even in french, only the first secondary difference within
508
// a base character matters)
509
} else {
510                         if (checkTertiary) {
511                             // a tertiary difference may still matter
512
short terSOrder = CollationElementIterator.tertiaryOrder(sOrder);
513                             short terTOrder = CollationElementIterator.tertiaryOrder(tOrder);
514                             if (terSOrder != terTOrder) {
515                                 // there is a tertiary difference
516
result = (terSOrder < terTOrder) ? Collator.LESS : Collator.GREATER;
517                                                 // (strength is TERTIARY)
518
checkTertiary = false;
519                             }
520                         }
521                     }
522                 } // if (checkSecTer)
523

524             } // if ( pSOrder != pTOrder )
525
} // while()
526

527         if (sOrder != CollationElementIterator.NULLORDER) {
528             // (tOrder must be CollationElementIterator::NULLORDER,
529
// since this point is only reached when sOrder or tOrder is NULLORDER.)
530
// The source string has more elements, but the target string hasn't.
531
do {
532                 if (CollationElementIterator.primaryOrder(sOrder) != 0) {
533                     // We found an additional non-ignorable base character in the source string.
534
// This is a primary difference, so the source is greater
535
return Collator.GREATER; // (strength is PRIMARY)
536
}
537                 else if (CollationElementIterator.secondaryOrder(sOrder) != 0) {
538                     // Additional secondary elements mean the source string is greater
539
if (checkSecTer) {
540                         result = Collator.GREATER; // (strength is SECONDARY)
541
checkSecTer = false;
542                     }
543                 }
544             } while ((sOrder = sourceCursor.next()) != CollationElementIterator.NULLORDER);
545         }
546         else if (tOrder != CollationElementIterator.NULLORDER) {
547             // The target string has more elements, but the source string hasn't.
548
do {
549                 if (CollationElementIterator.primaryOrder(tOrder) != 0)
550                     // We found an additional non-ignorable base character in the target string.
551
// This is a primary difference, so the source is less
552
return Collator.LESS; // (strength is PRIMARY)
553
else if (CollationElementIterator.secondaryOrder(tOrder) != 0) {
554                     // Additional secondary elements in the target mean the source string is less
555
if (checkSecTer) {
556                         result = Collator.LESS; // (strength is SECONDARY)
557
checkSecTer = false;
558                     }
559                 }
560             } while ((tOrder = targetCursor.next()) != CollationElementIterator.NULLORDER);
561         }
562
563         // For IDENTICAL comparisons, we use a bitwise character comparison
564
// as a tiebreaker if all else is equal
565
if (result == 0 && getStrength() == IDENTICAL) {
566             Normalizer.Mode JavaDoc mode = NormalizerUtilities.toNormalizerMode(getDecomposition());
567             String JavaDoc sourceDecomposition = Normalizer.normalize(source, mode, 0);
568             String JavaDoc targetDecomposition = Normalizer.normalize(target, mode, 0);
569             result = sourceDecomposition.compareTo(targetDecomposition);
570         }
571         return result;
572     }
573
574     /**
575      * Transforms the string into a series of characters that can be compared
576      * with CollationKey.compareTo. This overrides java.text.Collator.getCollationKey.
577      * It can be overriden in a subclass.
578      */

579     public synchronized CollationKey JavaDoc getCollationKey(String JavaDoc source)
580     {
581         //
582
// The basic algorithm here is to find all of the collation elements for each
583
// character in the source string, convert them to a char representation,
584
// and put them into the collation key. But it's trickier than that.
585
// Each collation element in a string has three components: primary (A vs B),
586
// secondary (A vs A-acute), and tertiary (A' vs a); and a primary difference
587
// at the end of a string takes precedence over a secondary or tertiary
588
// difference earlier in the string.
589
//
590
// To account for this, we put all of the primary orders at the beginning of the
591
// string, followed by the secondary and tertiary orders, separated by nulls.
592
//
593
// Here's a hypothetical example, with the collation element represented as
594
// a three-digit number, one digit for primary, one for secondary, etc.
595
//
596
// String: A a B \u00e9 <--(e-acute)
597
// Collation Elements: 101 100 201 510
598
//
599
// Collation Key: 1125<null>0001<null>1010
600
//
601
// To make things even trickier, secondary differences (accent marks) are compared
602
// starting at the *end* of the string in languages with French secondary ordering.
603
// But when comparing the accent marks on a single base character, they are compared
604
// from the beginning. To handle this, we reverse all of the accents that belong
605
// to each base character, then we reverse the entire string of secondary orderings
606
// at the end. Taking the same example above, a French collator might return
607
// this instead:
608
//
609
// Collation Key: 1125<null>1000<null>1010
610
//
611
if (source == null)
612             return null;
613
614         if (primResult == null) {
615             primResult = new StringBuffer JavaDoc();
616             secResult = new StringBuffer JavaDoc();
617             terResult = new StringBuffer JavaDoc();
618         } else {
619             primResult.setLength(0);
620             secResult.setLength(0);
621             terResult.setLength(0);
622         }
623         int order = 0;
624         boolean compareSec = (getStrength() >= Collator.SECONDARY);
625         boolean compareTer = (getStrength() >= Collator.TERTIARY);
626         int secOrder = CollationElementIterator.NULLORDER;
627         int terOrder = CollationElementIterator.NULLORDER;
628         int preSecIgnore = 0;
629
630         if (sourceCursor == null) {
631             sourceCursor = getCollationElementIterator(source);
632         } else {
633             sourceCursor.setText(source);
634         }
635
636         // walk through each character
637
while ((order = sourceCursor.next()) !=
638                CollationElementIterator.NULLORDER)
639         {
640             secOrder = CollationElementIterator.secondaryOrder(order);
641             terOrder = CollationElementIterator.tertiaryOrder(order);
642             if (!CollationElementIterator.isIgnorable(order))
643             {
644                 primResult.append((char) (CollationElementIterator.primaryOrder(order)
645                                     + COLLATIONKEYOFFSET));
646
647                 if (compareSec) {
648                     //
649
// accumulate all of the ignorable/secondary characters attached
650
// to a given base character
651
//
652
if (tables.isFrenchSec() && preSecIgnore < secResult.length()) {
653                         //
654
// We're doing reversed secondary ordering and we've hit a base
655
// (non-ignorable) character. Reverse any secondary orderings
656
// that applied to the last base character. (see block comment above.)
657
//
658
RBCollationTables.reverse(secResult, preSecIgnore, secResult.length());
659                     }
660                     // Remember where we are in the secondary orderings - this is how far
661
// back to go if we need to reverse them later.
662
secResult.append((char)(secOrder+ COLLATIONKEYOFFSET));
663                     preSecIgnore = secResult.length();
664                 }
665                 if (compareTer) {
666                     terResult.append((char)(terOrder+ COLLATIONKEYOFFSET));
667                 }
668             }
669             else
670             {
671                 if (compareSec && secOrder != 0)
672                     secResult.append((char)
673                         (secOrder + tables.getMaxSecOrder() + COLLATIONKEYOFFSET));
674                 if (compareTer && terOrder != 0)
675                     terResult.append((char)
676                         (terOrder + tables.getMaxTerOrder() + COLLATIONKEYOFFSET));
677             }
678         }
679         if (tables.isFrenchSec())
680         {
681             if (preSecIgnore < secResult.length()) {
682                 // If we've accumlated any secondary characters after the last base character,
683
// reverse them.
684
RBCollationTables.reverse(secResult, preSecIgnore, secResult.length());
685             }
686             // And now reverse the entire secResult to get French secondary ordering.
687
RBCollationTables.reverse(secResult, 0, secResult.length());
688         }
689         primResult.append((char)0);
690         secResult.append((char)0);
691         secResult.append(terResult.toString());
692         primResult.append(secResult.toString());
693
694         if (getStrength() == IDENTICAL) {
695             primResult.append((char)0);
696             Normalizer.Mode JavaDoc mode = NormalizerUtilities.toNormalizerMode(getDecomposition());
697             primResult.append(Normalizer.normalize(source, mode, 0));
698         }
699         return new CollationKey JavaDoc(source, primResult.toString());
700     }
701
702     /**
703      * Standard override; no change in semantics.
704      */

705     public Object JavaDoc clone() {
706         // if we know we're not actually a subclass of RuleBasedCollator
707
// (this class really should have been made final), bypass
708
// Object.clone() and use our "copy constructor". This is faster.
709
if (getClass() == RuleBasedCollator JavaDoc.class) {
710             return new RuleBasedCollator JavaDoc(this);
711         }
712         else {
713             RuleBasedCollator JavaDoc result = (RuleBasedCollator JavaDoc) super.clone();
714             result.primResult = null;
715             result.secResult = null;
716             result.terResult = null;
717             result.sourceCursor = null;
718             result.targetCursor = null;
719             return result;
720         }
721     }
722
723     /**
724      * Compares the equality of two collation objects.
725      * @param obj the table-based collation object to be compared with this.
726      * @return true if the current table-based collation object is the same
727      * as the table-based collation object obj; false otherwise.
728      */

729     public boolean equals(Object JavaDoc obj) {
730         if (obj == null) return false;
731         if (!super.equals(obj)) return false; // super does class check
732
RuleBasedCollator JavaDoc other = (RuleBasedCollator JavaDoc) obj;
733         // all other non-transient information is also contained in rules.
734
return (getRules().equals(other.getRules()));
735     }
736
737     /**
738      * Generates the hash code for the table-based collation object
739      */

740     public int hashCode() {
741         return getRules().hashCode();
742     }
743
744     /**
745      * Allows CollationElementIterator access to the tables object
746      */

747     RBCollationTables JavaDoc getTables() {
748         return tables;
749     }
750
751     // ==============================================================
752
// private
753
// ==============================================================
754

755     final static int CHARINDEX = 0x70000000; // need look up in .commit()
756
final static int EXPANDCHARINDEX = 0x7E000000; // Expand index follows
757
final static int CONTRACTCHARINDEX = 0x7F000000; // contract indexes follow
758
final static int UNMAPPED = 0xFFFFFFFF;
759
760     private final static int COLLATIONKEYOFFSET = 1;
761
762     private RBCollationTables JavaDoc tables = null;
763
764     // Internal objects that are cached across calls so that they don't have to
765
// be created/destroyed on every call to compare() and getCollationKey()
766
private StringBuffer JavaDoc primResult = null;
767     private StringBuffer JavaDoc secResult = null;
768     private StringBuffer JavaDoc terResult = null;
769     private CollationElementIterator JavaDoc sourceCursor = null;
770     private CollationElementIterator JavaDoc targetCursor = null;
771 }
772
773
Popular Tags