• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2014 The Android Open Source Project
3  * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This code is free software; you can redistribute it and/or modify it
7  * under the terms of the GNU General Public License version 2 only, as
8  * published by the Free Software Foundation.  Oracle designates this
9  * particular file as subject to the "Classpath" exception as provided
10  * by Oracle in the LICENSE file that accompanied this code.
11  *
12  * This code is distributed in the hope that it will be useful, but WITHOUT
13  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
15  * version 2 for more details (a copy is included in the LICENSE file that
16  * accompanied this code).
17  *
18  * You should have received a copy of the GNU General Public License version
19  * 2 along with this work; if not, write to the Free Software Foundation,
20  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
21  *
22  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
23  * or visit www.oracle.com if you need additional information or have any
24  * questions.
25  */
26 
27 /*
28  * (C) Copyright Taligent, Inc. 1996, 1997 - All Rights Reserved
29  * (C) Copyright IBM Corp. 1996-1998 - All Rights Reserved
30  *
31  *   The original version of this source code and documentation is copyrighted
32  * and owned by Taligent, Inc., a wholly-owned subsidiary of IBM. These
33  * materials are provided under terms of a License Agreement between Taligent
34  * and Sun. This technology is protected by multiple US and International
35  * patents. This notice and attribution to Taligent may not be removed.
36  *   Taligent is a registered trademark of Taligent, Inc.
37  *
38  */
39 
40 package java.text;
41 
42 import libcore.icu.CollationKeyICU;
43 
44 /**
45  * The <code>RuleBasedCollator</code> class is a concrete subclass of
46  * <code>Collator</code> that provides a simple, data-driven, table
47  * collator.  With this class you can create a customized table-based
48  * <code>Collator</code>.  <code>RuleBasedCollator</code> maps
49  * characters to sort keys.
50  *
51  * <p>
52  * <code>RuleBasedCollator</code> has the following restrictions
53  * for efficiency (other subclasses may be used for more complex languages) :
54  * <ol>
55  * <li>If a special collation rule controlled by a &lt;modifier&gt; is
56       specified it applies to the whole collator object.
57  * <li>All non-mentioned characters are at the end of the
58  *     collation order.
59  * </ol>
60  *
61  * <p>
62  * The collation table is composed of a list of collation rules, where each
63  * rule is of one of three forms:
64  * <pre>
65  *    &lt;modifier&gt;
66  *    &lt;relation&gt; &lt;text-argument&gt;
67  *    &lt;reset&gt; &lt;text-argument&gt;
68  * </pre>
69  * The definitions of the rule elements is as follows:
70  * <UL>
71  *    <LI><strong>Text-Argument</strong>: A text-argument is any sequence of
72  *        characters, excluding special characters (that is, common
73  *        whitespace characters [0009-000D, 0020] and rule syntax characters
74  *        [0021-002F, 003A-0040, 005B-0060, 007B-007E]). If those
75  *        characters are desired, you can put them in single quotes
76  *        (e.g. ampersand =&gt; '&amp;'). Note that unquoted white space characters
77  *        are ignored; e.g. <code>b c</code> is treated as <code>bc</code>.
78  *    <LI><strong>Modifier</strong>: There are currently two modifiers that
79  *        turn on special collation rules.
80  *        <UL>
81  *            <LI>'@' : Turns on backwards sorting of accents (secondary
82  *                      differences), as in French.
83  *            <LI>'!' : Turns on Thai/Lao vowel-consonant swapping.  If this
84  *                      rule is in force when a Thai vowel of the range
85  *                      &#92;U0E40-&#92;U0E44 precedes a Thai consonant of the range
86  *                      &#92;U0E01-&#92;U0E2E OR a Lao vowel of the range &#92;U0EC0-&#92;U0EC4
87  *                      precedes a Lao consonant of the range &#92;U0E81-&#92;U0EAE then
88  *                      the vowel is placed after the consonant for collation
89  *                      purposes.
90  *        </UL>
91  *        <p>'@' : Indicates that accents are sorted backwards, as in French.
92  *    <LI><strong>Relation</strong>: The relations are the following:
93  *        <UL>
94  *            <LI>'&lt;' : Greater, as a letter difference (primary)
95  *            <LI>';' : Greater, as an accent difference (secondary)
96  *            <LI>',' : Greater, as a case difference (tertiary)
97  *            <LI>'=' : Equal
98  *        </UL>
99  *    <LI><strong>Reset</strong>: There is a single reset
100  *        which is used primarily for contractions and expansions, but which
101  *        can also be used to add a modification at the end of a set of rules.
102  *        <p>'&amp;' : Indicates that the next rule follows the position to where
103  *            the reset text-argument would be sorted.
104  * </UL>
105  *
106  * <p>
107  * This sounds more complicated than it is in practice. For example, the
108  * following are equivalent ways of expressing the same thing:
109  * <blockquote>
110  * <pre>
111  * a &lt; b &lt; c
112  * a &lt; b &amp; b &lt; c
113  * a &lt; c &amp; a &lt; b
114  * </pre>
115  * </blockquote>
116  * Notice that the order is important, as the subsequent item goes immediately
117  * after the text-argument. The following are not equivalent:
118  * <blockquote>
119  * <pre>
120  * a &lt; b &amp; a &lt; c
121  * a &lt; c &amp; a &lt; b
122  * </pre>
123  * </blockquote>
124  * Either the text-argument must already be present in the sequence, or some
125  * initial substring of the text-argument must be present. (e.g. "a &lt; b &amp; ae &lt;
126  * e" is valid since "a" is present in the sequence before "ae" is reset). In
127  * this latter case, "ae" is not entered and treated as a single character;
128  * instead, "e" is sorted as if it were expanded to two characters: "a"
129  * followed by an "e". This difference appears in natural languages: in
130  * traditional Spanish "ch" is treated as though it contracts to a single
131  * character (expressed as "c &lt; ch &lt; d"), while in traditional German
132  * a-umlaut is treated as though it expanded to two characters
133  * (expressed as "a,A &lt; b,B ... &amp;ae;&#92;u00e3&amp;AE;&#92;u00c3").
134  * [&#92;u00e3 and &#92;u00c3 are, of course, the escape sequences for a-umlaut.]
135  * <p>
136  * <strong>Ignorable Characters</strong>
137  * <p>
138  * For ignorable characters, the first rule must start with a relation (the
139  * examples we have used above are really fragments; "a &lt; b" really should be
140  * "&lt; a &lt; b"). If, however, the first relation is not "&lt;", then all the all
141  * text-arguments up to the first "&lt;" are ignorable. For example, ", - &lt; a &lt; b"
142  * makes "-" an ignorable character, as we saw earlier in the word
143  * "black-birds". In the samples for different languages, you see that most
144  * accents are ignorable.
145  *
146  * <p><strong>Normalization and Accents</strong>
147  * <p>
148  * <code>RuleBasedCollator</code> automatically processes its rule table to
149  * include both pre-composed and combining-character versions of
150  * accented characters.  Even if the provided rule string contains only
151  * base characters and separate combining accent characters, the pre-composed
152  * accented characters matching all canonical combinations of characters from
153  * the rule string will be entered in the table.
154  * <p>
155  * This allows you to use a RuleBasedCollator to compare accented strings
156  * even when the collator is set to NO_DECOMPOSITION.  There are two caveats,
157  * however.  First, if the strings to be collated contain combining
158  * sequences that may not be in canonical order, you should set the collator to
159  * CANONICAL_DECOMPOSITION or FULL_DECOMPOSITION to enable sorting of
160  * combining sequences.  Second, if the strings contain characters with
161  * compatibility decompositions (such as full-width and half-width forms),
162  * you must use FULL_DECOMPOSITION, since the rule tables only include
163  * canonical mappings.
164  *
165  * <p><strong>Errors</strong>
166  * <p>
167  * The following are errors:
168  * <UL>
169  *     <LI>A text-argument contains unquoted punctuation symbols
170  *        (e.g. "a &lt; b-c &lt; d").
171  *     <LI>A relation or reset character not followed by a text-argument
172  *        (e.g. "a &lt; ,b").
173  *     <LI>A reset where the text-argument (or an initial substring of the
174  *         text-argument) is not already in the sequence.
175  *         (e.g. "a &lt; b &amp; e &lt; f")
176  * </UL>
177  * If you produce one of these errors, a <code>RuleBasedCollator</code> throws
178  * a <code>ParseException</code>.
179  *
180  * <p><strong>Examples</strong>
181  * <p>Simple:     "&lt; a &lt; b &lt; c &lt; d"
182  * <p>Norwegian:  "&lt; a, A &lt; b, B &lt; c, C &lt; d, D &lt; e, E &lt; f, F
183  *                 &lt; g, G &lt; h, H &lt; i, I &lt; j, J &lt; k, K &lt; l, L
184  *                 &lt; m, M &lt; n, N &lt; o, O &lt; p, P &lt; q, Q &lt; r, R
185  *                 &lt; s, S &lt; t, T &lt; u, U &lt; v, V &lt; w, W &lt; x, X
186  *                 &lt; y, Y &lt; z, Z
187  *                 &lt; &#92;u00E6, &#92;u00C6
188  *                 &lt; &#92;u00F8, &#92;u00D8
189  *                 &lt; &#92;u00E5 = a&#92;u030A, &#92;u00C5 = A&#92;u030A;
190  *                      aa, AA"
191  *
192  * <p>
193  * To create a <code>RuleBasedCollator</code> object with specialized
194  * rules tailored to your needs, you construct the <code>RuleBasedCollator</code>
195  * with the rules contained in a <code>String</code> object. For example:
196  * <blockquote>
197  * <pre>
198  * String simple = "&lt; a&lt; b&lt; c&lt; d";
199  * RuleBasedCollator mySimple = new RuleBasedCollator(simple);
200  * </pre>
201  * </blockquote>
202  * Or:
203  * <blockquote>
204  * <pre>
205  * String Norwegian = "&lt; a, A &lt; b, B &lt; c, C &lt; d, D &lt; e, E &lt; f, F &lt; g, G &lt; h, H &lt; i, I" +
206  *                    "&lt; j, J &lt; k, K &lt; l, L &lt; m, M &lt; n, N &lt; o, O &lt; p, P &lt; q, Q &lt; r, R" +
207  *                    "&lt; s, S &lt; t, T &lt; u, U &lt; v, V &lt; w, W &lt; x, X &lt; y, Y &lt; z, Z" +
208  *                    "&lt; &#92;u00E6, &#92;u00C6" +     // Latin letter ae &amp; AE
209  *                    "&lt; &#92;u00F8, &#92;u00D8" +     // Latin letter o &amp; O with stroke
210  *                    "&lt; &#92;u00E5 = a&#92;u030A," +  // Latin letter a with ring above
211  *                    "  &#92;u00C5 = A&#92;u030A;" +  // Latin letter A with ring above
212  *                    "  aa, AA";
213  * RuleBasedCollator myNorwegian = new RuleBasedCollator(Norwegian);
214  * </pre>
215  * </blockquote>
216  *
217  * <p>
218  * A new collation rules string can be created by concatenating rules
219  * strings. For example, the rules returned by {@link #getRules()} could
220  * be concatenated to combine multiple <code>RuleBasedCollator</code>s.
221  *
222  * <p>
223  * The following example demonstrates how to change the order of
224  * non-spacing accents,
225  * <blockquote>
226  * <pre>
227  * // old rule
228  * String oldRules = "=&#92;u0301;&#92;u0300;&#92;u0302;&#92;u0308"    // main accents
229  *                 + ";&#92;u0327;&#92;u0303;&#92;u0304;&#92;u0305"    // main accents
230  *                 + ";&#92;u0306;&#92;u0307;&#92;u0309;&#92;u030A"    // main accents
231  *                 + ";&#92;u030B;&#92;u030C;&#92;u030D;&#92;u030E"    // main accents
232  *                 + ";&#92;u030F;&#92;u0310;&#92;u0311;&#92;u0312"    // main accents
233  *                 + "&lt; a , A ; ae, AE ; &#92;u00e6 , &#92;u00c6"
234  *                 + "&lt; b , B &lt; c, C &lt; e, E &amp; C &lt; d, D";
235  * // change the order of accent characters
236  * String addOn = "&amp; &#92;u0300 ; &#92;u0308 ; &#92;u0302";
237  * RuleBasedCollator myCollator = new RuleBasedCollator(oldRules + addOn);
238  * </pre>
239  * </blockquote>
240  *
241  * @see        Collator
242  * @see        CollationElementIterator
243  * @author     Helena Shih, Laura Werner, Richard Gillam
244  */
245 public class RuleBasedCollator extends Collator{
246     // Android-added: protected constructor taking an ICU RuleBasedCollator.
RuleBasedCollator(android.icu.text.RuleBasedCollator wrapper)247     RuleBasedCollator(android.icu.text.RuleBasedCollator wrapper) {
248         super(wrapper);
249     }
250 
251     // IMPLEMENTATION NOTES:  The implementation of the collation algorithm is
252     // divided across three classes: RuleBasedCollator, RBCollationTables, and
253     // CollationElementIterator.  RuleBasedCollator contains the collator's
254     // transient state and includes the code that uses the other classes to
255     // implement comparison and sort-key building.  RuleBasedCollator also
256     // contains the logic to handle French secondary accent sorting.
257     // A RuleBasedCollator has two CollationElementIterators.  State doesn't
258     // need to be preserved in these objects between calls to compare() or
259     // getCollationKey(), but the objects persist anyway to avoid wasting extra
260     // creation time.  compare() and getCollationKey() are synchronized to ensure
261     // thread safety with this scheme.  The CollationElementIterator is responsible
262     // for generating collation elements from strings and returning one element at
263     // a time (sometimes there's a one-to-many or many-to-one mapping between
264     // characters and collation elements-- this class handles that).
265     // CollationElementIterator depends on RBCollationTables, which contains the
266     // collator's static state.  RBCollationTables contains the actual data
267     // tables specifying the collation order of characters for a particular locale
268     // or use.  It also contains the base logic that CollationElementIterator
269     // uses to map from characters to collation elements.  A single RBCollationTables
270     // object is shared among all RuleBasedCollators for the same locale, and
271     // thus by all the CollationElementIterators they create.
272 
273     /**
274      * RuleBasedCollator constructor.  This takes the table rules and builds
275      * a collation table out of them.  Please see RuleBasedCollator class
276      * description for more details on the collation rule syntax.
277      * @see java.util.Locale
278      * @param rules the collation rules to build the collation table from.
279      * @exception ParseException A format exception
280      * will be thrown if the build process of the rules fails. For
281      * example, build rule "a &lt; ? &lt; d" will cause the constructor to
282      * throw the ParseException because the '?' is not quoted.
283      */
RuleBasedCollator(String rules)284     public RuleBasedCollator(String rules) throws ParseException {
285         // BEGIN Android-changed: Switched to ICU.
286         if (rules == null) {
287             throw new NullPointerException("rules == null");
288         }
289         try {
290             icuColl = new android.icu.text.RuleBasedCollator(rules);
291         } catch (Exception e) {
292             if (e instanceof ParseException) {
293                 throw (ParseException) e;
294             }
295             /*
296              * -1 means it's not a ParseException. Maybe IOException thrown when
297              * an error occurred while reading internal data.
298              */
299             throw new ParseException(e.getMessage(), -1);
300         }
301         // END Android-changed: Switched to ICU.
302     }
303 
304     // Android-removed: (String rules, int decomp) constructor and copy constructor.
305 
306     // Android-changed: document that getRules() won't return rules in common case.
307     /**
308      * Gets the table-based rules for the collation object.
309      *
310      * <p>On Android, the returned string will be empty unless this instance was
311      * constructed using {@link #RuleBasedCollator(String)}.
312      *
313      * @return returns the collation rules that the table collation object
314      * was created from.
315      */
getRules()316     public String getRules()
317     {
318         // Android-changed: Switched to ICU.
319         return collAsICU().getRules();
320     }
321 
322     /**
323      * Returns a CollationElementIterator for the given String.
324      *
325      * @param source the string to be collated
326      * @return a {@code CollationElementIterator} object
327      * @see java.text.CollationElementIterator
328      */
getCollationElementIterator(String source)329     public CollationElementIterator getCollationElementIterator(String source) {
330         // Android-changed: Switch to ICU and check for null value.
331         if (source == null) {
332             throw new NullPointerException("source == null");
333         }
334         return new CollationElementIterator(collAsICU().getCollationElementIterator(source));
335     }
336 
337     /**
338      * Returns a CollationElementIterator for the given CharacterIterator.
339      *
340      * @param source the character iterator to be collated
341      * @return a {@code CollationElementIterator} object
342      * @see java.text.CollationElementIterator
343      * @since 1.2
344      */
getCollationElementIterator( CharacterIterator source)345     public CollationElementIterator getCollationElementIterator(
346                                                 CharacterIterator source) {
347         // Android-changed: Switch to ICU and check for null value.
348        if (source == null) {
349             throw new NullPointerException("source == null");
350         }
351         return new CollationElementIterator(collAsICU().getCollationElementIterator(source));
352     }
353 
354     /**
355      * Compares the character data stored in two different strings based on the
356      * collation rules.  Returns information about whether a string is less
357      * than, greater than or equal to another string in a language.
358      * This can be overriden in a subclass.
359      *
360      * @exception NullPointerException if <code>source</code> or <code>target</code> is null.
361      */
compare(String source, String target)362     public synchronized int compare(String source, String target)
363     {
364         if (source == null || target == null) {
365             throw new NullPointerException();
366         }
367         // Android-changed: Switched to ICU.
368         return icuColl.compare(source, target);
369     }
370 
371     /**
372      * Transforms the string into a series of characters that can be compared
373      * with CollationKey.compareTo. This overrides java.text.Collator.getCollationKey.
374      * It can be overriden in a subclass.
375      */
getCollationKey(String source)376     public synchronized CollationKey getCollationKey(String source)
377     {
378         // Android-changed: Switched to ICU.
379         if (source == null) {
380             return null;
381         }
382         return new CollationKeyICU(source, icuColl.getCollationKey(source));
383     }
384 
385     /**
386      * Standard override; no change in semantics.
387      */
clone()388     public Object clone() {
389         // Android-changed: remove special case for cloning.
390         return super.clone();
391     }
392 
393     /**
394      * Compares the equality of two collation objects.
395      * @param obj the table-based collation object to be compared with this.
396      * @return true if the current table-based collation object is the same
397      * as the table-based collation object obj; false otherwise.
398      */
equals(Object obj)399     public boolean equals(Object obj) {
400         if (obj == null) return false;
401         // Android-changed: delegate to super class, as that already compares icuColl.
402         return super.equals(obj);
403     }
404 
405     /**
406      * Generates the hash code for the table-based collation object
407      */
hashCode()408     public int hashCode() {
409         // Android-changed: Switched to ICU.
410         return icuColl.hashCode();
411     }
412 
413     // Android-added: collAsIcu helper method.
collAsICU()414     private android.icu.text.RuleBasedCollator collAsICU() {
415         return (android.icu.text.RuleBasedCollator) icuColl;
416     }
417 
418     // Android-removed: private constants and fields.
419 }
420