Locale.java 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030
  1. /* Locale.java -- i18n locales
  2. Copyright (C) 1998, 1999, 2001, 2002, 2005, 2006 Free Software Foundation, Inc.
  3. This file is part of GNU Classpath.
  4. GNU Classpath is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2, or (at your option)
  7. any later version.
  8. GNU Classpath is distributed in the hope that it will be useful, but
  9. WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with GNU Classpath; see the file COPYING. If not, write to the
  14. Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
  15. 02110-1301 USA.
  16. Linking this library statically or dynamically with other modules is
  17. making a combined work based on this library. Thus, the terms and
  18. conditions of the GNU General Public License cover the whole
  19. combination.
  20. As a special exception, the copyright holders of this library give you
  21. permission to link this library with independent modules to produce an
  22. executable, regardless of the license terms of these independent
  23. modules, and to copy and distribute the resulting executable under
  24. terms of your choice, provided that you also meet, for each linked
  25. independent module, the terms and conditions of the license of that
  26. module. An independent module is a module which is not derived from
  27. or based on this library. If you modify this library, you may extend
  28. this exception to your version of the library, but you are not
  29. obligated to do so. If you do not wish to do so, delete this
  30. exception statement from your version. */
  31. package java.util;
  32. import gnu.classpath.SystemProperties;
  33. import gnu.java.lang.CPStringBuilder;
  34. import gnu.java.locale.LocaleHelper;
  35. import java.io.IOException;
  36. import java.io.ObjectInputStream;
  37. import java.io.ObjectOutputStream;
  38. import java.io.Serializable;
  39. import java.util.spi.LocaleNameProvider;
  40. /**
  41. * Locales represent a specific country and culture. Classes which can be
  42. * passed a Locale object tailor their information for a given locale. For
  43. * instance, currency number formatting is handled differently for the USA
  44. * and France.
  45. *
  46. * <p>Locales are made up of a language code, a country code, and an optional
  47. * set of variant strings. Language codes are represented by
  48. * <a href="http://www.ics.uci.edu/pub/ietf/http/related/iso639.txt">
  49. * ISO 639:1988</a> w/ additions from ISO 639/RA Newsletter No. 1/1989
  50. * and a decision of the Advisory Committee of ISO/TC39 on August 8, 1997.
  51. *
  52. * <p>Country codes are represented by
  53. * <a href="http://www.chemie.fu-berlin.de/diverse/doc/ISO_3166.html">
  54. * ISO 3166</a>. Variant strings are vendor and browser specific. Standard
  55. * variant strings include "POSIX" for POSIX, "WIN" for MS-Windows, and
  56. * "MAC" for Macintosh. When there is more than one variant string, they must
  57. * be separated by an underscore (U+005F).
  58. *
  59. * <p>The default locale is determined by the values of the system properties
  60. * user.language, user.country (or user.region), and user.variant, defaulting
  61. * to "en_US". Note that the locale does NOT contain the conversion and
  62. * formatting capabilities (for that, use ResourceBundle and java.text).
  63. * Rather, it is an immutable tag object for identifying a given locale, which
  64. * is referenced by these other classes when they must make locale-dependent
  65. * decisions.
  66. *
  67. * @see ResourceBundle
  68. * @see java.text.Format
  69. * @see java.text.NumberFormat
  70. * @see java.text.Collator
  71. * @author Jochen Hoenicke
  72. * @author Paul Fisher
  73. * @author Eric Blake (ebb9@email.byu.edu)
  74. * @author Andrew John Hughes (gnu_andrew@member.fsf.org)
  75. * @since 1.1
  76. * @status updated to 1.4
  77. */
  78. public final class Locale implements Serializable, Cloneable
  79. {
  80. /** Locale which represents the English language. */
  81. public static final Locale ENGLISH = getLocale("en");
  82. /** Locale which represents the French language. */
  83. public static final Locale FRENCH = getLocale("fr");
  84. /** Locale which represents the German language. */
  85. public static final Locale GERMAN = getLocale("de");
  86. /** Locale which represents the Italian language. */
  87. public static final Locale ITALIAN = getLocale("it");
  88. /** Locale which represents the Japanese language. */
  89. public static final Locale JAPANESE = getLocale("ja");
  90. /** Locale which represents the Korean language. */
  91. public static final Locale KOREAN = getLocale("ko");
  92. /** Locale which represents the Chinese language. */
  93. public static final Locale CHINESE = getLocale("zh");
  94. /** Locale which represents the Chinese language as used in China. */
  95. public static final Locale SIMPLIFIED_CHINESE = getLocale("zh", "CN");
  96. /**
  97. * Locale which represents the Chinese language as used in Taiwan.
  98. * Same as TAIWAN Locale.
  99. */
  100. public static final Locale TRADITIONAL_CHINESE = getLocale("zh", "TW");
  101. /** Locale which represents France. */
  102. public static final Locale FRANCE = getLocale("fr", "FR");
  103. /** Locale which represents Germany. */
  104. public static final Locale GERMANY = getLocale("de", "DE");
  105. /** Locale which represents Italy. */
  106. public static final Locale ITALY = getLocale("it", "IT");
  107. /** Locale which represents Japan. */
  108. public static final Locale JAPAN = getLocale("ja", "JP");
  109. /** Locale which represents Korea. */
  110. public static final Locale KOREA = getLocale("ko", "KR");
  111. /**
  112. * Locale which represents China.
  113. * Same as SIMPLIFIED_CHINESE Locale.
  114. */
  115. public static final Locale CHINA = SIMPLIFIED_CHINESE;
  116. /**
  117. * Locale which represents the People's Republic of China.
  118. * Same as CHINA Locale.
  119. */
  120. public static final Locale PRC = CHINA;
  121. /**
  122. * Locale which represents Taiwan.
  123. * Same as TRADITIONAL_CHINESE Locale.
  124. */
  125. public static final Locale TAIWAN = TRADITIONAL_CHINESE;
  126. /** Locale which represents the United Kingdom. */
  127. public static final Locale UK = getLocale("en", "GB");
  128. /** Locale which represents the United States. */
  129. public static final Locale US = getLocale("en", "US");
  130. /** Locale which represents the English speaking portion of Canada. */
  131. public static final Locale CANADA = getLocale("en", "CA");
  132. /** Locale which represents the French speaking portion of Canada. */
  133. public static final Locale CANADA_FRENCH = getLocale("fr", "CA");
  134. /** The root locale, used as the base case in lookups by
  135. * locale-sensitive operations.
  136. */
  137. public static final Locale ROOT = new Locale("","","");
  138. /**
  139. * Compatible with JDK 1.1+.
  140. */
  141. private static final long serialVersionUID = 9149081749638150636L;
  142. /**
  143. * The language code, as returned by getLanguage().
  144. *
  145. * @serial the languange, possibly ""
  146. */
  147. private final String language;
  148. /**
  149. * The country code, as returned by getCountry().
  150. *
  151. * @serial the country, possibly ""
  152. */
  153. private final String country;
  154. /**
  155. * The variant code, as returned by getVariant().
  156. *
  157. * @serial the variant, possibly ""
  158. */
  159. private final String variant;
  160. /**
  161. * This is the cached hashcode. When writing to stream, we write -1.
  162. *
  163. * @serial should be -1 in serial streams
  164. */
  165. private int hashcode;
  166. /**
  167. * Array storing all available locales.
  168. */
  169. private static transient Locale[] availableLocales;
  170. /**
  171. * Locale cache. Only created locale objects are stored.
  172. * Contains all supported locales when getAvailableLocales()
  173. * got called.
  174. */
  175. private static transient HashMap localeMap;
  176. /**
  177. * The default locale. Except for during bootstrapping, this should never be
  178. * null. Note the logic in the main constructor, to detect when
  179. * bootstrapping has completed.
  180. */
  181. private static Locale defaultLocale;
  182. static {
  183. String language = SystemProperties.getProperty("user.language", "en");
  184. String country = SystemProperties.getProperty("user.country", "US");
  185. String region = SystemProperties.getProperty("user.region", null);
  186. String variant = SystemProperties.getProperty("user.variant", "");
  187. defaultLocale = getLocale(language,
  188. (region != null) ? region : country,
  189. variant);
  190. }
  191. /**
  192. * Array storing all the available two-letter ISO639 languages.
  193. */
  194. private static transient String[] languageCache;
  195. /**
  196. * Array storing all the available two-letter ISO3166 country codes.
  197. */
  198. private static transient String[] countryCache;
  199. /**
  200. * Retrieves the locale with the specified language from the cache.
  201. *
  202. * @param language the language of the locale to retrieve.
  203. * @return the locale.
  204. */
  205. private static Locale getLocale(String language)
  206. {
  207. return getLocale(language, "", "");
  208. }
  209. /**
  210. * Retrieves the locale with the specified language and country
  211. * from the cache.
  212. *
  213. * @param language the language of the locale to retrieve.
  214. * @param country the country of the locale to retrieve.
  215. * @return the locale.
  216. */
  217. private static Locale getLocale(String language, String country)
  218. {
  219. return getLocale(language, country, "");
  220. }
  221. /**
  222. * Retrieves the locale with the specified language, country
  223. * and variant from the cache.
  224. *
  225. * @param language the language of the locale to retrieve.
  226. * @param country the country of the locale to retrieve.
  227. * @param variant the variant of the locale to retrieve.
  228. * @return the locale.
  229. */
  230. private static Locale getLocale(String language, String country, String variant)
  231. {
  232. if (localeMap == null)
  233. localeMap = new HashMap(256);
  234. String name = language + "_" + country + "_" + variant;
  235. Locale locale = (Locale) localeMap.get(name);
  236. if (locale == null)
  237. {
  238. locale = new Locale(language, country, variant);
  239. localeMap.put(name, locale);
  240. }
  241. return locale;
  242. }
  243. /**
  244. * Convert new iso639 codes to the old ones.
  245. *
  246. * @param language the language to check
  247. * @return the appropriate code
  248. */
  249. private String convertLanguage(String language)
  250. {
  251. if (language.equals(""))
  252. return language;
  253. language = language.toLowerCase();
  254. int index = "he,id,yi".indexOf(language);
  255. if (index != -1)
  256. return "iw,in,ji".substring(index, index + 2);
  257. return language;
  258. }
  259. /**
  260. * Creates a new locale for the given language and country.
  261. *
  262. * @param language lowercase two-letter ISO-639 A2 language code
  263. * @param country uppercase two-letter ISO-3166 A2 contry code
  264. * @param variant vendor and browser specific
  265. * @throws NullPointerException if any argument is null
  266. */
  267. public Locale(String language, String country, String variant)
  268. {
  269. // During bootstrap, we already know the strings being passed in are
  270. // the correct capitalization, and not null. We can't call
  271. // String.toUpperCase during this time, since that depends on the
  272. // default locale.
  273. if (defaultLocale != null)
  274. {
  275. language = convertLanguage(language);
  276. country = country.toUpperCase();
  277. }
  278. this.language = language.intern();
  279. this.country = country.intern();
  280. this.variant = variant.intern();
  281. hashcode = language.hashCode() ^ country.hashCode() ^ variant.hashCode();
  282. }
  283. /**
  284. * Creates a new locale for the given language and country.
  285. *
  286. * @param language lowercase two-letter ISO-639 A2 language code
  287. * @param country uppercase two-letter ISO-3166 A2 country code
  288. * @throws NullPointerException if either argument is null
  289. */
  290. public Locale(String language, String country)
  291. {
  292. this(language, country, "");
  293. }
  294. /**
  295. * Creates a new locale for a language.
  296. *
  297. * @param language lowercase two-letter ISO-639 A2 language code
  298. * @throws NullPointerException if either argument is null
  299. * @since 1.4
  300. */
  301. public Locale(String language)
  302. {
  303. this(language, "", "");
  304. }
  305. /**
  306. * Returns the default Locale. The default locale is generally once set
  307. * on start up and then never changed. Normally you should use this locale
  308. * for everywhere you need a locale. The initial setting matches the
  309. * default locale, the user has chosen.
  310. *
  311. * @return the default locale for this virtual machine
  312. */
  313. public static Locale getDefault()
  314. {
  315. return defaultLocale;
  316. }
  317. /**
  318. * Changes the default locale. Normally only called on program start up.
  319. * Note that this doesn't change the locale for other programs. This has
  320. * a security check,
  321. * <code>PropertyPermission("user.language", "write")</code>, because of
  322. * its potential impact to running code.
  323. *
  324. * @param newLocale the new default locale
  325. * @throws NullPointerException if newLocale is null
  326. * @throws SecurityException if permission is denied
  327. */
  328. public static void setDefault(Locale newLocale)
  329. {
  330. if (newLocale == null)
  331. throw new NullPointerException();
  332. SecurityManager sm = System.getSecurityManager();
  333. if (sm != null)
  334. sm.checkPermission(new PropertyPermission("user.language", "write"));
  335. defaultLocale = newLocale;
  336. }
  337. /**
  338. * Returns the list of available locales.
  339. *
  340. * @return the installed locales
  341. */
  342. public static synchronized Locale[] getAvailableLocales()
  343. {
  344. if (availableLocales == null)
  345. {
  346. int len = LocaleHelper.getLocaleCount();
  347. availableLocales = new Locale[len];
  348. for (int i = 0; i < len; i++)
  349. {
  350. String language;
  351. String country = "";
  352. String variant = "";
  353. String name = LocaleHelper.getLocaleName(i);
  354. language = name.substring(0, 2);
  355. if (name.length() > 2)
  356. country = name.substring(3);
  357. int index = country.indexOf("_");
  358. if (index > 0)
  359. {
  360. variant = country.substring(index + 1);
  361. country = country.substring(0, index - 1);
  362. }
  363. availableLocales[i] = getLocale(language, country, variant);
  364. }
  365. }
  366. return (Locale[]) availableLocales.clone();
  367. }
  368. /**
  369. * Returns a list of all 2-letter uppercase country codes as defined
  370. * in ISO 3166.
  371. *
  372. * @return a list of acceptable country codes
  373. */
  374. public static String[] getISOCountries()
  375. {
  376. if (countryCache == null)
  377. {
  378. countryCache = getISOStrings("territories");
  379. }
  380. return (String[]) countryCache.clone();
  381. }
  382. /**
  383. * Returns a list of all 2-letter lowercase language codes as defined
  384. * in ISO 639 (both old and new variant).
  385. *
  386. * @return a list of acceptable language codes
  387. */
  388. public static String[] getISOLanguages()
  389. {
  390. if (languageCache == null)
  391. {
  392. languageCache = getISOStrings("languages");
  393. }
  394. return (String[]) languageCache.clone();
  395. }
  396. /**
  397. * Returns the set of keys from the specified resource hashtable, filtered
  398. * so that only two letter strings are returned.
  399. *
  400. * @param tableName the name of the table from which to retrieve the keys.
  401. * @return an array of two-letter strings.
  402. */
  403. private static String[] getISOStrings(String tableName)
  404. {
  405. int count = 0;
  406. ResourceBundle bundle =
  407. ResourceBundle.getBundle("gnu.java.locale.LocaleInformation");
  408. Enumeration e = bundle.getKeys();
  409. ArrayList tempList = new ArrayList();
  410. while (e.hasMoreElements())
  411. {
  412. String key = (String) e.nextElement();
  413. if (key.startsWith(tableName + "."))
  414. {
  415. String str = key.substring(tableName.length() + 1);
  416. if (str.length() == 2
  417. && Character.isLetter(str.charAt(0))
  418. && Character.isLetter(str.charAt(1)))
  419. {
  420. tempList.add(str);
  421. ++count;
  422. }
  423. }
  424. }
  425. String[] strings = new String[count];
  426. for (int a = 0; a < count; ++a)
  427. strings[a] = (String) tempList.get(a);
  428. return strings;
  429. }
  430. /**
  431. * Returns the language code of this locale. Some language codes have changed
  432. * as ISO 639 has evolved; this returns the old name, even if you built
  433. * the locale with the new one.
  434. *
  435. * @return language code portion of this locale, or an empty String
  436. */
  437. public String getLanguage()
  438. {
  439. return language;
  440. }
  441. /**
  442. * Returns the country code of this locale.
  443. *
  444. * @return country code portion of this locale, or an empty String
  445. */
  446. public String getCountry()
  447. {
  448. return country;
  449. }
  450. /**
  451. * Returns the variant code of this locale.
  452. *
  453. * @return the variant code portion of this locale, or an empty String
  454. */
  455. public String getVariant()
  456. {
  457. return variant;
  458. }
  459. /**
  460. * Gets the string representation of the current locale. This consists of
  461. * the language, the country, and the variant, separated by an underscore.
  462. * The variant is listed only if there is a language or country. Examples:
  463. * "en", "de_DE", "_GB", "en_US_WIN", "de__POSIX", "fr__MAC".
  464. *
  465. * @return the string representation of this Locale
  466. * @see #getDisplayName()
  467. */
  468. public String toString()
  469. {
  470. if (language.length() == 0 && country.length() == 0)
  471. return "";
  472. else if (country.length() == 0 && variant.length() == 0)
  473. return language;
  474. CPStringBuilder result = new CPStringBuilder(language);
  475. result.append('_').append(country);
  476. if (variant.length() != 0)
  477. result.append('_').append(variant);
  478. return result.toString();
  479. }
  480. /**
  481. * Returns the three-letter ISO language abbrevation of this locale.
  482. *
  483. * @throws MissingResourceException if the three-letter code is not known
  484. */
  485. public String getISO3Language()
  486. {
  487. // We know all strings are interned so we can use '==' for better performance.
  488. if (language == "")
  489. return "";
  490. int index
  491. = ("aa,ab,af,am,ar,as,ay,az,ba,be,bg,bh,bi,bn,bo,br,ca,co,cs,cy,da,"
  492. + "de,dz,el,en,eo,es,et,eu,fa,fi,fj,fo,fr,fy,ga,gd,gl,gn,gu,ha,iw,"
  493. + "hi,hr,hu,hy,ia,in,ie,ik,in,is,it,iu,iw,ja,ji,jw,ka,kk,kl,km,kn,"
  494. + "ko,ks,ku,ky,la,ln,lo,lt,lv,mg,mi,mk,ml,mn,mo,mr,ms,mt,my,na,ne,"
  495. + "nl,no,oc,om,or,pa,pl,ps,pt,qu,rm,rn,ro,ru,rw,sa,sd,sg,sh,si,sk,"
  496. + "sl,sm,sn,so,sq,sr,ss,st,su,sv,sw,ta,te,tg,th,ti,tk,tl,tn,to,tr,"
  497. + "ts,tt,tw,ug,uk,ur,uz,vi,vo,wo,xh,ji,yo,za,zh,zu")
  498. .indexOf(language);
  499. if (index % 3 != 0 || language.length() != 2)
  500. throw new MissingResourceException
  501. ("Can't find ISO3 language for " + language,
  502. "java.util.Locale", language);
  503. // Don't read this aloud. These are the three letter language codes.
  504. return
  505. ("aarabkaframharaasmaymazebakbelbulbihbisbenbodbrecatcoscescymdandeu"
  506. + "dzoellengepospaesteusfasfinfijfaofrafrygaigdhglggrngujhauhebhinhrv"
  507. + "hunhyeinaindileipkindislitaikuhebjpnyidjawkatkazkalkhmkankorkaskur"
  508. + "kirlatlinlaolitlavmlgmrimkdmalmonmolmarmsamltmyanaunepnldnorociorm"
  509. + "oripanpolpusporquerohrunronruskinsansndsagsrpsinslkslvsmosnasomsqi"
  510. + "srpsswsotsunsweswatamteltgkthatirtuktgltsntonturtsotattwiuigukrurd"
  511. + "uzbvievolwolxhoyidyorzhazhozul")
  512. .substring(index, index + 3);
  513. }
  514. /**
  515. * Returns the three-letter ISO country abbrevation of the locale.
  516. *
  517. * @throws MissingResourceException if the three-letter code is not known
  518. */
  519. public String getISO3Country()
  520. {
  521. // We know all strings are interned so we can use '==' for better performance.
  522. if (country == "")
  523. return "";
  524. int index
  525. = ("AD,AE,AF,AG,AI,AL,AM,AN,AO,AQ,AR,AS,AT,AU,AW,AZ,BA,BB,BD,BE,BF,"
  526. + "BG,BH,BI,BJ,BM,BN,BO,BR,BS,BT,BV,BW,BY,BZ,CA,CC,CF,CG,CH,CI,CK,"
  527. + "CL,CM,CN,CO,CR,CU,CV,CX,CY,CZ,DE,DJ,DK,DM,DO,DZ,EC,EE,EG,EH,ER,"
  528. + "ES,ET,FI,FJ,FK,FM,FO,FR,FX,GA,GB,GD,GE,GF,GH,GI,GL,GM,GN,GP,GQ,"
  529. + "GR,GS,GT,GU,GW,GY,HK,HM,HN,HR,HT,HU,ID,IE,IL,IN,IO,IQ,IR,IS,IT,"
  530. + "JM,JO,JP,KE,KG,KH,KI,KM,KN,KP,KR,KW,KY,KZ,LA,LB,LC,LI,LK,LR,LS,"
  531. + "LT,LU,LV,LY,MA,MC,MD,MG,MH,MK,ML,MM,MN,MO,MP,MQ,MR,MS,MT,MU,MV,"
  532. + "MW,MX,MY,MZ,NA,NC,NE,NF,NG,NI,NL,NO,NP,NR,NU,NZ,OM,PA,PE,PF,PG,"
  533. + "PH,PK,PL,PM,PN,PR,PT,PW,PY,QA,RE,RO,RU,RW,SA,SB,SC,SD,SE,SG,SH,"
  534. + "SI,SJ,SK,SL,SM,SN,SO,SR,ST,SV,SY,SZ,TC,TD,TF,TG,TH,TJ,TK,TM,TN,"
  535. + "TO,TP,TR,TT,TV,TW,TZ,UA,UG,UM,US,UY,UZ,VA,VC,VE,VG,VI,VN,VU,WF,"
  536. + "WS,YE,YT,YU,ZA,ZM,ZR,ZW")
  537. .indexOf(country);
  538. if (index % 3 != 0 || country.length() != 2)
  539. throw new MissingResourceException
  540. ("Can't find ISO3 country for " + country,
  541. "java.util.Locale", country);
  542. // Don't read this aloud. These are the three letter country codes.
  543. return
  544. ("ANDAREAFGATGAIAALBARMANTAGOATAARGASMAUTAUSABWAZEBIHBRBBGDBELBFABGR"
  545. + "BHRBDIBENBMUBRNBOLBRABHSBTNBVTBWABLRBLZCANCCKCAFCOGCHECIVCOKCHLCMR"
  546. + "CHNCOLCRICUBCPVCXRCYPCZEDEUDJIDNKDMADOMDZAECUESTEGYESHERIESPETHFIN"
  547. + "FJIFLKFSMFROFRAFXXGABGBRGRDGEOGUFGHAGIBGRLGMBGINGLPGNQGRCSGSGTMGUM"
  548. + "GNBGUYHKGHMDHNDHRVHTIHUNIDNIRLISRINDIOTIRQIRNISLITAJAMJORJPNKENKGZ"
  549. + "KHMKIRCOMKNAPRKKORKWTCYMKAZLAOLBNLCALIELKALBRLSOLTULUXLVALBYMARMCO"
  550. + "MDAMDGMHLMKDMLIMMRMNGMACMNPMTQMRTMSRMLTMUSMDVMWIMEXMYSMOZNAMNCLNER"
  551. + "NFKNGANICNLDNORNPLNRUNIUNZLOMNPANPERPYFPNGPHLPAKPOLSPMPCNPRIPRTPLW"
  552. + "PRYQATREUROMRUSRWASAUSLBSYCSDNSWESGPSHNSVNSJMSVKSLESMRSENSOMSURSTP"
  553. + "SLVSYRSWZTCATCDATFTGOTHATJKTKLTKMTUNTONTMPTURTTOTUVTWNTZAUKRUGAUMI"
  554. + "USAURYUZBVATVCTVENVGBVIRVNMVUTWLFWSMYEMMYTYUGZAFZMBZARZWE")
  555. .substring(index, index + 3);
  556. }
  557. /**
  558. * Gets the country name suitable for display to the user, formatted
  559. * for the default locale. This has the same effect as
  560. * <pre>
  561. * getDisplayLanguage(Locale.getDefault());
  562. * </pre>
  563. *
  564. * @return the language name of this locale localized to the default locale,
  565. * with the ISO code as backup
  566. */
  567. public String getDisplayLanguage()
  568. {
  569. return getDisplayLanguage(defaultLocale);
  570. }
  571. /**
  572. * <p>
  573. * Gets the name of the language specified by this locale, in a form suitable
  574. * for display to the user. If possible, the display name will be localized
  575. * to the specified locale. For example, if the locale instance is
  576. * <code>Locale.GERMANY</code>, and the specified locale is <code>Locale.UK</code>,
  577. * the result would be 'German'. Using the German locale would instead give
  578. * 'Deutsch'. If the display name can not be localized to the supplied
  579. * locale, it will fall back on other output in the following order:
  580. * </p>
  581. * <ul>
  582. * <li>the display name in the default locale</li>
  583. * <li>the display name in English</li>
  584. * <li>the ISO code</li>
  585. * </ul>
  586. * <p>
  587. * If the language is unspecified by this locale, then the empty string is
  588. * returned.
  589. * </p>
  590. *
  591. * @param inLocale the locale to use for formatting the display string.
  592. * @return the language name of this locale localized to the given locale,
  593. * with the default locale, English and the ISO code as backups.
  594. * @throws NullPointerException if the supplied locale is null.
  595. */
  596. public String getDisplayLanguage(Locale inLocale)
  597. {
  598. if (language.isEmpty())
  599. return "";
  600. try
  601. {
  602. ResourceBundle res =
  603. ResourceBundle.getBundle("gnu.java.locale.LocaleInformation",
  604. inLocale,
  605. ClassLoader.getSystemClassLoader());
  606. return res.getString("languages." + language);
  607. }
  608. catch (MissingResourceException e)
  609. {
  610. /* This means runtime support for the locale
  611. * is not available, so we check providers. */
  612. }
  613. for (LocaleNameProvider p :
  614. ServiceLoader.load(LocaleNameProvider.class))
  615. {
  616. for (Locale loc : p.getAvailableLocales())
  617. {
  618. if (loc.equals(inLocale))
  619. {
  620. String locLang = p.getDisplayLanguage(language,
  621. inLocale);
  622. if (locLang != null)
  623. return locLang;
  624. break;
  625. }
  626. }
  627. }
  628. if (inLocale.equals(Locale.ROOT)) // Base case
  629. return language;
  630. return getDisplayLanguage(LocaleHelper.getFallbackLocale(inLocale));
  631. }
  632. /**
  633. * Returns the country name of this locale localized to the
  634. * default locale. If the localized is not found, the ISO code
  635. * is returned. This has the same effect as
  636. * <pre>
  637. * getDisplayCountry(Locale.getDefault());
  638. * </pre>
  639. *
  640. * @return the country name of this locale localized to the given locale,
  641. * with the ISO code as backup
  642. */
  643. public String getDisplayCountry()
  644. {
  645. return getDisplayCountry(defaultLocale);
  646. }
  647. /**
  648. * <p>
  649. * Gets the name of the country specified by this locale, in a form suitable
  650. * for display to the user. If possible, the display name will be localized
  651. * to the specified locale. For example, if the locale instance is
  652. * <code>Locale.GERMANY</code>, and the specified locale is <code>Locale.UK</code>,
  653. * the result would be 'Germany'. Using the German locale would instead give
  654. * 'Deutschland'. If the display name can not be localized to the supplied
  655. * locale, it will fall back on other output in the following order:
  656. * </p>
  657. * <ul>
  658. * <li>the display name in the default locale</li>
  659. * <li>the display name in English</li>
  660. * <li>the ISO code</li>
  661. * </ul>
  662. * <p>
  663. * If the country is unspecified by this locale, then the empty string is
  664. * returned.
  665. * </p>
  666. *
  667. * @param inLocale the locale to use for formatting the display string.
  668. * @return the country name of this locale localized to the given locale,
  669. * with the default locale, English and the ISO code as backups.
  670. * @throws NullPointerException if the supplied locale is null.
  671. */
  672. public String getDisplayCountry(Locale inLocale)
  673. {
  674. if (country.isEmpty())
  675. return "";
  676. try
  677. {
  678. ResourceBundle res =
  679. ResourceBundle.getBundle("gnu.java.locale.LocaleInformation",
  680. inLocale,
  681. ClassLoader.getSystemClassLoader());
  682. return res.getString("territories." + country);
  683. }
  684. catch (MissingResourceException e)
  685. {
  686. /* This means runtime support for the locale
  687. * is not available, so we check providers. */
  688. }
  689. for (LocaleNameProvider p :
  690. ServiceLoader.load(LocaleNameProvider.class))
  691. {
  692. for (Locale loc : p.getAvailableLocales())
  693. {
  694. if (loc.equals(inLocale))
  695. {
  696. String locCountry = p.getDisplayCountry(country,
  697. inLocale);
  698. if (locCountry != null)
  699. return locCountry;
  700. break;
  701. }
  702. }
  703. }
  704. if (inLocale.equals(Locale.ROOT)) // Base case
  705. return country;
  706. return getDisplayCountry(LocaleHelper.getFallbackLocale(inLocale));
  707. }
  708. /**
  709. * Returns the variant name of this locale localized to the
  710. * default locale. If the localized is not found, the variant code
  711. * itself is returned. This has the same effect as
  712. * <pre>
  713. * getDisplayVariant(Locale.getDefault());
  714. * </pre>
  715. *
  716. * @return the variant code of this locale localized to the given locale,
  717. * with the ISO code as backup
  718. */
  719. public String getDisplayVariant()
  720. {
  721. return getDisplayVariant(defaultLocale);
  722. }
  723. /**
  724. * <p>
  725. * Gets the name of the variant specified by this locale, in a form suitable
  726. * for display to the user. If possible, the display name will be localized
  727. * to the specified locale. For example, if the locale instance is a revised
  728. * variant, and the specified locale is <code>Locale.UK</code>, the result
  729. * would be 'REVISED'. Using the German locale would instead give
  730. * 'Revidiert'. If the display name can not be localized to the supplied
  731. * locale, it will fall back on other output in the following order:
  732. * </p>
  733. * <ul>
  734. * <li>the display name in the default locale</li>
  735. * <li>the display name in English</li>
  736. * <li>the ISO code</li>
  737. * </ul>
  738. * <p>
  739. * If the variant is unspecified by this locale, then the empty string is
  740. * returned.
  741. * </p>
  742. *
  743. * @param inLocale the locale to use for formatting the display string.
  744. * @return the variant name of this locale localized to the given locale,
  745. * with the default locale, English and the ISO code as backups.
  746. * @throws NullPointerException if the supplied locale is null.
  747. */
  748. public String getDisplayVariant(Locale inLocale)
  749. {
  750. if (variant.isEmpty())
  751. return "";
  752. try
  753. {
  754. ResourceBundle res =
  755. ResourceBundle.getBundle("gnu.java.locale.LocaleInformation",
  756. inLocale,
  757. ClassLoader.getSystemClassLoader());
  758. return res.getString("variants." + variant);
  759. }
  760. catch (MissingResourceException e)
  761. {
  762. /* This means runtime support for the locale
  763. * is not available, so we check providers. */
  764. }
  765. for (LocaleNameProvider p :
  766. ServiceLoader.load(LocaleNameProvider.class))
  767. {
  768. for (Locale loc : p.getAvailableLocales())
  769. {
  770. if (loc.equals(inLocale))
  771. {
  772. String locVar = p.getDisplayVariant(variant,
  773. inLocale);
  774. if (locVar != null)
  775. return locVar;
  776. break;
  777. }
  778. }
  779. }
  780. if (inLocale.equals(Locale.ROOT)) // Base case
  781. return country;
  782. return getDisplayVariant(LocaleHelper.getFallbackLocale(inLocale));
  783. }
  784. /**
  785. * Gets all local components suitable for display to the user, formatted
  786. * for the default locale. For the language component, getDisplayLanguage
  787. * is called. For the country component, getDisplayCountry is called.
  788. * For the variant set component, getDisplayVariant is called.
  789. *
  790. * <p>The returned String will be one of the following forms:<br>
  791. * <pre>
  792. * language (country, variant)
  793. * language (country)
  794. * language (variant)
  795. * country (variant)
  796. * language
  797. * country
  798. * variant
  799. * </pre>
  800. *
  801. * @return String version of this locale, suitable for display to the user
  802. */
  803. public String getDisplayName()
  804. {
  805. return getDisplayName(defaultLocale);
  806. }
  807. /**
  808. * Gets all local components suitable for display to the user, formatted
  809. * for a specified locale. For the language component,
  810. * getDisplayLanguage(Locale) is called. For the country component,
  811. * getDisplayCountry(Locale) is called. For the variant set component,
  812. * getDisplayVariant(Locale) is called.
  813. *
  814. * <p>The returned String will be one of the following forms:<br>
  815. * <pre>
  816. * language (country, variant)
  817. * language (country)
  818. * language (variant)
  819. * country (variant)
  820. * language
  821. * country
  822. * variant
  823. * </pre>
  824. *
  825. * @param locale locale to use for formatting
  826. * @return String version of this locale, suitable for display to the user
  827. */
  828. public String getDisplayName(Locale locale)
  829. {
  830. CPStringBuilder result = new CPStringBuilder();
  831. int count = 0;
  832. String[] delimiters = {"", " (", ","};
  833. if (language.length() != 0)
  834. {
  835. result.append(delimiters[count++]);
  836. result.append(getDisplayLanguage(locale));
  837. }
  838. if (country.length() != 0)
  839. {
  840. result.append(delimiters[count++]);
  841. result.append(getDisplayCountry(locale));
  842. }
  843. if (variant.length() != 0)
  844. {
  845. result.append(delimiters[count++]);
  846. result.append(getDisplayVariant(locale));
  847. }
  848. if (count > 1)
  849. result.append(")");
  850. return result.toString();
  851. }
  852. /**
  853. * Does the same as <code>Object.clone()</code> but does not throw
  854. * a <code>CloneNotSupportedException</code>. Why anyone would
  855. * use this method is a secret to me, since this class is immutable.
  856. *
  857. * @return the clone
  858. */
  859. public Object clone()
  860. {
  861. // This class is final, so no need to use native super.clone().
  862. return new Locale(language, country, variant);
  863. }
  864. /**
  865. * Return the hash code for this locale. The hashcode is the logical
  866. * xor of the hash codes of the language, the country and the variant.
  867. * The hash code is precomputed, since <code>Locale</code>s are often
  868. * used in hash tables.
  869. *
  870. * @return the hashcode
  871. */
  872. public int hashCode()
  873. {
  874. return hashcode;
  875. }
  876. /**
  877. * Compares two locales. To be equal, obj must be a Locale with the same
  878. * language, country, and variant code.
  879. *
  880. * @param obj the other locale
  881. * @return true if obj is equal to this
  882. */
  883. public boolean equals(Object obj)
  884. {
  885. if (this == obj)
  886. return true;
  887. if (! (obj instanceof Locale))
  888. return false;
  889. Locale l = (Locale) obj;
  890. return (language == l.language
  891. && country == l.country
  892. && variant == l.variant);
  893. }
  894. /**
  895. * Write the locale to an object stream.
  896. *
  897. * @param s the stream to write to
  898. * @throws IOException if the write fails
  899. * @serialData The first three fields are Strings representing language,
  900. * country, and variant. The fourth field is a placeholder for
  901. * the cached hashcode, but this is always written as -1, and
  902. * recomputed when reading it back.
  903. */
  904. private void writeObject(ObjectOutputStream s)
  905. throws IOException
  906. {
  907. ObjectOutputStream.PutField fields = s.putFields();
  908. fields.put("hashcode", -1);
  909. s.defaultWriteObject();
  910. }
  911. /**
  912. * Reads a locale from the input stream.
  913. *
  914. * @param s the stream to read from
  915. * @throws IOException if reading fails
  916. * @throws ClassNotFoundException if reading fails
  917. * @serialData the hashCode is always invalid and must be recomputed
  918. */
  919. private void readObject(ObjectInputStream s)
  920. throws IOException, ClassNotFoundException
  921. {
  922. s.defaultReadObject();
  923. hashcode = language.hashCode() ^ country.hashCode() ^ variant.hashCode();
  924. }
  925. } // class Locale