1. /*
  2. * @(#)RuleBasedCollator.java 1.28 00/01/19
  3. *
  4. * Copyright 1997-2000 Sun Microsystems, Inc. All Rights Reserved.
  5. *
  6. * This software is the proprietary information of Sun Microsystems, Inc.
  7. * Use is subject to license terms.
  8. *
  9. */
  10. /*
  11. * (C) Copyright Taligent, Inc. 1996, 1997 - All Rights Reserved
  12. * (C) Copyright IBM Corp. 1996-1998 - All Rights Reserved
  13. *
  14. * The original version of this source code and documentation is copyrighted
  15. * and owned by Taligent, Inc., a wholly-owned subsidiary of IBM. These
  16. * materials are provided under terms of a License Agreement between Taligent
  17. * and Sun. This technology is protected by multiple US and International
  18. * patents. This notice and attribution to Taligent may not be removed.
  19. * Taligent is a registered trademark of Taligent, Inc.
  20. *
  21. */
  22. package java.text;
  23. import java.util.Vector;
  24. import java.util.Locale;
  25. /**
  26. * The <code>RuleBasedCollator</code> class is a concrete subclass of
  27. * <code>Collator</code> that provides a simple, data-driven, table
  28. * collator. With this class you can create a customized table-based
  29. * <code>Collator</code>. <code>RuleBasedCollator</code> maps
  30. * characters to sort keys.
  31. *
  32. * <p>
  33. * <code>RuleBasedCollator</code> has the following restrictions
  34. * for efficiency (other subclasses may be used for more complex languages) :
  35. * <ol>
  36. * <li>If a French secondary ordering is specified it applies to the
  37. * whole collator object.
  38. * <li>All non-mentioned Unicode characters are at the end of the
  39. * collation order.
  40. * </ol>
  41. *
  42. * <p>
  43. * The collation table is composed of a list of collation rules, where each
  44. * rule is of three forms:
  45. * <pre>
  46. * < modifier >
  47. * < relation > < text-argument >
  48. * < reset > < text-argument >
  49. * </pre>
  50. * The following demonstrates how to create your own collation rules:
  51. * <UL Type=disc>
  52. * <LI><strong>Text-Argument</strong>: A text-argument is any sequence of
  53. * characters, excluding special characters (that is, common
  54. * whitespace characters [0009-000D, 0020] and rule syntax characters
  55. * [0021-002F, 003A-0040, 005B-0060, 007B-007E]). If those
  56. * characters are desired, you can put them in single quotes
  57. * (e.g. ampersand => '&'). Note that unquoted white space characters
  58. * are ignored; e.g. <code>b c</code> is treated as <code>bc</code>.
  59. * <LI><strong>Modifier</strong>: There is a single modifier
  60. * which is used to specify that all accents (secondary differences) are
  61. * backwards.
  62. * <p>'@' : Indicates that accents are sorted backwards, as in French.
  63. * <LI><strong>Relation</strong>: The relations are the following:
  64. * <UL Type=square>
  65. * <LI>'<' : Greater, as a letter difference (primary)
  66. * <LI>';' : Greater, as an accent difference (secondary)
  67. * <LI>',' : Greater, as a case difference (tertiary)
  68. * <LI>'=' : Equal
  69. * </UL>
  70. * <LI><strong>Reset</strong>: There is a single reset
  71. * which is used primarily for contractions and expansions, but which
  72. * can also be used to add a modification at the end of a set of rules.
  73. * <p>'&' : Indicates that the next rule follows the position to where
  74. * the reset text-argument would be sorted.
  75. * </UL>
  76. *
  77. * <p>
  78. * This sounds more complicated than it is in practice. For example, the
  79. * following are equivalent ways of expressing the same thing:
  80. * <blockquote>
  81. * <pre>
  82. * a < b < c
  83. * a < b & b < c
  84. * a < c & a < b
  85. * </pre>
  86. * </blockquote>
  87. * Notice that the order is important, as the subsequent item goes immediately
  88. * after the text-argument. The following are not equivalent:
  89. * <blockquote>
  90. * <pre>
  91. * a < b & a < c
  92. * a < c & a < b
  93. * </pre>
  94. * </blockquote>
  95. * Either the text-argument must already be present in the sequence, or some
  96. * initial substring of the text-argument must be present. (e.g. "a < b & ae <
  97. * e" is valid since "a" is present in the sequence before "ae" is reset). In
  98. * this latter case, "ae" is not entered and treated as a single character;
  99. * instead, "e" is sorted as if it were expanded to two characters: "a"
  100. * followed by an "e". This difference appears in natural languages: in
  101. * traditional Spanish "ch" is treated as though it contracts to a single
  102. * character (expressed as "c < ch < d"), while in traditional German
  103. * a-umlaut is treated as though it expanded to two characters
  104. * (expressed as "a,A < b,B ... & ae;\u00e3 & AE;\u00c3").
  105. * [\u00e3 and \u00c3 are, of course, the escape sequences for a-umlaut.]
  106. * <p>
  107. * <strong>Ignorable Characters</strong>
  108. * <p>
  109. * For ignorable characters, the first rule must start with a relation (the
  110. * examples we have used above are really fragments; "a < b" really should be
  111. * "< a < b"). If, however, the first relation is not "<", then all the all
  112. * text-arguments up to the first "<" are ignorable. For example, ", - < a < b"
  113. * makes "-" an ignorable character, as we saw earlier in the word
  114. * "black-birds". In the samples for different languages, you see that most
  115. * accents are ignorable.
  116. *
  117. * <p><strong>Normalization and Accents</strong>
  118. * <p>
  119. * <code>RuleBasedCollator</code> automatically processes its rule table to
  120. * include both pre-composed and combining-character versions of
  121. * accented characters. Even if the provided rule string contains only
  122. * base characters and separate combining accent characters, the pre-composed
  123. * accented characters matching all canonical combinations of characters from
  124. * the rule string will be entered in the table.
  125. * <p>
  126. * This allows you to use a RuleBasedCollator to compare accented strings
  127. * even when the collator is set to NO_DECOMPOSITION. There are two caveats,
  128. * however. First, if the strings to be collated contain combining
  129. * sequences that may not be in canonical order, you should set the collator to
  130. * CANONICAL_DECOMPOSITION or FULL_DECOMPOSITION to enable sorting of
  131. * combining sequences. Second, if the strings contain characters with
  132. * compatibility decompositions (such as full-width and half-width forms),
  133. * you must use FULL_DECOMPOSITION, since the rule tables only include
  134. * canonical mappings.
  135. * For more information, see
  136. * <A HREF="http://www.aw.com/devpress">The Unicode Standard, Version 2.0</A>.)
  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.25 07/24/98
  262. * @author Helena Shih, Laura Werner, Richard Gillam
  263. */
  264. public class RuleBasedCollator extends Collator{
  265. // IMPLEMENTATION NOTES: The implementation of the collation algorithm is
  266. // divided across three classes: RuleBasedCollator, RBCollationTables, and
  267. // CollationElementIterator. RuleBasedCollator contains the collator's
  268. // transient state and includes the code that uses the other classes to
  269. // implement comparison and sort-key building. RuleBasedCollator also
  270. // contains the logic to handle French secondary accent sorting.
  271. // A RuleBasedCollator has two CollationElementIterators. State doesn't
  272. // need to be preserved in these objects between calls to compare() or
  273. // getCollationKey(), but the objects persist anyway to avoid wasting extra
  274. // creation time. compare() and getCollationKey() are synchronized to ensure
  275. // thread safety with this scheme. The CollationElementIterator is responsible
  276. // for generating collation elements from strings and returning one element at
  277. // a time (sometimes there's a one-to-many or many-to-one mapping between
  278. // characters and collation elements-- this class handles that).
  279. // CollationElementIterator depends on RBCollationTables, which contains the
  280. // collator's static state. RBCollationTables contains the actual data
  281. // tables specifying the collation order of characters for a particular locale
  282. // or use. It also contains the base logic that CollationElementIterator
  283. // uses to map from characters to collation elements. A single RBCollationTables
  284. // object is shared among all RuleBasedCollators for the same locale, and
  285. // thus by all the CollationElementIterators they create.
  286. /**
  287. * RuleBasedCollator constructor. This takes the table rules and builds
  288. * a collation table out of them. Please see RuleBasedCollator class
  289. * description for more details on the collation rule syntax.
  290. * @see java.util.Locale
  291. * @param rules the collation rules to build the collation table from.
  292. * @exception ParseException A format exception
  293. * will be thrown if the build process of the rules fails. For
  294. * example, build rule "a < ? < d" will cause the constructor to
  295. * throw the ParseException because the '?' is not quoted.
  296. */
  297. public RuleBasedCollator(String rules) throws ParseException {
  298. this(rules, Collator.CANONICAL_DECOMPOSITION);
  299. }
  300. /**
  301. * RuleBasedCollator constructor. This takes the table rules and builds
  302. * a collation table out of them. Please see RuleBasedCollator class
  303. * description for more details on the collation rule syntax.
  304. * @see java.util.Locale
  305. * @param rules the collation rules to build the collation table from.
  306. * @param decomp the decomposition strength used to build the
  307. * collation table and to perform comparisons.
  308. * @exception ParseException A format exception
  309. * will be thrown if the build process of the rules fails. For
  310. * example, build rule "a < ? < d" will cause the constructor to
  311. * throw the ParseException because the '?' is not quoted.
  312. */
  313. RuleBasedCollator(String rules, int decomp) throws ParseException {
  314. setStrength(Collator.TERTIARY);
  315. setDecomposition(decomp);
  316. tables = new RBCollationTables(rules, decomp);
  317. }
  318. /**
  319. * "Copy constructor." Used in clone() for performance.
  320. */
  321. private RuleBasedCollator(RuleBasedCollator that) {
  322. setStrength(that.getStrength());
  323. setDecomposition(that.getDecomposition());
  324. tables = that.tables;
  325. }
  326. /**
  327. * Gets the table-based rules for the collation object.
  328. * @return returns the collation rules that the table collation object
  329. * was created from.
  330. */
  331. public String getRules()
  332. {
  333. return tables.getRules();
  334. }
  335. /**
  336. * Return a CollationElementIterator for the given String.
  337. * @see java.text.CollationElementIterator
  338. */
  339. public CollationElementIterator getCollationElementIterator(String source) {
  340. return new CollationElementIterator( source, this );
  341. }
  342. /**
  343. * Return a CollationElementIterator for the given String.
  344. * @see java.text.CollationElementIterator
  345. */
  346. public CollationElementIterator getCollationElementIterator(
  347. CharacterIterator source) {
  348. return new CollationElementIterator( source, this );
  349. }
  350. /**
  351. * Compares the character data stored in two different strings based on the
  352. * collation rules. Returns information about whether a string is less
  353. * than, greater than or equal to another string in a language.
  354. * This can be overriden in a subclass.
  355. */
  356. public synchronized int compare(String source, String target)
  357. {
  358. // The basic algorithm here is that we use CollationElementIterators
  359. // to step through both the source and target strings. We compare each
  360. // collation element in the source string against the corresponding one
  361. // in the target, checking for differences.
  362. //
  363. // If a difference is found, we set <result> to LESS or GREATER to
  364. // indicate whether the source string is less or greater than the target.
  365. //
  366. // However, it's not that simple. If we find a tertiary difference
  367. // (e.g. 'A' vs. 'a') near the beginning of a string, it can be
  368. // overridden by a primary difference (e.g. "A" vs. "B") later in
  369. // the string. For example, "AA" < "aB", even though 'A' > 'a'.
  370. //
  371. // To keep track of this, we use strengthResult to keep track of the
  372. // strength of the most significant difference that has been found
  373. // so far. When we find a difference whose strength is greater than
  374. // strengthResult, it overrides the last difference (if any) that
  375. // was found.
  376. int result = Collator.EQUAL;
  377. if (sourceCursor == null) {
  378. sourceCursor = getCollationElementIterator(source);
  379. } else {
  380. sourceCursor.setText(source);
  381. }
  382. if (targetCursor == null) {
  383. targetCursor = getCollationElementIterator(target);
  384. } else {
  385. targetCursor.setText(target);
  386. }
  387. int sOrder = 0, tOrder = 0;
  388. boolean initialCheckSecTer = getStrength() >= Collator.SECONDARY;
  389. boolean checkSecTer = initialCheckSecTer;
  390. boolean checkTertiary = getStrength() >= Collator.TERTIARY;
  391. boolean gets = true, gett = true;
  392. while(true) {
  393. // Get the next collation element in each of the strings, unless
  394. // we've been requested to skip it.
  395. if (gets) sOrder = sourceCursor.next(); else gets = true;
  396. if (gett) tOrder = targetCursor.next(); else gett = true;
  397. // If we've hit the end of one of the strings, jump out of the loop
  398. if ((sOrder == CollationElementIterator.NULLORDER)||
  399. (tOrder == CollationElementIterator.NULLORDER))
  400. break;
  401. int pSOrder = CollationElementIterator.primaryOrder(sOrder);
  402. int pTOrder = CollationElementIterator.primaryOrder(tOrder);
  403. // If there's no difference at this position, we can skip it
  404. if (sOrder == tOrder) {
  405. if (tables.isFrenchSec() && pSOrder != 0) {
  406. if (!checkSecTer) {
  407. // in french, a secondary difference more to the right is stronger,
  408. // so accents have to be checked with each base element
  409. checkSecTer = initialCheckSecTer;
  410. // but tertiary differences are less important than the first
  411. // secondary difference, so checking tertiary remains disabled
  412. checkTertiary = false;
  413. }
  414. }
  415. continue;
  416. }
  417. // Compare primary differences first.
  418. if ( pSOrder != pTOrder )
  419. {
  420. if (sOrder == 0) {
  421. // The entire source element is ignorable.
  422. // Skip to the next source element, but don't fetch another target element.
  423. gett = false;
  424. continue;
  425. }
  426. if (tOrder == 0) {
  427. gets = false;
  428. continue;
  429. }
  430. // The source and target elements aren't ignorable, but it's still possible
  431. // for the primary component of one of the elements to be ignorable....
  432. if (pSOrder == 0) // primary order in source is ignorable
  433. {
  434. // The source's primary is ignorable, but the target's isn't. We treat ignorables
  435. // as a secondary difference, so remember that we found one.
  436. if (checkSecTer) {
  437. result = Collator.GREATER; // (strength is SECONDARY)
  438. checkSecTer = false;
  439. }
  440. // Skip to the next source element, but don't fetch another target element.
  441. gett = false;
  442. }
  443. else if (pTOrder == 0)
  444. {
  445. // record differences - see the comment above.
  446. if (checkSecTer) {
  447. result = Collator.LESS; // (strength is SECONDARY)
  448. checkSecTer = false;
  449. }
  450. // Skip to the next source element, but don't fetch another target element.
  451. gets = false;
  452. } else {
  453. // Neither of the orders is ignorable, and we already know that the primary
  454. // orders are different because of the (pSOrder != pTOrder) test above.
  455. // Record the difference and stop the comparison.
  456. if (pSOrder < pTOrder) {
  457. return Collator.LESS; // (strength is PRIMARY)
  458. } else {
  459. return Collator.GREATER; // (strength is PRIMARY)
  460. }
  461. }
  462. } else { // else of if ( pSOrder != pTOrder )
  463. // primary order is the same, but complete order is different. So there
  464. // are no base elements at this point, only ignorables (Since the strings are
  465. // normalized)
  466. if (checkSecTer) {
  467. // a secondary or tertiary difference may still matter
  468. short secSOrder = CollationElementIterator.secondaryOrder(sOrder);
  469. short secTOrder = CollationElementIterator.secondaryOrder(tOrder);
  470. if (secSOrder != secTOrder) {
  471. // there is a secondary difference
  472. result = (secSOrder < secTOrder) ? Collator.LESS : Collator.GREATER;
  473. // (strength is SECONDARY)
  474. checkSecTer = false;
  475. // (even in french, only the first secondary difference within
  476. // a base character matters)
  477. } else {
  478. if (checkTertiary) {
  479. // a tertiary difference may still matter
  480. short terSOrder = CollationElementIterator.tertiaryOrder(sOrder);
  481. short terTOrder = CollationElementIterator.tertiaryOrder(tOrder);
  482. if (terSOrder != terTOrder) {
  483. // there is a tertiary difference
  484. result = (terSOrder < terTOrder) ? Collator.LESS : Collator.GREATER;
  485. // (strength is TERTIARY)
  486. checkTertiary = false;
  487. }
  488. }
  489. }
  490. } // if (checkSecTer)
  491. } // if ( pSOrder != pTOrder )
  492. } // while()
  493. if (sOrder != CollationElementIterator.NULLORDER) {
  494. // (tOrder must be CollationElementIterator::NULLORDER,
  495. // since this point is only reached when sOrder or tOrder is NULLORDER.)
  496. // The source string has more elements, but the target string hasn't.
  497. do {
  498. if (CollationElementIterator.primaryOrder(sOrder) != 0) {
  499. // We found an additional non-ignorable base character in the source string.
  500. // This is a primary difference, so the source is greater
  501. return Collator.GREATER; // (strength is PRIMARY)
  502. }
  503. else if (CollationElementIterator.secondaryOrder(sOrder) != 0) {
  504. // Additional secondary elements mean the source string is greater
  505. if (checkSecTer) {
  506. result = Collator.GREATER; // (strength is SECONDARY)
  507. checkSecTer = false;
  508. }
  509. }
  510. } while ((sOrder = sourceCursor.next()) != CollationElementIterator.NULLORDER);
  511. }
  512. else if (tOrder != CollationElementIterator.NULLORDER) {
  513. // The target string has more elements, but the source string hasn't.
  514. do {
  515. if (CollationElementIterator.primaryOrder(tOrder) != 0)
  516. // We found an additional non-ignorable base character in the target string.
  517. // This is a primary difference, so the source is less
  518. return Collator.LESS; // (strength is PRIMARY)
  519. else if (CollationElementIterator.secondaryOrder(tOrder) != 0) {
  520. // Additional secondary elements in the target mean the source string is less
  521. if (checkSecTer) {
  522. result = Collator.LESS; // (strength is SECONDARY)
  523. checkSecTer = false;
  524. }
  525. }
  526. } while ((tOrder = targetCursor.next()) != CollationElementIterator.NULLORDER);
  527. }
  528. // For IDENTICAL comparisons, we use a bitwise character comparison
  529. // as a tiebreaker if all else is equal
  530. if (result == 0 && getStrength() == IDENTICAL) {
  531. result = Normalizer.decompose(source,getDecomposition())
  532. .compareTo(Normalizer.decompose(target,getDecomposition()));
  533. }
  534. return result;
  535. }
  536. /**
  537. * Transforms the string into a series of characters that can be compared
  538. * with CollationKey.compareTo. This overrides java.text.Collator.getCollationKey.
  539. * It can be overriden in a subclass.
  540. */
  541. public synchronized CollationKey getCollationKey(String source)
  542. {
  543. //
  544. // The basic algorithm here is to find all of the collation elements for each
  545. // character in the source string, convert them to a char representation,
  546. // and put them into the collation key. But it's trickier than that.
  547. // Each collation element in a string has three components: primary (A vs B),
  548. // secondary (A vs A-acute), and tertiary (A' vs a); and a primary difference
  549. // at the end of a string takes precedence over a secondary or tertiary
  550. // difference earlier in the string.
  551. //
  552. // To account for this, we put all of the primary orders at the beginning of the
  553. // string, followed by the secondary and tertiary orders, separated by nulls.
  554. //
  555. // Here's a hypothetical example, with the collation element represented as
  556. // a three-digit number, one digit for primary, one for secondary, etc.
  557. //
  558. // String: A a B \u00e9 <--(e-acute)
  559. // Collation Elements: 101 100 201 510
  560. //
  561. // Collation Key: 1125<null>0001<null>1010
  562. //
  563. // To make things even trickier, secondary differences (accent marks) are compared
  564. // starting at the *end* of the string in languages with French secondary ordering.
  565. // But when comparing the accent marks on a single base character, they are compared
  566. // from the beginning. To handle this, we reverse all of the accents that belong
  567. // to each base character, then we reverse the entire string of secondary orderings
  568. // at the end. Taking the same example above, a French collator might return
  569. // this instead:
  570. //
  571. // Collation Key: 1125<null>1000<null>1010
  572. //
  573. if (source == null)
  574. return null;
  575. if (primResult == null) {
  576. primResult = new StringBuffer();
  577. secResult = new StringBuffer();
  578. terResult = new StringBuffer();
  579. } else {
  580. primResult.setLength(0);
  581. secResult.setLength(0);
  582. terResult.setLength(0);
  583. }
  584. int order = 0;
  585. boolean compareSec = (getStrength() >= Collator.SECONDARY);
  586. boolean compareTer = (getStrength() >= Collator.TERTIARY);
  587. int secOrder = CollationElementIterator.NULLORDER;
  588. int terOrder = CollationElementIterator.NULLORDER;
  589. int preSecIgnore = 0;
  590. if (sourceCursor == null) {
  591. sourceCursor = getCollationElementIterator(source);
  592. } else {
  593. sourceCursor.setText(source);
  594. }
  595. // walk through each character
  596. while ((order = sourceCursor.next()) !=
  597. CollationElementIterator.NULLORDER)
  598. {
  599. secOrder = CollationElementIterator.secondaryOrder(order);
  600. terOrder = CollationElementIterator.tertiaryOrder(order);
  601. if (!CollationElementIterator.isIgnorable(order))
  602. {
  603. primResult.append((char) (CollationElementIterator.primaryOrder(order)
  604. + COLLATIONKEYOFFSET));
  605. if (compareSec) {
  606. //
  607. // accumulate all of the ignorable/secondary characters attached
  608. // to a given base character
  609. //
  610. if (tables.isFrenchSec() && preSecIgnore < secResult.length()) {
  611. //
  612. // We're doing reversed secondary ordering and we've hit a base
  613. // (non-ignorable) character. Reverse any secondary orderings
  614. // that applied to the last base character. (see block comment above.)
  615. //
  616. RBCollationTables.reverse(secResult, preSecIgnore, secResult.length());
  617. }
  618. // Remember where we are in the secondary orderings - this is how far
  619. // back to go if we need to reverse them later.
  620. secResult.append((char)(secOrder+ COLLATIONKEYOFFSET));
  621. preSecIgnore = secResult.length();
  622. }
  623. if (compareTer) {
  624. terResult.append((char)(terOrder+ COLLATIONKEYOFFSET));
  625. }
  626. }
  627. else
  628. {
  629. if (compareSec && secOrder != 0)
  630. secResult.append((char)
  631. (secOrder + tables.getMaxSecOrder() + COLLATIONKEYOFFSET));
  632. if (compareTer && terOrder != 0)
  633. terResult.append((char)
  634. (terOrder + tables.getMaxTerOrder() + COLLATIONKEYOFFSET));
  635. }
  636. }
  637. if (tables.isFrenchSec())
  638. {
  639. if (preSecIgnore < secResult.length()) {
  640. // If we've accumlated any secondary characters after the last base character,
  641. // reverse them.
  642. RBCollationTables.reverse(secResult, preSecIgnore, secResult.length());
  643. }
  644. // And now reverse the entire secResult to get French secondary ordering.
  645. RBCollationTables.reverse(secResult, 0, secResult.length());
  646. }
  647. primResult.append((char)0);
  648. secResult.append((char)0);
  649. secResult.append(terResult.toString());
  650. primResult.append(secResult.toString());
  651. if (getStrength() == IDENTICAL) {
  652. primResult.append((char)0);
  653. primResult.append(Normalizer.decompose(source,getDecomposition()));
  654. }
  655. return new CollationKey(source, primResult.toString());
  656. }
  657. /**
  658. * Standard override; no change in semantics.
  659. */
  660. public Object clone() {
  661. // if we know we're not actually a subclass of RuleBasedCollator
  662. // (this class really should have been made final), bypass
  663. // Object.clone() and use our "copy constructor". This is faster.
  664. if (getClass() == RuleBasedCollator.class) {
  665. return new RuleBasedCollator(this);
  666. }
  667. else {
  668. RuleBasedCollator result = (RuleBasedCollator) super.clone();
  669. result.primResult = null;
  670. result.secResult = null;
  671. result.terResult = null;
  672. result.sourceCursor = null;
  673. result.targetCursor = null;
  674. return result;
  675. }
  676. }
  677. /**
  678. * Compares the equality of two collation objects.
  679. * @param obj the table-based collation object to be compared with this.
  680. * @return true if the current table-based collation object is the same
  681. * as the table-based collation object obj; false otherwise.
  682. */
  683. public boolean equals(Object obj) {
  684. if (obj == null) return false;
  685. if (!super.equals(obj)) return false; // super does class check
  686. RuleBasedCollator other = (RuleBasedCollator) obj;
  687. // all other non-transient information is also contained in rules.
  688. return (getRules().equals(other.getRules()));
  689. }
  690. /**
  691. * Generates the hash code for the table-based collation object
  692. */
  693. public int hashCode() {
  694. return getRules().hashCode();
  695. }
  696. /**
  697. * Allows CollationElementIterator access to the tables object
  698. */
  699. RBCollationTables getTables() {
  700. return tables;
  701. }
  702. // ==============================================================
  703. // private
  704. // ==============================================================
  705. final static int CHARINDEX = 0x70000000; // need look up in .commit()
  706. final static int EXPANDCHARINDEX = 0x7E000000; // Expand index follows
  707. final static int CONTRACTCHARINDEX = 0x7F000000; // contract indexes follow
  708. final static int UNMAPPED = 0xFFFFFFFF;
  709. private final static int COLLATIONKEYOFFSET = 1;
  710. private RBCollationTables tables = null;
  711. // Internal objects that are cached across calls so that they don't have to
  712. // be created/destroyed on every call to compare() and getCollationKey()
  713. private StringBuffer primResult = null;
  714. private StringBuffer secResult = null;
  715. private StringBuffer terResult = null;
  716. private CollationElementIterator sourceCursor = null;
  717. private CollationElementIterator targetCursor = null;
  718. }