File D:\maven-qcr-plugin-testsunitaires\qcr4java\h2-1.3.170-sources\target\site\qc\lecode\value\CompareModeIcu4J.java.html

1 /*
2 * Copyright 2004-2011 H2 Group. Multiple-Licensed under the H2 License,
3 * Version 1.0, and under the Eclipse Public License, Version 1.0
4 * (http://h2database.com/html/license.html).
5 * Initial Developer: H2 Group
6 */
7 package org.h2.value;
8
9 import java.lang.reflect.Method;
10 import java.util.Comparator;
11 import java.util.Locale;
12 import org.h2.message.DbException;
13 import org.h2.util.StringUtils;
14 import org.h2.util.Utils;
15
16 /**
17 * An implementation of CompareMode that uses the ICU4J Collator.
18 */
19 public class CompareModeIcu4J extends CompareMode {
20
21 private final Comparator<String> collator;
22
23 protected CompareModeIcu4J(String name, int strength) {
24 super(name, strength);
25 collator = getIcu4jCollator(name, strength);
26 }
27
28 public int compareString(String a, String b, boolean ignoreCase) {
29 if (ignoreCase) {
30 a = a.toUpperCase();
31 b = b.toUpperCase();
32 }
33 return collator.compare(a, b);
34 }
35
36 public boolean equalsChars(String a, int ai, String b, int bi, boolean ignoreCase) {
37 return compareString(a.substring(ai, ai + 1), b.substring(bi, bi + 1), ignoreCase) == 0;
38 }
39
40 @SuppressWarnings("unchecked")
41 private static Comparator<String> getIcu4jCollator(String name, int strength) {
42 try {
43 Comparator<String> result = null;
44 Class<?> collatorClass = Utils.loadUserClass("com.ibm.icu.text.Collator");
45 Method getInstanceMethod = collatorClass.getMethod("getInstance", Locale.class);
46 if (name.length() == 2) {
47 Locale locale = new Locale(StringUtils.toLowerEnglish(name), "");
48 if (compareLocaleNames(locale, name)) {
49 result = (Comparator<String>) getInstanceMethod.invoke(null, locale);
50 }
51 } else if (name.length() == 5) {
52 // LL_CC (language_country)
53 int idx = name.indexOf('_');
54 if (idx >= 0) {
55 String language = StringUtils.toLowerEnglish(name.substring(0, idx));
56 String country = name.substring(idx + 1);
57 Locale locale = new Locale(language, country);
58 if (compareLocaleNames(locale, name)) {
59 result = (Comparator<String>) getInstanceMethod.invoke(null, locale);
60 }
61 }
62 }
63 if (result == null) {
64 for (Locale locale : (Locale[]) collatorClass.getMethod("getAvailableLocales").invoke(null)) {
65 if (compareLocaleNames(locale, name)) {
66 result = (Comparator<String>) getInstanceMethod.invoke(null, locale);
67 break;
68 }
69 }
70 }
71 if (result == null) {
72 throw DbException.getInvalidValueException("collator", name);
73 }
74 collatorClass.getMethod("setStrength", int.class).invoke(result, strength);
75 return result;
76 } catch (Exception e) {
77 throw DbException.convert(e);
78 }
79 }
80
81 }
82