Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/test/sun/text/resources/LocaleDataTest.java
38840 views
/*1* Copyright (c) 2007, 2020, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*/22/*23* @test24* @bug 4052473 4052679 4055602 4066550 4067619 4068012 4068073 4070174 407045225* 4070178 4070450 4070695 4070725 4070795 4071003 4071183 4071782 407201326* 4072388 4072773 4075404 4084356 4087238 4092361 4094033 4094371 409851827* 4099810 4103218 4103220 4103861 4112136 4113638 4113654 4117054 412246828* 4122840 4139860 4156708 4175306 4215747 4209960 4290801 4900884 494298229* 4518811 4945388 4936845 4794068 4461740 4965260 4984277 4826794 503258030* 5102005 5074431 6182685 6208712 6277020 6245766 6351682 6386647 637938231* 6414459 6455680 6498742 6558863 6488119 6547501 6497154 6558856 648117732* 6379214 6485516 6486607 4225362 4494727 6533691 6531591 6531593 657025933* 6509039 6609737 6610748 6645271 6507067 6873931 6450945 6645268 664661134* 6645405 6650730 6910489 6573250 6870908 6585666 6716626 6914413 691678735* 6919624 6998391 7019267 7020960 7025837 7020583 7036905 7066203 710149536* 7003124 7085757 7028073 7171028 7189611 8000983 7195759 8004489 800650937* 7114053 7074882 7040556 8013836 8021121 6192407 6931564 8027695 709082638* 8017142 8037343 8055222 8042126 8074791 8075173 8080774 8129361 814595239* 8164784 8187946 8195478 8193552 8202026 8204269 8208746 8209775 823422840* 8250665 825508641* @summary Verify locale data42*43*/4445/*46*47* (C) Copyright Taligent, Inc. 1996, 1997 - All Rights Reserved48* (C) Copyright IBM Corp. 1996 - 1998 - All Rights Reserved49*50* Portions copyright (c) 2007 Sun Microsystems, Inc.51* All Rights Reserved.52*53* The original version of this source code and documentation54* is copyrighted and owned by Taligent, Inc., a wholly-owned55* subsidiary of IBM. These materials are provided under terms56* of a License Agreement between Taligent and Sun. This technology57* is protected by multiple US and International patents.58*59* This notice and attribution to Taligent may not be removed.60* Taligent is a registered trademark of Taligent, Inc.61*62* Permission to use, copy, modify, and distribute this software63* and its documentation for NON-COMMERCIAL purposes and without64* fee is hereby granted provided that this copyright notice65* appears in all copies. Please refer to the file "copyright.html"66* for further important copyright and licensing information.67*68* SUN MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF69* THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED70* TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A71* PARTICULAR PURPOSE, OR NON-INFRINGEMENT. SUN SHALL NOT BE LIABLE FOR72* ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR73* DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.74*75*/7677/* This test is a generalized test for verifying changes to the locale data.78* It is driven by an external file that specifies the particular pieces of locale79* data to check. That file is in .properties file format: a series of key/value80* pairs delimited by newline characters, with the keys separated from the values81* by = signs. The keys are similar in syntax to a Unix pathname, with keys at82* successive levels of containment in the resource-data hierarchy separated by83* slashes. The file is in ISO 8859-1 encoding, with control characters and84* non-ASCII characters denoted with backslash-u escape sequences. The program also allows85* blank lines and comment lines to be interspersed with the data. Comment lines86* begin with '#'.87*88* A data file for this test would look something like this:<pre>89* FormatData//MonthNames/0=January90* FormatData//MonthNames/1=February91* LocaleNames//US=United States92* LocaleNames//FR=France93* FormatData/fr_FR/MonthNames/0=janvier94* FormatData/fr_FR/MonthNames/1=f\u00e9vrier95* LocaleNames/fr_FR/US=\u00c9tats-Unis96* LocaleNames/fr_FR/FR=France</pre>97*98* You can use language tag with '-' in locale field like this:<pre>99* LocaleNames/sr-Latn/SR=Surinam100* FormatData/sr-Latn-BA/DayNames/2=utorak</pre>101*102* The command-line syntax of this test is103* <tt>java LocaleDataTest [-w] [{ -s | <filename> }]</tt>104*105* This program always sends its results to standard output. If -w is not specified,106* this program prints out only the differences between the data file and the actual107* resource data. If -w is specified, the program prints out every entry, comment,108* and blank line from the data file. Where there is a difference between the data109* file and the resource data, the data is the data from the resources. This feature110* can be used to quickly generate a new data file.111*112* The user can specify an optional filename or -s. If the user specifies a filename,113* the program uses that file as the data file. If the user specifies -s, the program114* reads its input from standard input rather than from a file. If the user specifies115* neither, the program reads its input from a file called LocaleData in the same116* directory the program itself resides in.117*118* The -nothrow option prevents the program from throwing an exception when it119* gets an error. -w implies -nothrow.120*121* Other command-line options can be specified, but are ignored.122*123* It's important to note what this test will NOT test. Certain changes to the locale124* data are meant to have certain effects on the internationalization frameworks. For125* instance, we could ensure round-trip formatting/parsing integrity for the full126* date/time format of SimpleDateFormat by making sure that the full date and time127* patterns include sufficient data. The test of this is not whether changes were128* made to the locale data; it's whether using this data gives round-trip integrity.129* Likewise, changing the currency patterns to use \u00a4 instead of local currency130* symbols isn't something that can be tested by this test; instead, you want to131* actually format currency values and make sure the proper currency symbol was used.132*133* This test by itself doesn't do an exhaustive comparison of locale data. It is134* possible to do this manually, however: Use the GenerateKeyList tool to produce135* a complete list of keys for the two versions of the locales you want to compare,136* and then diff them. This will flag additions and deletions. Generate a data file137* for the base version of the data using the -w option and the output from138* GenerateKeyList, and then use the resultant file as the data file when you run139* this test against the new version of the data.140*/141142import java.io.*;143import java.text.*;144import java.util.Locale;145import java.util.ResourceBundle;146import java.util.ResourceBundle.Control;147import java.util.MissingResourceException;148149public class LocaleDataTest150{151static final String TEXT_RESOURCES_PACKAGE ="sun.text.resources";152static final String UTIL_RESOURCES_PACKAGE ="sun.util.resources";153154public static void main(String[] args) throws Exception {155156// set up our flags and our input and output streams based on the157// command-line arguments (exceptions generated here will propagate out158// to the environment)159BufferedReader in = null;160PrintWriter out = null;161boolean writeNewFile = false;162boolean doThrow = true;163164for (int i = 0; i < args.length; i++) {165if (args[i].equals("-w")) {166writeNewFile = true;167doThrow = false;168}169170else if (args[i].equals("-nothrow"))171doThrow = false;172173else if (args[i].equals("-s") && in == null)174in = new BufferedReader(new EscapeReader(new InputStreamReader(System.in,175"ISO8859_1")));176else if (!args[i].startsWith("-") && in == null)177in = new BufferedReader(new EscapeReader(new InputStreamReader(new178FileInputStream(args[i]), "ISO8859_1")));179}180if (in == null) {181File localeData = new File(System.getProperty("test.src", "."), "LocaleData");182in = new BufferedReader(new EscapeReader(new InputStreamReader(new183FileInputStream(localeData), "ISO8859_1")));184}185out = new PrintWriter(new EscapeWriter(new OutputStreamWriter(System.out,186"ISO8859_1")), true);187188// perform the actual test189int errorCount = doTest(in, out, writeNewFile);190191// write out the error count, and throw an exception out into the environment192// if there were any errors193if (errorCount != 0) {194if (!writeNewFile)195out.println("Test failed. " + errorCount + " errors.");196if (doThrow)197throw new Exception("Test failed. " + errorCount + " errors.");198}199else if (!writeNewFile)200out.println("Test passed.");201202in.close();203out.close();204}205206static int doTest(BufferedReader in, PrintWriter out, boolean writeNewFile)207throws Exception {208int errorCount = 0;209210String key = null;211String expectedValue = null;212String line = in.readLine();213while (line != null) {214if (line.startsWith("#") || line.length() == 0) {215if (writeNewFile)216out.println(line);217}218219else {220int index = line.indexOf("=");221if (index == -1) {222key = line;223expectedValue = "";224}225else {226key = line.substring(0, index);227if (index + 1 == line.length())228expectedValue = "";229else230expectedValue = line.substring(index + 1);231}232if (!processLine(key, expectedValue, out, writeNewFile))233++errorCount;234}235line = in.readLine();236}237return errorCount;238}239240static boolean processLine(String key, String expectedValue, PrintWriter out,241boolean writeNewFile) throws Exception {242String rbName, localeName, resTag, qualifier;243String language = "", country = "", variant = "";244int index, oldIndex;245246index = key.indexOf("/");247if (index == -1 || index + 1 == key.length())248throw new Exception("Malformed input file: no slashes in \"" + key + "\"");249rbName = key.substring(0, index);250251oldIndex = index + 1;252index = key.indexOf("/", oldIndex);253if (index == -1 || index + 1 == key.length())254throw new Exception("Malformed input file: \"" + key + "\" is missing locale name");255localeName = key.substring(oldIndex, index);256boolean use_tag = localeName.indexOf("-") != -1;257258if (use_tag == false && localeName.length() > 0) {259language = localeName.substring(0, 2);260if (localeName.length() > 3) {261country = localeName.substring(3, 5);262if (localeName.length() > 5)263variant = localeName.substring(6);264}265}266267oldIndex = index + 1;268index = key.indexOf("/", oldIndex);269if (index == -1)270index = key.length();271resTag = key.substring(oldIndex, index);272273// TimeZone name may have "/" in it, for example "Asia/Taipei", so use "Asia\/Taipei in LocaleData.274if(resTag.endsWith("\\")) {275resTag = resTag.substring(0, resTag.length() - 1);276oldIndex = index;277index = key.indexOf("/", oldIndex + 1);278if (index == -1) index = key.length();279resTag += key.substring(oldIndex, index);280}281282if (index < key.length() - 1)283qualifier = key.substring(index + 1);284else285qualifier = "";286287String retrievedValue = null;288Object resource = null;289try {290String fullName = null;291if (rbName.equals("CalendarData")292|| rbName.equals("CurrencyNames")293|| rbName.equals("LocaleNames")294|| rbName.equals("TimeZoneNames")) {295fullName = UTIL_RESOURCES_PACKAGE + "." + rbName;296} else {297fullName = TEXT_RESOURCES_PACKAGE + "." + rbName;298}299Locale locale;300if (use_tag) {301locale = Locale.forLanguageTag(localeName);302} else {303locale = new Locale(language, country, variant);304}305ResourceBundle bundle = ResourceBundle.getBundle(fullName,306locale,307JRELocaleResourceBundleControl.INSTANCE);308resource = bundle.getObject(resTag);309}310catch (MissingResourceException e) {311}312313if (resource != null) {314if (resource instanceof String) {315retrievedValue = (String)resource;316}317else if (resource instanceof String[]) {318int element = Integer.valueOf(qualifier).intValue();319String[] stringList = (String[])resource;320if (element >= 0 && element < stringList.length)321retrievedValue = stringList[element];322}323else if (resource instanceof String[][]) {324String[][] stringArray = (String[][])resource;325int slash = qualifier.indexOf("/");326if (slash == -1) {327for (int i = 0; i < stringArray.length; i++) {328if (stringArray[i][0].equals(qualifier))329retrievedValue = stringArray[i][1];330}331}332else {333int row = Integer.valueOf(qualifier.substring(0, slash)).intValue();334int column = Integer.valueOf(qualifier.substring(slash + 1)).intValue();335if (row >= 0 && row < stringArray.length && column >= 0 && column <336stringArray[row].length)337retrievedValue = stringArray[row][column];338}339}340}341342if (retrievedValue == null || !retrievedValue.equals(expectedValue)) {343if (retrievedValue == null)344retrievedValue = "<MISSING!>";345346if (writeNewFile)347out.println(key + "=" + retrievedValue);348else {349out.println("Mismatch in " + key + ":");350out.println(" file = \"" + expectedValue + "\"");351out.println(" jvm = \"" + retrievedValue + "\"");352}353return false;354}355else {356if (writeNewFile)357out.println(key + "=" + expectedValue);358}359return true;360}361362private static class JRELocaleResourceBundleControl extends ResourceBundle.Control {363static final JRELocaleResourceBundleControl INSTANCE = new JRELocaleResourceBundleControl();364365private JRELocaleResourceBundleControl() {366}367368@Override369public Locale getFallbackLocale(String baseName, Locale locale) {370if (baseName == null || locale == null) {371throw new NullPointerException();372}373return null;374}375376private static final String CLDR = ".cldr";377378/**379* Changes baseName to its per-language package name and380* calls the super class implementation. For example,381* if the baseName is "sun.text.resources.FormatData" and locale is ja_JP,382* the baseName is changed to "sun.text.resources.ja.FormatData". If383* baseName contains "cldr", such as "sun.text.resources.cldr.FormatData",384* the name is changed to "sun.text.resources.cldr.jp.FormatData".385*/386@Override387public String toBundleName(String baseName, Locale locale) {388String newBaseName = baseName;389String lang = locale.getLanguage();390if (lang.length() > 0) {391if (baseName.startsWith(UTIL_RESOURCES_PACKAGE)392|| baseName.startsWith(TEXT_RESOURCES_PACKAGE)) {393// Assume the lengths are the same.394if (UTIL_RESOURCES_PACKAGE.length()395!= TEXT_RESOURCES_PACKAGE.length()) {396throw new InternalError("The resources package names have different lengths.");397}398int index = TEXT_RESOURCES_PACKAGE.length();399if (baseName.indexOf(CLDR, index) > 0) {400index += CLDR.length();401}402newBaseName = baseName.substring(0, index + 1) + lang403+ baseName.substring(index);404}405}406return super.toBundleName(newBaseName, locale);407}408}409}410411class EscapeReader extends FilterReader {412public EscapeReader(Reader in) {413super(in);414}415416public int read() throws IOException {417if (buffer != null) {418String b = buffer.toString();419int result = b.charAt(0);420if (b.length() > 1)421buffer = new StringBuffer(b.substring(1));422else423buffer = null;424return result;425}426else {427int result = super.read();428if (result != '\\')429return result;430else {431buffer = new StringBuffer();432result = super.read();433buffer.append((char)result);434if (result == 'u') {435for (int i = 0; i < 4; i++) {436result = super.read();437if (result == -1)438break;439buffer.append((char)result);440}441String number = buffer.toString().substring(1);442result = Integer.parseInt(number, 16);443buffer = null;444return result;445}446return '\\';447}448}449}450451public int read(char[] cbuf, int start, int len) throws IOException {452int p = start;453int end = start + len;454int c = 0;455while (c != -1 && p < end) {456c = read();457if (c != -1)458cbuf[p++] = (char)c;459}460if (c == -1 && p == start)461return -1;462else463return p - start;464}465466private StringBuffer buffer = null;467}468469class EscapeWriter extends FilterWriter {470public EscapeWriter(Writer out) {471super(out);472}473474public void write(int c) throws IOException {475if ((c >= ' ' && c <= '\u007e') || c == '\r' || c == '\n')476super.write(c);477else {478super.write('\\');479super.write('u');480String number = Integer.toHexString(c);481if (number.length() < 4)482number = zeros.substring(0, 4 - number.length()) + number;483super.write(number.charAt(0));484super.write(number.charAt(1));485super.write(number.charAt(2));486super.write(number.charAt(3));487}488}489490public void write(char[] cbuf, int off, int len) throws IOException {491int end = off + len;492while (off < end)493write(cbuf[off++]);494}495496public void write(String str, int off, int len) throws IOException {497int end = off + len;498while (off < end)499write(str.charAt(off++));500}501502private static String zeros = "0000";503}504505506