1 5 package org.h2.value; 6 7 import java.text.Collator ; 8 import java.util.Locale ; 9 10 import org.h2.util.StringUtils; 11 12 public class CompareMode { 13 public static final String OFF = "OFF"; 14 private String name = OFF; 15 private Collator collator; 16 17 public CompareMode(Collator collator, String name) { 18 this.collator = collator; 19 if(name != null) { 20 this.name = name; 21 } 22 } 23 24 public int compareString(String a, String b, boolean ignoreCase) { 25 if(collator == null) { 26 if(ignoreCase) { 27 return a.compareToIgnoreCase(b); 28 } 29 return a.compareTo(b); 30 } 31 if(ignoreCase) { 32 a = a.toUpperCase(); 34 b = b.toUpperCase(); 35 } 36 int comp = collator.compare(a, b); 37 return comp; 38 } 39 40 public static String getName(Locale l) { 41 Locale english = Locale.ENGLISH; 42 String name = l.getDisplayLanguage(english) + ' ' + l.getDisplayCountry(english) + ' ' + l.getVariant(); 43 name = StringUtils.toUpperEnglish(name.trim().replace(' ', '_')); 44 return name; 45 } 46 47 private static boolean compareLocaleNames(Locale locale, String name) { 48 return name.equalsIgnoreCase(locale.toString()) || name.equalsIgnoreCase(getName(locale)); 49 } 50 51 public static Collator getCollator(String name) { 52 Collator result = null; 53 if(name.length() == 2) { 54 Locale locale = new Locale (name.toLowerCase()); 55 if(compareLocaleNames(locale, name)) { 56 result = Collator.getInstance(locale); 57 } 58 } else if(name.length() == 5) { 59 int idx = name.indexOf('_'); 60 if(idx >= 0) { 61 String language = name.substring(0, idx).toLowerCase(); 62 String country = name.substring(idx + 1); 63 Locale locale = new Locale (language, country); 64 if(compareLocaleNames(locale, name)) { 65 result = Collator.getInstance(locale); 66 } 67 } 68 } 69 if(result == null) { 70 Locale [] locales = Collator.getAvailableLocales(); 71 for(int i=0; i<locales.length; i++) { 72 Locale locale = locales[i]; 73 if(compareLocaleNames(locale, name)) { 74 result = Collator.getInstance(locale); 75 break; 76 } 77 } 78 } 79 return result; 80 } 81 82 public String getName() { 83 return name; 84 } 85 86 } 87 | Popular Tags |