home *** CD-ROM | disk | FTP | other *** search
/ Java 1.2 How-To / JavaHowTo.iso / 3rdParty / jbuilder / unsupported / JDK1.2beta3 / SOURCE / SRC.ZIP / java / text / RuleBasedCollator.java < prev    next >
Encoding:
Java Source  |  1998-03-20  |  51.4 KB  |  1,237 lines

  1. /*
  2.  * @(#)RuleBasedCollator.java    1.18 98/03/18
  3.  *
  4.  * (C) Copyright Taligent, Inc. 1996, 1997 - All Rights Reserved
  5.  * (C) Copyright IBM Corp. 1996, 1997 - All Rights Reserved
  6.  *
  7.  * Portions copyright (c) 1997, 1998 Sun Microsystems, Inc. All Rights Reserved.
  8.  *
  9.  *   The original version of this source code and documentation is copyrighted
  10.  * and owned by Taligent, Inc., a wholly-owned subsidiary of IBM. These
  11.  * materials are provided under terms of a License Agreement between Taligent
  12.  * and Sun. This technology is protected by multiple US and International
  13.  * patents. This notice and attribution to Taligent may not be removed.
  14.  *   Taligent is a registered trademark of Taligent, Inc.
  15.  *
  16.  * Permission to use, copy, modify, and distribute this software
  17.  * and its documentation for NON-COMMERCIAL purposes and without
  18.  * fee is hereby granted provided that this copyright notice
  19.  * appears in all copies. Please refer to the file "copyright.html"
  20.  * for further important copyright and licensing information.
  21.  *
  22.  * SUN MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF
  23.  * THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
  24.  * TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
  25.  * PARTICULAR PURPOSE, OR NON-INFRINGEMENT. SUN SHALL NOT BE LIABLE FOR
  26.  * ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR
  27.  * DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
  28.  *
  29.  */
  30.  
  31. package java.text;
  32.  
  33. import java.util.Vector;
  34. import java.io.ObjectOutputStream;
  35. import java.io.ObjectInputStream;
  36. import java.io.IOException;
  37.  
  38. /**
  39.  * The <code>RuleBasedCollator</code> class is a concrete subclass of
  40.  * <code>Collator</code> that provides a simple, data-driven, table
  41.  * collator.  With this class you can create a customized table-based
  42.  * <code>Collator</code>.  <code>RuleBasedCollator</code> maps
  43.  * characters to sort keys.
  44.  *
  45.  * <p>
  46.  * <code>RuleBasedCollator</code> has the following restrictions
  47.  * for efficiency (other subclasses may be used for more complex languages) :
  48.  * <ol>
  49.  * <li>If a French secondary ordering is specified it applies to the
  50.  *     whole collator object.
  51.  * <li>All non-mentioned Unicode characters are at the end of the
  52.  *     collation order.
  53.  * </ol>
  54.  *
  55.  * <p>
  56.  * The collation table is composed of a list of collation rules, where each
  57.  * rule is of three forms:
  58.  * <pre>
  59.  *    < modifier >
  60.  *    < relation > < text-argument >
  61.  *    < reset > < text-argument >
  62.  * </pre>
  63.  * The following demonstrates how to create your own collation rules:
  64.  * <UL Type=disc>
  65.  *    <LI><strong>Text-Argument</strong>: A text-argument is any sequence of
  66.  *        characters, excluding special characters (that is, common
  67.  *        whitespace characters [0009-000D, 0020] and rule syntax characters
  68.  *        [0021-002F, 003A-0040, 005B-0060, 007B-007E]). If those
  69.  *        characters are desired, you can put them in single quotes
  70.  *        (e.g. ampersand => '&'). Note that unquoted white space characters
  71.  *        are ignored; e.g. <code>b c</code> is treated as <code>bc</code>.
  72.  *    <LI><strong>Modifier</strong>: There is a single modifier
  73.  *        which is used to specify that all accents (secondary differences) are
  74.  *        backwards.
  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>'<' : 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 < b < c
  96.  * a < b & b < c
  97.  * a < c & a < 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 < b & a < c
  105.  * a < c & a < 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 < b & ae <
  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 < ch < d"), while in traditional German
  116.  * "a" (a-umlaut) is treated as though it expanded to two characters
  117.  * (expressed as "a,A < b,B ... & ae,a & AE,A").
  118.  * <p>
  119.  * <strong>Ignorable Characters</strong>
  120.  * <p>
  121.  * For ignorable characters, the first rule must start with a relation (the
  122.  * examples we have used above are really fragments; "a < b" really should be
  123.  * "< a < b"). If, however, the first relation is not "<", then all the all
  124.  * text-arguments up to the first "<" are ignorable. For example, ", - < a < b"
  125.  * makes "-" an ignorable character, as we saw earlier in the word
  126.  * "black-birds". In the samples for different languages, you see that most
  127.  * accents are ignorable.
  128.  *
  129.  * <p><strong>Normalization and Accents</strong>
  130.  * <p>
  131.  * The <code>Collator</code> object automatically normalizes text internally
  132.  * to separate accents from base characters where possible. This is done both when
  133.  * processing the rules, and when comparing two strings. <code>Collator</code>
  134.  * also uses the Unicode canonical mapping to ensure that combining sequences
  135.  * are sorted properly (for more information, see
  136.  * <A HREF="http://www.aw.com/devpress">The Unicode Standard, Version 2.0</A>.)</P>
  137.  *
  138.  * <p><strong>Errors</strong>
  139.  * <p>
  140.  * The following are errors:
  141.  * <UL Type=disc>
  142.  *     <LI>A text-argument contains unquoted punctuation symbols
  143.  *        (e.g. "a < b-c < d").
  144.  *     <LI>A relation or reset character not followed by a text-argument
  145.  *        (e.g. "a < , b").
  146.  *     <LI>A reset where the text-argument (or an initial substring of the
  147.  *         text-argument) is not already in the sequence.
  148.  *         (e.g. "a < b & e < f")
  149.  * </UL>
  150.  * If you produce one of these errors, a <code>RuleBasedCollator</code> throws
  151.  * a <code>ParseException</code>.
  152.  *
  153.  * <p><strong>Examples</strong>
  154.  * <p>Simple:     "< a < b < c < d"
  155.  * <p>Norwegian:  "< a,A< b,B< c,C< d,D< e,E< f,F< g,G< h,H< i,I< j,J
  156.  *                 < k,K< l,L< m,M< n,N< o,O< p,P< q,Q< r,R< s,S< t,T
  157.  *                 < u,U< v,V< w,W< x,X< y,Y< z,Z
  158.  *                 < \u00E5=a\u030A,\u00C5=A\u030A
  159.  *                 ;aa,AA< \u00E6,\u00C6< \u00F8,\u00D8"
  160.  *
  161.  * <p>
  162.  * Normally, to create a rule-based Collator object, you will use
  163.  * <code>Collator</code>'s factory method <code>getInstance</code>.
  164.  * However, to create a rule-based Collator object with specialized
  165.  * rules tailored to your needs, you construct the <code>RuleBasedCollator</code>
  166.  * with the rules contained in a <code>String</code> object. For example:
  167.  * <blockquote>
  168.  * <pre>
  169.  * String Simple = "< a < b < c < d";
  170.  * RuleBasedCollator mySimple = new RuleBasedCollator(Simple);
  171.  * </pre>
  172.  * </blockquote>
  173.  * Or:
  174.  * <blockquote>
  175.  * <pre>
  176.  * String Norwegian = "< a,A< b,B< c,C< d,D< e,E< f,F< g,G< h,H< i,I< j,J" +
  177.  *                 "< k,K< l,L< m,M< n,N< o,O< p,P< q,Q< r,R< s,S< t,T" +
  178.  *                 "< u,U< v,V< w,W< x,X< y,Y< z,Z" +
  179.  *                 "< \u00E5=a\u030A,\u00C5=A\u030A" +
  180.  *                 ";aa,AA< \u00E6,\u00C6< \u00F8,\u00D8";
  181.  * RuleBasedCollator myNorwegian = new RuleBasedCollator(Norwegian);
  182.  * </pre>
  183.  * </blockquote>
  184.  *
  185.  * <p>
  186.  * Combining <code>Collator</code>s is as simple as concatenating strings.
  187.  * Here's an example that combines two <code>Collator</code>s from two
  188.  * different locales:
  189.  * <blockquote>
  190.  * <pre>
  191.  * // Create an en_US Collator object
  192.  * RuleBasedCollator en_USCollator = (RuleBasedCollator)
  193.  *     Collator.getInstance(new Locale("en", "US", ""));
  194.  * // Create a da_DK Collator object
  195.  * RuleBasedCollator da_DKCollator = (RuleBasedCollator)
  196.  *     Collator.getInstance(new Locale("da", "DK", ""));
  197.  * // Combine the two
  198.  * // First, get the collation rules from en_USCollator
  199.  * String en_USRules = en_USCollator.getRules();
  200.  * // Second, get the collation rules from da_DKCollator
  201.  * String da_DKRules = da_DKCollator.getRules();
  202.  * RuleBasedCollator newCollator =
  203.  *     new RuleBasedCollator(en_USRules + da_DKRules);
  204.  * // newCollator has the combined rules
  205.  * </pre>
  206.  * </blockquote>
  207.  *
  208.  * <p>
  209.  * Another more interesting example would be to make changes on an existing
  210.  * table to create a new <code>Collator</code> object.  For example, add
  211.  * "& C < ch, cH, Ch, CH" to the <code>en_USCollator</code> object to create
  212.  * your own:
  213.  * <blockquote>
  214.  * <pre>
  215.  * // Create a new Collator object with additional rules
  216.  * String addRules = "& C < ch, cH, Ch, CH";
  217.  * RuleBasedCollator myCollator =
  218.  *     new RuleBasedCollator(en_USCollator + addRules);
  219.  * // myCollator contains the new rules
  220.  * </pre>
  221.  * </blockquote>
  222.  *
  223.  * <p>
  224.  * The following example demonstrates how to change the order of
  225.  * non-spacing accents,
  226.  * <blockquote>
  227.  * <pre>
  228.  * // old rule
  229.  * String oldRules = "=\u0301;\u0300;\u0302;\u0308"    // main accents
  230.  *                 + ";\u0327;\u0303;\u0304;\u0305"    // main accents
  231.  *                 + ";\u0306;\u0307;\u0309;\u030A"    // main accents
  232.  *                 + ";\u030B;\u030C;\u030D;\u030E"    // main accents
  233.  *                 + ";\u030F;\u0310;\u0311;\u0312"    // main accents
  234.  *                 + "< a , A ; ae, AE ; \u00e6 , \u00c6"
  235.  *                 + "< b , B < c, C < e, E & C < d, D";
  236.  * // change the order of accent characters
  237.  * String addOn = "& \u0300 ; \u0308 ; \u0302";
  238.  * RuleBasedCollator myCollator = new RuleBasedCollator(oldRules + addOn);
  239.  * </pre>
  240.  * </blockquote>
  241.  *
  242.  * <p>
  243.  * The last example shows how to put new primary ordering in before the
  244.  * default setting. For example, in Japanese <code>Collator</code>, you
  245.  * can either sort English characters before or after Japanese characters,
  246.  * <blockquote>
  247.  * <pre>
  248.  * // get en_US Collator rules
  249.  * RuleBasedCollator en_USCollator = (RuleBasedCollator)Collator.getInstance(Locale.US);
  250.  * // add a few Japanese character to sort before English characters
  251.  * // suppose the last character before the first base letter 'a' in
  252.  * // the English collation rule is \u2212
  253.  * String jaString = "& \u2212 < \u3041, \u3042 < \u3043, \u3044";
  254.  * RuleBasedCollator myJapaneseCollator = new
  255.  *     RuleBasedCollator(en_USCollator.getRules() + jaString);
  256.  * </pre>
  257.  * </blockquote>
  258.  *
  259.  * @see        Collator
  260.  * @see        CollationElementIterator
  261.  * @version    1.18 03/18/98
  262.  * @author     Helena Shih
  263.  */
  264. public class RuleBasedCollator extends Collator{
  265.     //===========================================================================================
  266.     //  The following diagram shows the data structure of the RuleBasedCollator object.
  267.     //  Suppose we have the rule, where 'o-umlaut' is the unicode char 0x00F6.
  268.     //  "a, A < b, B < c, C, ch, cH, Ch, CH < d, D ... < o, O; 'o-umlaut'/E, 'O-umlaut'/E ...".
  269.     //  What the rule says is, sorts 'ch'ligatures and 'c' only with tertiary difference and
  270.     //  sorts 'o-umlaut' as if it's always expanded with 'e'.
  271.     //
  272.     // mapping table                     contracting list           expanding list
  273.     // (contains all unicode char
  274.     //  entries)                   ___    ____________       _________________________
  275.     //  ________                +>|_*_|->|'c' |v('c') |  +>|v('o')|v('umlaut')|v('e')|
  276.     // |_\u0001_|-> v('\u0001') | |_:_|  |------------|  | |-------------------------|
  277.     // |_\u0002_|-> v('\u0002') | |_:_|  |'ch'|v('ch')|  | |             :           |
  278.     // |____:___|               | |_:_|  |------------|  | |-------------------------|
  279.     // |____:___|               |        |'cH'|v('cH')|  | |             :           |
  280.     // |__'a'___|-> v('a')      |        |------------|  | |-------------------------|
  281.     // |__'b'___|-> v('b')      |        |'Ch'|v('Ch')|  | |             :           |
  282.     // |____:___|               |        |------------|  | |-------------------------|
  283.     // |____:___|               |        |'CH'|v('CH')|  | |             :           |
  284.     // |___'c'__|----------------         ------------   | |-------------------------|
  285.     // |____:___|                                        | |             :           |
  286.     // |o-umlaut|----------------------------------------  |_________________________|
  287.     // |____:___|
  288.     //
  289.     // Noted by Helena Shih on 6/23/97
  290.     //============================================================================================
  291.  
  292.     /**
  293.      * RuleBasedCollator constructor.  This takes the table rules and builds
  294.      * a collation table out of them.  Please see RuleBasedCollator class
  295.      * description for more details on the collation rule syntax.
  296.      * @see java.util.Locale
  297.      * @param rules the collation rules to build the collation table from.
  298.      * @exception ParseException A format exception
  299.      * will be thrown if the build process of the rules fails. For
  300.      * example, build rule "a < ? < d" will cause the constructor to
  301.      * throw the ParseException because the '?' is not quoted.
  302.      */
  303.     public RuleBasedCollator(String rules) throws ParseException {
  304.         setStrength(Collator.TERTIARY);
  305.         build(rules);
  306.     }
  307.  
  308.     /**
  309.      * Gets the table-based rules for the collation object.
  310.      * @return returns the collation rules that the table collation object
  311.      * was created from.
  312.      */
  313.     public String getRules()
  314.     {
  315.         if (ruleTable == null) {
  316.             ruleTable = mPattern.emitPattern();
  317.             mPattern = null;
  318.         }
  319.         return ruleTable;
  320.     }
  321.  
  322.  
  323.     /**
  324.      * Return a CollationElementIterator for the given String.
  325.      * @see java.text.CollationElementIterator
  326.      */
  327.     public CollationElementIterator getCollationElementIterator(String source) {
  328.         return new CollationElementIterator( source, this );
  329.     }
  330.  
  331.     /**
  332.      * Return a CollationElementIterator for the given String.
  333.      * @see java.text.CollationElementIterator
  334.      */
  335.     CollationElementIterator getCollationElementIterator(
  336.                                                 CharacterIterator source) {
  337.         return new CollationElementIterator( source, this );
  338.     }
  339.  
  340.     /**
  341.      * Compares the character data stored in two different strings based on the
  342.      * collation rules.  Returns information about whether a string is less
  343.      * than, greater than or equal to another string in a language.
  344.      * This can be overriden in a subclass.
  345.      */
  346.     public int compare(String source, String target)
  347.     {
  348.         // The basic algorithm here is that we use CollationElementIterators
  349.         // to step through both the source and target strings.  We compare each
  350.         // collation element in the source string against the corresponding one
  351.         // in the target, checking for differences.
  352.         //
  353.         // If a difference is found, we set <result> to LESS or GREATER to
  354.         // indicate whether the source string is less or greater than the target.
  355.         //
  356.         // However, it's not that simple.  If we find a tertiary difference
  357.         // (e.g. 'A' vs. 'a') near the beginning of a string, it can be
  358.         // overridden by a primary difference (e.g. "A" vs. "B") later in
  359.         // the string.  For example, "AA" < "aB", even though 'A' > 'a'.
  360.         //
  361.         // To keep track of this, we use strengthResult to keep track of the
  362.         // strength of the most significant difference that has been found
  363.         // so far.  When we find a difference whose strength is greater than
  364.         // strengthResult, it overrides the last difference (if any) that
  365.         // was found.
  366.  
  367.         int result = Collator.EQUAL;
  368.         strengthResult = Collator.IDENTICAL;
  369.         CollationElementIterator targetCursor
  370.             = new CollationElementIterator(target, this);
  371.         CollationElementIterator sourceCursor
  372.             = new CollationElementIterator(source, this);
  373.         int sOrder = 0, tOrder = 0;
  374.         int savedSOrder = 0, savedTOrder = 0;
  375.         boolean skipSecCheck = false;
  376.         boolean gets = true, gett = true;
  377.         while(true) {
  378.             // Get the next collation element in each of the strings, unless
  379.             // we've been requested to skip it.
  380.             int pSOrder = 0, pTOrder = 0;
  381.             if (gets) sOrder = sourceCursor.next(); else gets = true;
  382.             if (gett) tOrder = targetCursor.next(); else gett = true;
  383.  
  384.             // If we've hit the end of one of the strings, jump out of the loop
  385.             if ((sOrder == CollationElementIterator.NULLORDER)||
  386.                 (tOrder == CollationElementIterator.NULLORDER))
  387.                 break;
  388.  
  389.             // When we hit the end of one of the strings, we're going to need to remember
  390.             // the last element in each string, in order to decide if there
  391.             savedSOrder = sOrder;
  392.             savedTOrder = tOrder;
  393.  
  394.             // If there's no difference at this position, we can skip it
  395.             if (sOrder == tOrder)
  396.                 continue;
  397.  
  398.             // Compare primary differences first.
  399.             pSOrder = CollationElementIterator.primaryOrder(sOrder);
  400.             pTOrder = CollationElementIterator.primaryOrder(tOrder);
  401.             if ( pSOrder != pTOrder )
  402.             {
  403.                 if (sOrder == 0) {
  404.                     // The entire source element is ignorable.  Skip to the
  405.                     //next source element, but don't fetch another target element.
  406.                     gett = false;
  407.                     continue;
  408.                 }
  409.                 if (tOrder == 0) {
  410.                     gets = false;
  411.                     continue;
  412.                 }
  413.  
  414.                 // Neither the source or target order is totally ignorable,
  415.                 // but it's still possible for the primary component of one of the
  416.                 // elements to be ignorable, e.g. for a combining accent mark
  417.  
  418.                 if (pSOrder == 0)    // primary order in source is ignorable
  419.                 {
  420.                     if (pTOrder == 0)  // primary order in target is ignorable
  421.                     {
  422.                         // check the secondary/tertiary weight when both are ignorable chars.
  423.                         result = checkSecTerDiff(sOrder, tOrder, result, false);
  424.  
  425.                         // We already checked the secondary weights, so don't do it again
  426.                         skipSecCheck = true;
  427.                         continue;                   // both advances
  428.                     }
  429.                     else
  430.                     {
  431.                         //
  432.                         // The source's primary is ignorable, but the target's isn't.  We treat
  433.                         // ignorables as a secondary difference, so remember that we found one.
  434.                         // BUT, for French secondary ordering we might have already found a secondary
  435.                         // difference in the ignorables attached to this base char.  If we have, we
  436.                         // don't need to mark a difference here.
  437.                         //
  438.                         if ((!isFrenchSec &&
  439.                              (result == Collator.EQUAL || strengthResult > Collator.SECONDARY)) ||
  440.                             (isFrenchSec && !skipSecCheck))
  441.                         {
  442.                             strengthResult = Collator.SECONDARY;
  443.                             result = Collator.GREATER;
  444.                         }
  445.                         // Skip to the next source element, but don't fetch another target element.
  446.                         gett = false;
  447.                         skipSecCheck = false;
  448.                         continue;
  449.                     }
  450.                 }
  451.                 else if (pTOrder == 0)
  452.                 {
  453.                     // record differences - see the comment above.
  454.                     if ((!isFrenchSec &&
  455.                          (result == Collator.EQUAL || strengthResult > Collator.SECONDARY)) ||
  456.                         (isFrenchSec && !skipSecCheck))
  457.                      {
  458.                         result = Collator.LESS;
  459.                         strengthResult = Collator.SECONDARY;
  460.                     }
  461.                     gets = false;
  462.                     skipSecCheck = false;
  463.                     continue;
  464.                 }
  465.                 //
  466.                 // Neither of the orders is ignorable, and we already know that the primary
  467.                 // orders are different because of the (pSOrder != pTOrder) test above.
  468.                 // Record the difference and stop the comparison.
  469.                 //
  470.                 if (pSOrder < pTOrder)
  471.                     result = Collator.LESS;
  472.                 else
  473.                     result = Collator.GREATER;
  474.                 break;
  475.             }
  476.             else {
  477.                 //
  478.                 // The primary orders are the same, but we need to continue to check
  479.                 // for secondary or tertiary differences.
  480.                 //
  481.                 result = checkSecTerDiff(sOrder, tOrder, result, skipSecCheck);
  482.                 if (isFrenchSec &&
  483.                     CollationElementIterator.isIgnorable(sOrder) &&
  484.                     CollationElementIterator.isIgnorable(tOrder))
  485.                     skipSecCheck = true;
  486.                 else
  487.                     skipSecCheck = false;
  488.             }
  489.         } // while()
  490.  
  491.         if (sOrder != CollationElementIterator.NULLORDER) {
  492.             if (tOrder == CollationElementIterator.NULLORDER) {
  493.                 // The source string hasn't not reached the end and target string has...
  494.                 do {
  495.                     if (CollationElementIterator.primaryOrder(sOrder) != 0) {
  496.                         // We found a non-ignorable base character in the source string.
  497.                         // This is a primary difference, so the source is greater
  498.                         return 1;
  499.                     } else if (CollationElementIterator.secondaryOrder(sOrder) != 0) {
  500.                         //
  501.                         // If the last character in the target string was a base character,
  502.                         // or if we haven't found any secondary differences yet,
  503.                         // we still need to look at accent marks in the source string, because
  504.                         // they can affect the result in languages with reversed (French)
  505.                         // secondary ordering.
  506.                         //
  507.                         if (!CollationElementIterator.isIgnorable(savedTOrder) ||
  508.                             strengthResult > Collator.SECONDARY)
  509.                             result = checkSecTerDiff(sOrder, 0, result, false);
  510.                         else
  511.                             continue;
  512.                     }
  513.                 } while ((sOrder = sourceCursor.next()) != CollationElementIterator.NULLORDER);
  514.             }
  515.         }
  516.         else if (tOrder != CollationElementIterator.NULLORDER) {
  517.             // See comments above.
  518.             do {
  519.                 if (CollationElementIterator.primaryOrder(tOrder) != 0) {
  520.                     return -1;
  521.                 } else if (CollationElementIterator.secondaryOrder(tOrder) != 0) {
  522.                     if (!CollationElementIterator.isIgnorable(savedSOrder) ||
  523.                         strengthResult > Collator.SECONDARY)
  524.                         result = checkSecTerDiff(0, tOrder, result, false);
  525.                     else
  526.                         continue;
  527.                 }
  528.             } while ((tOrder = targetCursor.next()) != CollationElementIterator.NULLORDER);
  529.         }
  530.  
  531.         // For IDENTICAL comparisons, we use a bitwise character comparison
  532.         // as a tiebreaker if all else is equal
  533.         if (result == 0 && getStrength() == IDENTICAL) {
  534.             result = Normalizer.decompose(source,getDecomposition())
  535.                 .compareTo(Normalizer.decompose(target,getDecomposition()));
  536.         }
  537.         return result;
  538.     }
  539.     /**
  540.      * Transforms the string into a series of characters that can be compared
  541.      * with CollationKey.compareTo. This overrides java.text.Collator.getCollationKey.
  542.      * It can be overriden in a subclass.
  543.      */
  544.     public CollationKey getCollationKey(String source)
  545.     {
  546.         //
  547.         // The basic algorithm here is to find all of the collation elements for each
  548.         // character in the source string, convert them to a char representation,
  549.         // and put them into the collation key.  But it's trickier than that.
  550.         // Each collation element in a string has three components: primary (A vs B),
  551.         // secondary (A vs A-acute), and tertiary (A' vs a); and a primary difference
  552.         // at the end of a string takes precedence over a secondary or tertiary
  553.         // difference earlier in the string.
  554.         //
  555.         // To account for this, we put all of the primary orders at the beginning of the
  556.         // string, followed by the secondary and tertiary orders, separated by nulls.
  557.         //
  558.         // Here's a hypothetical example, with the collation element represented as
  559.         // a three-digit number, one digit for primary, one for secondary, etc.
  560.         //
  561.         // String:              A     a     B    Î˜ <--(e-acute)
  562.         // Collation Elements: 101   100   201  510
  563.         //
  564.         // Collation Key:      1125<null>0001<null>1010
  565.         //
  566.         // To make things even trickier, secondary differences (accent marks) are compared
  567.         // starting at the *end* of the string in languages with French secondary ordering.
  568.         // But when comparing the accent marks on a single base character, they are compared
  569.         // from the beginning.  To handle this, we reverse all of the accents that belong
  570.         // to each base character, then we reverse the entire string of secondary orderings
  571.         // at the end.  Taking the same example above, a French collator might return
  572.         // this instead:
  573.         //
  574.         // Collation Key:      1125<null>1000<null>1010
  575.         //
  576.         if (source == null)
  577.             return null;
  578.         primResult.setLength(0);
  579.         secResult.setLength(0);
  580.         terResult.setLength(0);
  581.         int order = 0;
  582.         boolean compareSec = (getStrength() >= Collator.SECONDARY);
  583.         boolean compareTer = (getStrength() >= Collator.TERTIARY);
  584.         int secOrder = CollationElementIterator.NULLORDER;
  585.         int terOrder = CollationElementIterator.NULLORDER;
  586.         int preSecIgnore = 0;
  587.  
  588.         CollationElementIterator sourceCursor = new
  589.             CollationElementIterator(source, this);
  590.  
  591.         // walk through each character
  592.         while ((order = sourceCursor.next()) !=
  593.                CollationElementIterator.NULLORDER)
  594.         {
  595.             secOrder = CollationElementIterator.secondaryOrder(order);
  596.             terOrder = CollationElementIterator.tertiaryOrder(order);
  597.             if (!CollationElementIterator.isIgnorable(order))
  598.             {
  599.                 primResult.append((char) (CollationElementIterator.primaryOrder(order)
  600.                                     + COLLATIONKEYOFFSET));
  601.  
  602.                 if (compareSec) {
  603.                     //
  604.                     // accumulate all of the ignorable/secondary characters attached
  605.                     // to a given base character
  606.                     //
  607.                     if (isFrenchSec && preSecIgnore < secResult.length()) {
  608.                         //
  609.                         // We're doing reversed secondary ordering and we've hit a base
  610.                         // (non-ignorable) character.  Reverse any secondary orderings
  611.                         // that applied to the last base character.  (see block comment above.)
  612.                         //
  613.                         reverse(secResult, preSecIgnore, secResult.length());
  614.                     }
  615.                     // Remember where we are in the secondary orderings - this is how far
  616.                     // back to go if we need to reverse them later.
  617.                     secResult.append((char)(secOrder+ COLLATIONKEYOFFSET));
  618.                     preSecIgnore = secResult.length();
  619.                 }
  620.                 if (compareTer) {
  621.                     terResult.append((char)(terOrder+ COLLATIONKEYOFFSET));
  622.                 }
  623.             }
  624.             else
  625.             {
  626.                 if (compareSec && secOrder != 0)
  627.                     secResult.append((char)
  628.                         (secOrder+maxSecOrder+ COLLATIONKEYOFFSET));
  629.                 if (compareTer && terOrder != 0)
  630.                     terResult.append((char)
  631.                         (terOrder+maxTerOrder+ COLLATIONKEYOFFSET));
  632.             }
  633.         }
  634.         if (isFrenchSec)
  635.         {
  636.             if (preSecIgnore < secResult.length()) {
  637.                 // If we've accumlated any secondary characters after the last base character,
  638.                 // reverse them.
  639.                 reverse(secResult, preSecIgnore, secResult.length());
  640.             }
  641.             // And now reverse the entire secResult to get French secondary ordering.
  642.             reverse(secResult, 0, secResult.length());
  643.         }
  644.         primResult.append((char)0);
  645.         secResult.append((char)0);
  646.         secResult.append(terResult.toString());
  647.         primResult.append(secResult.toString());
  648.  
  649.         if (getStrength() == IDENTICAL) {
  650.             primResult.append((char)0);
  651.             primResult.append(Normalizer.decompose(source,getDecomposition()));
  652.         }
  653.         return new CollationKey(source, primResult.toString());
  654.     }
  655.     /**
  656.      * Standard override; no change in semantics.
  657.      */
  658.     public Object clone() {
  659.         RuleBasedCollator other = (RuleBasedCollator) super.clone();
  660.         other.primResult = new StringBuffer(MAXTOKENLEN);
  661.         other.secResult = new StringBuffer(MAXTOKENLEN);
  662.         other.terResult = new StringBuffer(MAXTOKENLEN);
  663.         other.key = new StringBuffer(MAXKEYSIZE);
  664.         return other;
  665.     }
  666.  
  667.     /**
  668.      * Compares the equality of two collation objects.
  669.      * @param obj the table-based collation object to be compared with this.
  670.      * @return true if the current table-based collation object is the same
  671.      * as the table-based collation object obj; false otherwise.
  672.      */
  673.     public boolean equals(Object obj) {
  674.         if (obj == null) return false;
  675.         if (!super.equals(obj)) return false;  // super does class check
  676.         RuleBasedCollator other = (RuleBasedCollator) obj;
  677.         // all other non-transient information is also contained in rules.
  678.         return (getRules().equals(other.getRules()));
  679.     }
  680.     /**
  681.      * Generates the hash code for the table-based collation object
  682.      */
  683.     public int hashCode() {
  684.         return getRules().hashCode();
  685.     }
  686.  
  687.     // ==============================================================
  688.     // private
  689.     // ==============================================================
  690.  
  691.     /**
  692.      * Write the collator out to a stream
  693.      */
  694.     private void writeObject(ObjectOutputStream stream) throws IOException
  695.     {
  696.         stream.defaultWriteObject();
  697.         stream.writeUTF(getRules());
  698.     }
  699.  
  700.     /**
  701.      * Read the collator in from a stream
  702.      */
  703.     private void readObject(ObjectInputStream stream) throws IOException,
  704.             ClassNotFoundException, ParseException
  705.     {
  706.         stream.defaultReadObject();
  707.  
  708.         String rules = stream.readUTF();
  709.  
  710.         // we can't rely on the constructor to do these for us from in here
  711.         key = new StringBuffer(MAXKEYSIZE);
  712.         primResult = new StringBuffer(MAXTOKENLEN);
  713.         secResult = new StringBuffer(MAXTOKENLEN);
  714.         terResult = new StringBuffer(MAXTOKENLEN);
  715.  
  716.         build(rules);
  717.     }
  718.  
  719.     /**
  720.      * Create a table-based collation object with the given rules.
  721.      * @see java.util.RuleBasedCollator#RuleBasedCollator
  722.      * @exception ParseException If the rules format is incorrect.
  723.      */
  724.     private void build(String pattern) throws ParseException
  725.     {
  726.         int aStrength = Collator.IDENTICAL;
  727.         boolean isSource = true;
  728.         int i = 0;
  729.         String expChars;
  730.         String groupChars;
  731.         if (pattern.length() == 0)
  732.             throw new ParseException("Build rules empty.", 0);
  733.  
  734.         // This array maps Unicode characters to their collation ordering
  735.         mapping = new CompactIntArray((int)UNMAPPED);
  736.  
  737.         // Normalize the build rules.  Find occurances of all decomposed characters
  738.         // and normalize the rules before feeding into the builder.  By "normalize",
  739.         // we mean that all precomposed Unicode characters must be converted into
  740.         // a base character and one or more combining characters (such as accents).
  741.         // When there are multiple combining characters attached to a base character,
  742.         // the combining characters must be in their canonical order
  743.         //
  744.         pattern = Normalizer.decompose(pattern, getDecomposition());
  745.  
  746.         // Build the merged collation entries
  747.         // Since rules can be specified in any order in the string
  748.         // (e.g. "c , C < d , D < e , E .... C < CH")
  749.         // this splits all of the rules in the string out into separate
  750.         // objects and then sorts them.  In the above example, it merges the
  751.         // "C < CH" rule in just before the "C < D" rule.
  752.         //
  753.         mPattern = new MergeCollation(pattern);
  754.  
  755.         // Now walk though each entry and add it to my own tables
  756.         for (i = 0; i < mPattern.getCount(); ++i)
  757.         {
  758.             PatternEntry entry = mPattern.getItemAt(i);
  759.             if (entry != null) {
  760.                 groupChars = entry.getChars();
  761.                 if ((groupChars.length() > 1) &&
  762.                     (groupChars.charAt(groupChars.length()-1) == '@')) {
  763.                     isFrenchSec = true;
  764.                     groupChars = groupChars.substring(0, groupChars.length()-1);
  765.                 }
  766.                 expChars = entry.getExtension();
  767.                 if (expChars.length() != 0) {
  768.                     addExpandOrder(groupChars, expChars, entry.getStrength());
  769.                 } else if (groupChars.length() > 1) {
  770.                     addContractOrder(groupChars, entry.getStrength());
  771.                     lastChar = groupChars.charAt(0);
  772.                 } else {
  773.                     char ch = groupChars.charAt(0);
  774.                     addOrder(ch, entry.getStrength());
  775.                     lastChar = ch;
  776.                 }
  777.             }
  778.         }
  779.         commit();
  780.         mapping.compact();
  781.     }
  782.     /**
  783.      * Look up for unmapped values in the expanded character table.
  784.      */
  785.     private final void commit()
  786.     {
  787.     // When the expanding character tables are built by addExpandOrder,
  788.     // it doesn't know what the final ordering of each character
  789.     // in the expansion will be.  Instead, it just puts the raw character
  790.     // code into the table, adding CHARINDEX as a flag.  Now that we've
  791.     // finished building the mapping table, we can go back and look up
  792.     // that character to see what its real collation order is and
  793.     // stick that into the expansion table.  That lets us avoid doing
  794.     // a two-stage lookup later.
  795.  
  796.         if (expandTable != null)
  797.         {
  798.             for (int i = 0; i < expandTable.size(); i++)
  799.             {
  800.                 int[] valueList = (int [])expandTable.elementAt(i);
  801.                 for (int j = 0; j < valueList.length; j++)
  802.                 {
  803.                     if ((valueList[j] < EXPANDCHARINDEX) &&
  804.                              (valueList[j] > CHARINDEX))
  805.                     {
  806.                         // found a expanding character
  807.                         // the expanding char value is not filled in yet
  808.                         char ch = (char)(valueList[j] - CHARINDEX);
  809.  
  810.                         // Get the real values for the non-filled entry
  811.                         int realValue = mapping.elementAt(ch);
  812.  
  813.                         if (realValue == UNMAPPED)
  814.                         {
  815.                             // The real value is still unmapped, maybe it's an ignorable
  816.                             // char
  817.                             valueList[j] = IGNORABLEMASK & valueList[j-1];
  818.                         }
  819.                         else if (realValue >= CONTRACTCHARINDEX)
  820.                         {
  821.                                 // if the entry is actually pointing to a contracting char
  822.                             EntryPair pair = null;
  823.                             Vector groupList = (Vector)
  824.                                 contractTable.elementAt(realValue
  825.                                                         - CONTRACTCHARINDEX);
  826.                             pair = (EntryPair)groupList.firstElement();
  827.                             valueList[j] = pair.value;
  828.                         }
  829.                         else
  830.                         {
  831.                             // just fill in the value
  832.                             valueList[j] = realValue;
  833.                         }
  834.                     }
  835.                 }
  836.             }
  837.         }
  838.     }
  839.     /**
  840.      *  Increment of the last order based on the comparison level.
  841.      */
  842.     private final int increment(int aStrength, int lastValue)
  843.     {
  844.         switch(aStrength)
  845.         {
  846.         case Collator.PRIMARY:
  847.             // increment priamry order  and mask off secondary and tertiary difference
  848.             lastValue += PRIMARYORDERINCREMENT;
  849.             lastValue &= PRIMARYORDERMASK;
  850.             isOverIgnore = true;
  851.             break;
  852.         case Collator.SECONDARY:
  853.             // increment secondary order and mask off tertiary difference
  854.             lastValue += SECONDARYORDERINCREMENT;
  855.             lastValue &= SECONDARYDIFFERENCEONLY;
  856.             // record max # of ignorable chars with secondary difference
  857.             if (!isOverIgnore)
  858.                 maxSecOrder++;
  859.             break;
  860.         case Collator.TERTIARY:
  861.             // increment tertiary order
  862.             lastValue += TERTIARYORDERINCREMENT;
  863.             // record max # of ignorable chars with tertiary difference
  864.             if (!isOverIgnore)
  865.                 maxTerOrder++;
  866.             break;
  867.         }
  868.         return lastValue;
  869.     }
  870.  
  871.     /**
  872.      *  Adds a character and its designated order into the collation table.
  873.      */
  874.     private final void addOrder(char ch,
  875.                                 int aStrength)
  876.     {
  877.         // See if the char already has an order in the mapping table
  878.         int order = mapping.elementAt(ch);
  879.  
  880.         if (order >= CONTRACTCHARINDEX) {
  881.             // There's already an entry for this character that points to a contracting
  882.             // character table.  Instead of adding the character directly to the mapping
  883.             // table, we must add it to the contract table instead.
  884.  
  885.             key.setLength(0);
  886.             key.append(ch);
  887.             addContractOrder(key.toString(), aStrength);
  888.         } else {
  889.             // add the entry to the mapping table,
  890.             // the same later entry replaces the previous one
  891.             currentOrder = increment(aStrength, currentOrder);
  892.             mapping.setElementAt(ch, currentOrder);
  893.         }
  894.     }
  895.     /**
  896.      *  Adds the contracting string into the collation table.
  897.      */
  898.     private final void addContractOrder(String groupChars,
  899.                                   int   aStrength)
  900.     {
  901.         if (contractTable == null) {
  902.             contractTable = new Vector(INITIALTABLESIZE);
  903.         }
  904.  
  905.         // Figure out what ordering to give this new entry
  906.         if (aStrength != IDENTICAL) {
  907.             currentOrder = increment(aStrength, currentOrder);
  908.         }
  909.  
  910.         // See if the initial character of the string already has a contract table.
  911.         int entry = mapping.elementAt(groupChars.charAt(0));
  912.         Vector entryTable = getContractValues(entry - CONTRACTCHARINDEX);
  913.  
  914.         if (entryTable != null) {
  915.             int index = getEntry(entryTable, groupChars);
  916.  
  917.             if (index != UNMAPPED) {
  918.                 // If there was already a contracting table for this character,
  919.                 // we simply want to add (or replace) this string in it
  920.                 EntryPair pair = (EntryPair) entryTable.elementAt(index);
  921.                 pair.value = currentOrder;
  922.             } else {
  923.                 entryTable.addElement(new EntryPair(groupChars, currentOrder));
  924.             }
  925.         }
  926.         else
  927.         {
  928.             // We need to create a new table of contract entries
  929.             entryTable = new Vector(INITIALTABLESIZE);
  930.             int tableIndex = CONTRACTCHARINDEX + contractTable.size();
  931.  
  932.             // Always add the initial character's current ordering first.
  933.             entryTable.addElement(new EntryPair(groupChars.substring(0,1), entry));
  934.  
  935.             // And add the new one
  936.             entryTable.addElement(new EntryPair(groupChars, currentOrder));
  937.  
  938.             // Finally, add the new value table to the main contract table
  939.             // and update this character's mapping to point to it.
  940.             contractTable.addElement(entryTable);
  941.             mapping.setElementAt(groupChars.charAt(0), tableIndex);
  942.         }
  943.     }
  944.  
  945.     private final int getEntry(Vector list, String name) {
  946.         for (int i = 0; i < list.size(); i++) {
  947.             EntryPair pair = (EntryPair)list.elementAt(i);
  948.             if (pair.entryName.equals(name)) {
  949.                 return i;
  950.             }
  951.         }
  952.         return UNMAPPED;
  953.     }
  954.     /**
  955.      *  Get the entry of hash table of the contracting string in the collation
  956.      *  table.
  957.      *  @param ch the starting character of the contracting string
  958.      */
  959.     Vector getContractValues(char ch)
  960.     {
  961.         int index = mapping.elementAt(ch);
  962.         return getContractValues(index - CONTRACTCHARINDEX);
  963.     }
  964.  
  965.     Vector getContractValues(int index)
  966.     {
  967.         if (index >= 0)
  968.         {
  969.             return (Vector)contractTable.elementAt(index);
  970.         }
  971.         else // not found
  972.         {
  973.             return null;
  974.         }
  975.     }
  976.  
  977.     /**
  978.      *  Adds the expanding string into the collation table.
  979.      */
  980.     private final void addExpandOrder(String contractChars,
  981.                                 String expandChars,
  982.                                 int   aStrength) throws ParseException
  983.     {
  984.         EntryPair pair = new EntryPair();
  985.  
  986.         // Make a expanding char table if there's not one.
  987.         if (expandTable == null)
  988.         {
  989.             expandTable = new Vector(INITIALTABLESIZE);
  990.         }
  991.  
  992.         // For expanding characters, what we stick into the main mapping table
  993.         // is the character's index in the expand table, plus a flag to indicate
  994.         // that it's an  expanding character.
  995.         int tmpValue = EXPANDCHARINDEX + expandTable.size();
  996.  
  997.         // need to check if the entry is key or not later
  998.         key.setLength(0);
  999.         int keyValue = UNMAPPED;
  1000.  
  1001.         if (contractChars.length() > 1)
  1002.         {
  1003.             // This entry is actually a string of characters that contract
  1004.             // and then expand back into a different string.
  1005.             // First, we have to make sure that the entry is in the contract table
  1006.             //
  1007.             addContractOrder(contractChars, aStrength);
  1008.  
  1009.             // Remember the character we just added, so that the code in build() can use it
  1010.             // to decide where to put the next character.
  1011.             lastChar = contractChars.charAt(0);
  1012.  
  1013.             // Now that there's a contracting-table entry for this key, set its value
  1014.             // to the expanding character sequence
  1015.             Vector list = getContractValues(contractChars.charAt(0));
  1016.             int entry = UNMAPPED;
  1017.             entry = getEntry(list, contractChars);
  1018.             if (entry != UNMAPPED) {
  1019.                 pair = (EntryPair)list.elementAt(entry);
  1020.                 // Remember what this entry's old value was, for use below.
  1021.                 keyValue = pair.value;
  1022.             }
  1023.             pair.entryName = contractChars;
  1024.             pair.value = tmpValue;
  1025.         }
  1026.         else
  1027.         {
  1028.             // There's no contraction involved, just a single character expanding
  1029.             // into several other characters.
  1030.  
  1031.             char ch = contractChars.charAt(0);
  1032.             if ((keyValue = mapping.elementAt(ch)) == UNMAPPED) {
  1033.                 // This character doesn't have an entry in the mapping table yet,
  1034.                 // so make one for it.
  1035.                 addOrder(ch, aStrength);
  1036.                 lastChar = ch;
  1037.                 // Remember the ordering that we just created for this character...
  1038.                 keyValue = mapping.elementAt(lastChar);
  1039.             } else {
  1040.                 // This character already had an ordering, which we don't want to disturb,
  1041.                 // so create a new one to use.
  1042.                 keyValue = increment(aStrength, mapping.elementAt(lastChar));
  1043.             }
  1044.             mapping.setElementAt(ch, tmpValue);
  1045.         }
  1046.  
  1047.         // Create a list of the collation orders that this expands into...
  1048.         int[] valueList = new int[expandChars.length()+1];
  1049.         valueList[0] = keyValue;
  1050.  
  1051.         for (int i = 0; i < expandChars.length(); i++)
  1052.         {
  1053.             int mapValue = mapping.elementAt(expandChars.charAt(i));
  1054.             if (mapValue >= CONTRACTCHARINDEX)
  1055.             {
  1056.                 // if the expanding char is also a contracting char, look up the value
  1057.                 key.append(expandChars.charAt(i));
  1058.                 int foundValue = CHARINDEX + expandChars.charAt(i);
  1059.                 Vector list = getContractValues(expandChars.charAt(i));
  1060.                 if (list != null) {
  1061.                     int entry = UNMAPPED;
  1062.                     entry = getEntry(list, key.toString());
  1063.                     if (entry != UNMAPPED) {
  1064.                         pair = (EntryPair)list.elementAt(entry);
  1065.                         foundValue = pair.value;
  1066.                     }
  1067.                 }
  1068.                 key.setLength(0);
  1069.                 valueList[i+1] = foundValue;
  1070.             }
  1071.             else if (mapValue != UNMAPPED)
  1072.             {
  1073.                 // can't find it in the table, will be filled in by commit().
  1074.                 valueList[i+1] = mapValue;
  1075.             }
  1076.             else
  1077.             {
  1078.                 valueList[i+1] = CHARINDEX + (int)(expandChars.charAt(i));
  1079.             }
  1080.         }
  1081.         // Add the expanding char list into the table, finally.
  1082.         expandTable.addElement(valueList);
  1083.     }
  1084.  
  1085.     /**
  1086.      *  Get the entry of hash table of the expanding string in the collation
  1087.      *  table.
  1088.      *  @param ch the starting character of the expanding string
  1089.      */
  1090.     final int[] getExpandValueList(char ch)
  1091.     {
  1092.         int expIndex = mapping.elementAt(ch);
  1093.         if ((expIndex >= EXPANDCHARINDEX) &&
  1094.             (expIndex < CONTRACTCHARINDEX))
  1095.         {
  1096.             int tmpIndex = expIndex - EXPANDCHARINDEX;
  1097.             return (int[])expandTable.elementAt(tmpIndex);
  1098.         }
  1099.         else
  1100.         {
  1101.             return null;
  1102.         }
  1103.     }
  1104.     /**
  1105.      *  Get the entry of hash table of the expanding string in the collation
  1106.      *  table.
  1107.      *  @param idx the index of the expanding string value list
  1108.      */
  1109.     final int[] getExpandValueList(int idx)
  1110.     {
  1111.         if (idx < expandTable.size())
  1112.         {
  1113.             return (int[])expandTable.elementAt(idx);
  1114.         }
  1115.         else
  1116.         {
  1117.             return null;
  1118.         }
  1119.     }
  1120.     /**
  1121.      *  Get the comarison order of a character from the collation table.
  1122.      *  @return the comparison order of a character.
  1123.      */
  1124.     final int getUnicodeOrder(char ch)
  1125.     {
  1126.         return mapping.elementAt(ch);
  1127.     }
  1128.  
  1129.     /**
  1130.      * Check for the secondary and tertiary differences of source and
  1131.      * target comparison orders.
  1132.      * @return Collator.LESS if sOrder < tOrder; EQUAL if sOrder == tOrder;
  1133.      * Collator.GREATER if sOrder > tOrder.
  1134.      */
  1135.     private final int checkSecTerDiff(int sOrder,
  1136.                                       int tOrder,
  1137.                                       int result,
  1138.                                       boolean skipSecCheck)
  1139.     {
  1140.         int endResult = result;
  1141.         if (CollationElementIterator.secondaryOrder(sOrder) !=
  1142.             CollationElementIterator.secondaryOrder(tOrder))
  1143.         {
  1144.             if ((!isFrenchSec &&
  1145.                  (result == Collator.EQUAL || strengthResult > Collator.SECONDARY)) ||
  1146.                 (isFrenchSec && !skipSecCheck))
  1147.              {
  1148.                 strengthResult = Collator.SECONDARY;
  1149.                 if (CollationElementIterator.secondaryOrder(sOrder) <
  1150.                     CollationElementIterator.secondaryOrder(tOrder))
  1151.                     endResult = Collator.LESS;
  1152.                 else
  1153.                     endResult = Collator.GREATER;
  1154.             }
  1155.         }
  1156.         else if ((CollationElementIterator.tertiaryOrder(sOrder) !=
  1157.                   CollationElementIterator.tertiaryOrder(tOrder)) &&
  1158.                  (endResult == Collator.EQUAL))
  1159.         {
  1160.             strengthResult = Collator.TERTIARY;
  1161.             if (CollationElementIterator.tertiaryOrder(sOrder) <
  1162.                 CollationElementIterator.tertiaryOrder(tOrder))
  1163.                 endResult = Collator.LESS;
  1164.             else
  1165.                 endResult = Collator.GREATER;
  1166.         }
  1167.         return endResult;
  1168.     }
  1169.     /**
  1170.      * Reverse a string.
  1171.      */
  1172.     private final void reverse (StringBuffer result, int from, int to)
  1173.     {
  1174.         int i = from;
  1175.         char swap;
  1176.  
  1177.         int j = to - 1;
  1178.         while (i < j) {
  1179.             swap =  result.charAt(i);
  1180.             result.setCharAt(i, result.charAt(j));
  1181.             result.setCharAt(j, swap);
  1182.             i++;
  1183.             j--;
  1184.         }
  1185.     }
  1186.  
  1187.     // Proclaim compatibility with 1.1
  1188.     static final long serialVersionUID = 2822366911447564107L;
  1189.  
  1190.     static int CHARINDEX = 0x70000000;  // need look up in .commit()
  1191.     static int EXPANDCHARINDEX = 0x7E000000; // Expand index follows
  1192.     static int CONTRACTCHARINDEX = 0x7F000000;  // contract indexes follow
  1193.     static int UNMAPPED = 0xFFFFFFFF;
  1194.  
  1195.     private final static int SHORT_MAX_VALUE = 32767;
  1196.     private final static int PRIMARYORDERINCREMENT = 0x00010000;
  1197.     private final static int MAXIGNORABLE = 0x00010000;
  1198.     private final static int SECONDARYORDERINCREMENT = 0x00000100;
  1199.     private final static int TERTIARYORDERINCREMENT = 0x00000001;
  1200.     final static int PRIMARYORDERMASK = 0xffff0000;
  1201.     final static int SECONDARYORDERMASK = 0x0000ff00;
  1202.     final static int TERTIARYORDERMASK = 0x000000ff;
  1203.     final static int PRIMARYDIFFERENCEONLY = 0xffff0000;
  1204.     final static int SECONDARYDIFFERENCEONLY = 0xffffff00;
  1205.     private final static int SECONDARYRESETMASK = 0x0000ffff;
  1206.     private final static int IGNORABLEMASK = 0x0000ffff;
  1207.     private final static int INITIALTABLESIZE = 20;
  1208.     private final static int MAXKEYSIZE = 5;
  1209.     static int PRIMARYORDERSHIFT = 16;
  1210.     static int SECONDARYORDERSHIFT = 8;
  1211.     private final static int MAXTOKENLEN = 256;
  1212.     private final static int MAXRULELEN = 512;
  1213.     private final static int COLLATIONKEYOFFSET = 1;
  1214.  
  1215.     // these data members are reconstructed by readObject()
  1216.     private transient boolean isFrenchSec = false;
  1217.     private transient String ruleTable = null;
  1218.  
  1219.     private transient CompactIntArray mapping = null;
  1220.     private transient Vector   contractTable = null;
  1221.     private transient Vector   expandTable = null;
  1222.  
  1223.     // transients, only used in build or processing
  1224.     private transient MergeCollation mPattern = null;
  1225.     private transient boolean isOverIgnore = false;
  1226.     private transient int currentOrder = 0;
  1227.     private transient short maxSecOrder = 0;
  1228.     private transient short maxTerOrder = 0;
  1229.     private transient char lastChar;
  1230.     private transient StringBuffer key = new StringBuffer(MAXKEYSIZE);
  1231.     private transient int strengthResult = Collator.IDENTICAL;
  1232.     private transient StringBuffer primResult = new StringBuffer(MAXTOKENLEN);
  1233.     private transient StringBuffer secResult = new StringBuffer(MAXTOKENLEN);
  1234.     private transient StringBuffer terResult = new StringBuffer(MAXTOKENLEN);
  1235. }
  1236.  
  1237.