Debian Codegraph @

net/sf/saxon/expr/sort/UcaCollatorUsingJava.java

raw symbols SCIP
1 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2 // Copyright (c) 2018 Saxonica Limited.
3 // This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
4 // If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
5 // This Source Code Form is "Incompatible With Secondary Licenses", as defined by the Mozilla Public License, v. 2.0.
6 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
7
8 package net.sf.saxon.expr.sort;
9
10 import net.sf.saxon.lib.SubstringMatcher;
11 import net.sf.saxon.trans.XPathException;
12 import net.sf.saxon.type.StringConverter;
13 import net.sf.saxon.type.ValidationFailure;
14 import net.sf.saxon.value.AnyURIValue;
15
16 import java.net.URI;
17 import java.net.URISyntaxException;
18 import java.text.CollationElementIterator;
19 import java.text.CollationKey;
20 import java.text.Collator;
21 import java.text.RuleBasedCollator;
22 import java.util.*;
23
24
25 /**
26 * This class implements (an approximation to) the UCA Collation Algorithm
27 * relying solely on the built-in Java support (that is, without using the
28 * ICU library). This provides a fallback implementation for Saxon-HE, and
29 * it is used only when the collation URI does not include the option
30 * fallback=no.
31 */
32 public class UcaCollatorUsingJava implements SubstringMatcher {
33
34 private String uri;
35 private RuleBasedCollator uca;
36 private Strength strengthLevel;
37 private Properties properties;
38
39
40 private static String keywords[] = {"fallback", "lang", "version", "strength",
41 "alternate", "backwards", "normalization", "maxVariable",
42 "caseLevel", "caseFirst", "numeric", "reorder"}; //, "hiraganaQuaternary"
43 private static Set<String> keys = new HashSet<String>(Arrays.asList(keywords));
44
45 /**
46 * Create a collation from a given collation URI
47 * @param uri the collation URI, in the format defined in the W3C <i>Functions and Operators</i>
48 * specification
49 * @throws XPathException if the collation URI does not conform to the W3C rules, or if it
50 * requires features that Saxon-HE does not support
51 */
52
53 public UcaCollatorUsingJava(String uri) throws XPathException {
54 this.uri = uri;
55 uca = (RuleBasedCollator) RuleBasedCollator.getInstance();
56 setProps(parseProps(uri));
57 }
58
59 /**
60 * Get the underlying Java Collator object
61 * @return the underlying Java Collator
62 */
63
64 public RuleBasedCollator getRuleBasedCollator() {
65 return uca;
66 }
67
68 private void error(String field, String allowed) throws XPathException {
69 error("value of " + field + " must be " + allowed);
70 }
71
72 private void error(String field, String allowed, String requested) throws XPathException {
73 error("value of " + field + " must be " + allowed + ", requested was:" + requested);
74 }
75
76 private void error(String message) throws XPathException {
77 throw new XPathException("Error in UCA Collation URI " + uri + ": " + message, "FOCH0002");
78 }
79
80 // public String show() {
81 // if (uca != null) {
82 // return " UCAversion=" + uca.getUCAVersion()
83 // + " Version=" + uca.getVersion()
84 // + " lang=" + uca.get
85 // + " french=" + uca.isFrenchCollation()
86 // + " lowerFirst=" + uca.isLowerCaseFirst()
87 // + " upperFirst=" + uca.isUpperCaseFirst()
88 // + " strength=" + uca.getStrength();
89 // } else {
90 // return "No RuleBasedCollator initialised";
91 // }
92 // }
93
94 /**
95 * Factory method to create a CollationKey that can be used as a proxy for
96 * string comparisons under this collation
97 * @param source the string whose CollationKey is required
98 * @return a CollationKey with the property that two collation keys are equal (according
99 * to its {@link CollationKey#equals(Object)} method if their corresponding strings are
100 * considered to be equal under this collation
101 */
102 public CollationKey getJavaCollationKey(String source) {
103 return uca.getCollationKey(source);
104 }
105
106 /**
107 * Get a hash code used to compare two collations. (Probably not used.)
108 * @return a suitable hash code
109 */
110
111 @Override
112 public int hashCode() {
113 return uca.hashCode();
114 }
115
116 /**
117 * Set the properties for the UCA collation
118 *
119 * @param props the set of properties parsed from the UCA parameters
120 * @throws XPathException
121 */
122 private void setProps(Properties props) throws XPathException {
123 this.properties = props;
124 boolean fallbackError = false;
125 String fallback = props.getProperty("fallback");
126 if (fallback != null) {
127 switch (fallback) {
128 case "yes":
129 break;
130 case "no":
131 error("fallback=no is not supported in Saxon-HE");
132 break;
133 default:
134 error("fallback", "yes|no");
135 break;
136 }
137 }
138
139 String lang = props.getProperty("lang");
140 if (lang != null && !lang.isEmpty()) {
141 ValidationFailure vf = StringConverter.StringToLanguage.INSTANCE.validate(lang);
142 if (vf != null) {
143 error("lang", "a valid language code");
144 }
145 String language, country = "", variant = "";
146 String parts[] = lang.split("-");
147 language = parts[0];
148 if (parts.length > 1) {
149 country = parts[1];
150 }
151 if (parts.length > 2) {
152 variant = parts[2];
153 }
154 Locale loc = new Locale(language, country, variant);
155 uca = (RuleBasedCollator) Collator.getInstance(loc);
156 }
157
158 String strength = props.getProperty("strength");
159 if (strength != null) {
160 switch (strength) {
161 case "primary":
162 case "1":
163 setStrength(Collator.PRIMARY);
164 break;
165 case "secondary":
166 case "2":
167 setStrength(Collator.SECONDARY);
168 break;
169 case "tertiary":
170 case "3":
171 setStrength(Collator.TERTIARY);
172 break;
173 case "quaternary":
174 case "4":
175 setStrength(Collator.IDENTICAL); // fallback to nearest supported option
176
177 break;
178 case "identical":
179 case "5":
180 setStrength(Collator.IDENTICAL);
181 break;
182 }
183 }
184
185 String normalization = props.getProperty("normalization");
186 if (normalization != null) {
187 if (normalization.equals("yes")) {
188 uca.setDecomposition(java.text.Collator.CANONICAL_DECOMPOSITION);
189 } else if (normalization.equals("no")) {
190 uca.setDecomposition(java.text.Collator.NO_DECOMPOSITION);
191 }
192 }
193 }
194
195 /**
196 * Get the properties of the collation
197 * @return the properties of the collation
198 */
199
200 public Properties getProperties() {
201 return properties;
202 }
203
204 private Properties parseProps(String uri) throws XPathException {
205 URI uuri;
206 try {
207 uuri = new URI(uri);
208 } catch (URISyntaxException err) {
209 throw new XPathException(err);
210 }
211 ArrayList<String> unknownKeys = new ArrayList<String>();
212 Properties props = new Properties();
213 String query = AnyURIValue.decode(uuri.getRawQuery());
214 if (query != null && !query.isEmpty()) {
215 for (String s : query.split(";")) {
216 String tokens[] = s.split("=");
217 if (!keys.contains(tokens[0])) {
218 unknownKeys.add(tokens[0]);
219 }
220 props.setProperty(tokens[0], tokens[1]);
221 }
222 }
223 String fallback = props.getProperty("fallback");
224 if (fallback != null && fallback.equals("no") && !unknownKeys.isEmpty()) {
225 StringBuilder message = new StringBuilder(unknownKeys.size() > 1 ? "unknown parameters:" : "unknown parameter:");
226 for (String u : unknownKeys) {
227 message.append(u).append(" ");
228 }
229 error(message.toString());
230 }
231 return props;
232 }
233
234 /**
235 * Set the strength of the collation (primary, secondary, tertiary, etc)
236 * @param newStrength the strength
237 */
238
239 public void setStrength(int newStrength) {
240 uca.setStrength(newStrength);
241 }
242
243 /**
244 * Get the strength of the collation (primary, secondary, tertiary, etc)
245 * @return the strength
246 */
247
248 public int getStrength() {
249 return uca.getStrength();
250 }
251
252 /**
253 * Ask whether two strings are considered equal under this collation
254 * @param s1 the first string
255 * @param s2 the second string
256 * @return true if the strings are considered equal
257 */
258 @Override
259 public boolean comparesEqual(CharSequence s1, CharSequence s2) {
260 return uca.compare(s1, s2) == 0;
261 }
262
263 /**
264 * Get the collation URI corresponding to this collation
265 * @return the collation URI
266 */
267
268 @Override
269 public String getCollationURI() {
270 return uri;
271 }
272
273 /**
274 * Compare two strings for equality or ordering under the rules of this collation
275 * @param o1 the first string
276 * @param o2 the second string
277 * @return -1, 0, or +1 according to the relative ordering of the strings
278 */
279
280 @Override
281 public int compareStrings(CharSequence o1, CharSequence o2) {
282 return uca.compare(o1, o2);
283 }
284
285 /**
286 * Get a collation key that can be used as a proxy for strings being compared
287 * @param s the string whose collation key is required
288 * @return a collation key
289 */
290
291 @Override
292 public AtomicMatchKey getCollationKey(CharSequence s) {
293 CollationKey ck = uca.getCollationKey(s.toString());
294 return new CollationMatchKey(ck);
295 }
296
297 /**
298 * Test whether one string contains another, according to the rules
299 * of the XPath contains() function
300 *
301 * @param s1 the containing string
302 * @param s2 the contained string
303 * @return true iff s1 contains s2
304 */
305
306 public boolean contains(String s1, String s2) {
307 RuleBasedCollator collator = getRuleBasedCollator();
308 CollationElementIterator iter1 = collator.getCollationElementIterator(s1);
309 CollationElementIterator iter2 = collator.getCollationElementIterator(s2);
310 return collationContains(iter1, iter2, null, false);
311 }
312
313 /**
314 * Test whether one string ends with another, according to the rules
315 * of the XPath ends-with() function
316 *
317 * @param s1 the containing string
318 * @param s2 the contained string
319 * @return true iff s1 ends with s2
320 */
321
322 public boolean endsWith(String s1, String s2) {
323 RuleBasedCollator collator = getRuleBasedCollator();
324 CollationElementIterator iter1 = collator.getCollationElementIterator(s1);
325 CollationElementIterator iter2 = collator.getCollationElementIterator(s2);
326 return collationContains(iter1, iter2, null, true);
327 }
328
329 /**
330 * Test whether one string starts with another, according to the rules
331 * of the XPath starts-with() function
332 *
333 * @param s1 the containing string
334 * @param s2 the contained string
335 * @return true iff s1 starts with s2
336 */
337
338 public boolean startsWith(String s1, String s2) {
339 RuleBasedCollator collator = getRuleBasedCollator();
340 CollationElementIterator iter1 = collator.getCollationElementIterator(s1);
341 CollationElementIterator iter2 = collator.getCollationElementIterator(s2);
342 return collationStartsWith(iter1, iter2);
343 }
344
345 /**
346 * Return the part of a string after a given substring, according to the rules
347 * of the XPath substring-after() function
348 *
349 * @param s1 the containing string
350 * @param s2 the contained string
351 * @return the part of s1 that follows the first occurrence of s2
352 */
353
354 public String substringAfter(String s1, String s2) {
355 RuleBasedCollator collator = getRuleBasedCollator();
356 CollationElementIterator iter1 = collator.getCollationElementIterator(s1);
357 CollationElementIterator iter2 = collator.getCollationElementIterator(s2);
358 int[] ia = new int[2];
359 boolean ba = collationContains(iter1, iter2, ia, false);
360 if (ba) {
361 return s1.substring(ia[1]);
362 } else {
363 return "";
364 }
365 }
366
367 /**
368 * Return the part of a string before a given substring, according to the rules
369 * of the XPath substring-before() function
370 *
371 * @param s1 the containing string
372 * @param s2 the contained string
373 * @return the part of s1 that precedes the first occurrence of s2
374 */
375
376 public String substringBefore(String s1, String s2) {
377 RuleBasedCollator collator = getRuleBasedCollator();
378 CollationElementIterator iter1 = collator.getCollationElementIterator(s1);
379 CollationElementIterator iter2 = collator.getCollationElementIterator(s2);
380 int[] ib = new int[2];
381 boolean bb = collationContains(iter1, iter2, ib, false);
382 if (bb) {
383 return s1.substring(0, ib[0]);
384 } else {
385 return "";
386 }
387 }
388
389 /**
390 * Determine whether one string starts with another, under the terms of a given
391 * collating sequence.
392 *
393 * @param s0 iterator over the collation elements of the containing string
394 * @param s1 iterator over the collation elements of the contained string
395 * @return true if the first string starts with the second
396 */
397
398 private boolean collationStartsWith(CollationElementIterator s0,
399 CollationElementIterator s1) {
400 makeStrengthObject();
401 while (true) {
402 int e0, e1;
403 e1 = s1.next();
404 if (e1 == CollationElementIterator.NULLORDER) {
405 return true;
406 }
407 e0 = s0.next();
408 if (e0 == CollationElementIterator.NULLORDER) {
409 return false;
410 }
411 if (strengthLevel.compare(e0, e1) != 0) {
412 return false;
413 }
414 }
415 }
416
417 private String show(int ce) {
418 return "" + CollationElementIterator.primaryOrder(ce) + "/" +
419 CollationElementIterator.secondaryOrder(ce) + "/" +
420 CollationElementIterator.tertiaryOrder(ce);
421 }
422
423 private void makeStrengthObject() {
424 if (strengthLevel == null) {
425 switch (getStrength()) {
426 case com.ibm.icu.text.Collator.PRIMARY:
427 strengthLevel = new Primary();
428 break;
429 case com.ibm.icu.text.Collator.SECONDARY:
430 strengthLevel = new Secondary();
431 break;
432 case com.ibm.icu.text.Collator.TERTIARY:
433 strengthLevel = new Tertiary();
434 break;
435 default:
436 strengthLevel = new Identical();
437 break;
438 }
439 }
440 }
441
442 /**
443 * Determine whether one string contains another, under the terms of a given
444 * collating sequence. If matchAtEnd=true, the match must be at the end of the first
445 * string.
446 *
447 * @param s0 iterator over the collation elements of the containing string
448 * @param s1 iterator over the collation elements of the contained string
449 * @param offsets may be null, but if it is supplied, it must be an array of two
450 * integers which, if the function returns true, will contain the start position of the
451 * first matching substring, and the offset of the first character after the first
452 * matching substring. This is not available for matchAtEnd=true
453 * @param matchAtEnd true if the match is required to be at the end of the string
454 * @return true if the first string contains the second
455 */
456
457 private boolean collationContains(CollationElementIterator s0,
458 CollationElementIterator s1,
459 /*@Nullable*/ int[] offsets,
460 boolean matchAtEnd) {
461 makeStrengthObject();
462 int e0, e1;
463 e1 = s1.next();
464 if (e1 == CollationElementIterator.NULLORDER) {
465 return true;
466 }
467 e0 = CollationElementIterator.NULLORDER;
468 while (true) {
469 // scan the first string to find a matching character
470 while (strengthLevel.compare(e0, e1) != 0) {
471 e0 = s0.next();
472 if (e0 == CollationElementIterator.NULLORDER) {
473 // hit the end, no match
474 return false;
475 }
476 }
477 // matched first character, note the position of the possible match
478 int start = s0.getOffset();
479 if (collationStartsWith(s0, s1)) {
480 if (matchAtEnd) {
481 e0 = s0.next();
482 if (e0 == CollationElementIterator.NULLORDER) {
483 // the match is at the end
484 return true;
485 }
486 // else ignore this match and keep looking
487 } else {
488 if (offsets != null) {
489 offsets[0] = start - 1;
490 offsets[1] = s0.getOffset();
491 }
492 return true;
493 }
494 }
495 // reset the position and try again
496 s0.setOffset(start);
497
498 // workaround for a difference between JDK 1.4.0 and JDK 1.4.1
499 if (s0.getOffset() != start) {
500 // JDK 1.4.0 takes this path
501 s0.next();
502 }
503 s1.reset();
504 e0 = -1;
505 e1 = s1.next();
506 // loop round to try again
507 }
508 }
509
510
511 private interface Strength {
512 int compare(int ce1, int ce2);
513 }
514
515 private class Primary implements Strength {
516 @Override
517 public int compare(int ce1, int ce2) {
518 return Integer.compare(CollationElementIterator.primaryOrder(ce1), CollationElementIterator.primaryOrder(ce2));
519 }
520
521 }
522
523 private class Secondary implements Strength {
524 @Override
525 public int compare(int ce1, int ce2) {
526 int c1 = Integer.compare(CollationElementIterator.primaryOrder(ce1), CollationElementIterator.primaryOrder(ce2));
527 if (c1 == 0) {
528 return Integer.compare((int) CollationElementIterator.secondaryOrder(ce1), (int) CollationElementIterator.secondaryOrder(ce2));
529 } else {
530 return c1;
531 }
532 }
533
534 }
535
536 private class Tertiary implements Strength {
537 @Override
538 public int compare(int ce1, int ce2) {
539 int c1 = Integer.compare(CollationElementIterator.primaryOrder(ce1), CollationElementIterator.primaryOrder(ce2));
540 if (c1 == 0) {
541 int c2 = Integer.compare((int) CollationElementIterator.secondaryOrder(ce1), (int) CollationElementIterator.secondaryOrder(ce2));
542 if (c2 == 0) {
543 return Integer.compare((int) CollationElementIterator.tertiaryOrder(ce1), (int) CollationElementIterator.tertiaryOrder(ce2));
544 } else {
545 return c2;
546 }
547 } else {
548 return c1;
549 }
550 }
551
552 }
553
554 private class Identical implements Strength {
555 @Override
556 public int compare(int ce1, int ce2) {
557 return Integer.compare(ce1, ce2);
558 }
559
560 }
561
562
563 }