Path: blob/master/test/jdk/sun/text/resources/LocaleDataTest.java
41149 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 8008577 8013836 8021121 6192407 6931564 802769538* 8017142 8037343 8055222 8042126 8074791 8075173 8080774 8129361 813491639* 8145136 8145952 8164784 8037111 8081643 7037368 8178872 8185841 819091840* 8187946 8195478 8181157 8179071 8193552 8202026 8204269 8202537 820874641* 8209775 8221432 8227127 8230284 8231273 8233579 8234288 8250665 825508642* 825131743* @summary Verify locale data44* @modules java.base/sun.util.resources45* @modules jdk.localedata46* @run main LocaleDataTest47* @run main LocaleDataTest -cldr48*49*/5051/*52*53* (C) Copyright Taligent, Inc. 1996, 1997 - All Rights Reserved54* (C) Copyright IBM Corp. 1996 - 1998 - All Rights Reserved55*56* Portions copyright (c) 2007 Sun Microsystems, Inc.57* All Rights Reserved.58*59* The original version of this source code and documentation60* is copyrighted and owned by Taligent, Inc., a wholly-owned61* subsidiary of IBM. These materials are provided under terms62* of a License Agreement between Taligent and Sun. This technology63* is protected by multiple US and International patents.64*65* This notice and attribution to Taligent may not be removed.66* Taligent is a registered trademark of Taligent, Inc.67*68* Permission to use, copy, modify, and distribute this software69* and its documentation for NON-COMMERCIAL purposes and without70* fee is hereby granted provided that this copyright notice71* appears in all copies. Please refer to the file "copyright.html"72* for further important copyright and licensing information.73*74* SUN MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF75* THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED76* TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A77* PARTICULAR PURPOSE, OR NON-INFRINGEMENT. SUN SHALL NOT BE LIABLE FOR78* ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR79* DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.80*81*/8283/* This test is a generalized test for verifying changes to the locale data.84* It is driven by an external file that specifies the particular pieces of locale85* data to check. That file is in .properties file format: a series of key/value86* pairs delimited by newline characters, with the keys separated from the values87* by = signs. The keys are similar in syntax to a Unix pathname, with keys at88* successive levels of containment in the resource-data hierarchy separated by89* slashes. The file is in ISO 8859-1 encoding, with control characters and90* non-ASCII characters denoted with backslash-u escape sequences. The program also allows91* blank lines and comment lines to be interspersed with the data. Comment lines92* begin with '#'.93*94* A data file for this test would look something like this:<pre>95* FormatData//MonthNames/0=January96* FormatData//MonthNames/1=February97* LocaleNames//US=United States98* LocaleNames//FR=France99* FormatData/fr_FR/MonthNames/0=janvier100* FormatData/fr_FR/MonthNames/1=f\u00e9vrier101* LocaleNames/fr_FR/US=\u00c9tats-Unis102* LocaleNames/fr_FR/FR=France</pre>103*104* Second field which designates locale is in the form of:105* 1) Legacy locale notation using '_' as a locale component(language/country/variant) separator.106* language is a mandatory component. country and variant are optional, however,107* variant cannot exist without country. So for example, while "ja"/"ja_JP"/"ja_JP_JP" are valid,108* "_JP"/"ja__JP" are invalid.109*110* 2) BCP47 language tag notation in which we can specify language tag with '-' as a subtag111* separator. Language tag can be specified with '-' in locale field like this:112* <pre>LocaleNames/sr-Latn/SR=Surinam113* FormatData/sr-Latn-BA/DayNames/2=utorak</pre>114*115* The command-line syntax of this test is116* <tt>java --add-exports java.base/sun.util.resources=ALL-UNNAMED LocaleDataTest.java [-w] [{ -s | <filename> }] [-cldr]</tt>117*118* This program always sends its results to standard output. If -w is not specified,119* this program prints out only the differences between the data file and the actual120* resource data. If -w is specified, the program prints out every entry, comment,121* and blank line from the data file. Where there is a difference between the data122* file and the resource data, the data is the data from the resources. This feature123* can be used to quickly generate a new data file.124*125* The user can specify an optional filename or -s. If the user specifies a filename,126* the program uses that file as the data file. If the user specifies -s, the program127* reads its input from standard input rather than from a file. If the user specifies128* neither, the program reads its input from a file called LocaleData in the same129* directory the program itself resides in.130*131* The -nothrow option prevents the program from throwing an exception when it132* gets an error. -w implies -nothrow.133*134* -cldr option specifies to test CLDR locale data. The default data file name for this135* option is "LocaleData.cldr".136*137* Other command-line options can be specified, but are ignored.138*139* It's important to note what this test will NOT test. Certain changes to the locale140* data are meant to have certain effects on the internationalization frameworks. For141* instance, we could ensure round-trip formatting/parsing integrity for the full142* date/time format of SimpleDateFormat by making sure that the full date and time143* patterns include sufficient data. The test of this is not whether changes were144* made to the locale data; it's whether using this data gives round-trip integrity.145* Likewise, changing the currency patterns to use \u00a4 instead of local currency146* symbols isn't something that can be tested by this test; instead, you want to147* actually format currency values and make sure the proper currency symbol was used.148*149* This test by itself doesn't do an exhaustive comparison of locale data. It is150* possible to do this manually, however: Use the GenerateKeyList tool to produce151* a complete list of keys for the two versions of the locales you want to compare,152* and then diff them. This will flag additions and deletions. Generate a data file153* for the base version of the data using the -w option and the output from154* GenerateKeyList, and then use the resultant file as the data file when you run155* this test against the new version of the data.156*/157158import java.io.BufferedReader;159import java.io.File;160import java.io.FileInputStream;161import java.io.FilterReader;162import java.io.FilterWriter;163import java.io.IOException;164import java.io.InputStreamReader;165import java.io.OutputStreamWriter;166import java.io.PrintWriter;167import java.io.Reader;168import java.io.Writer;169import java.util.Locale;170import java.util.MissingResourceException;171import java.util.ResourceBundle;172import sun.util.resources.LocaleData;173174public class LocaleDataTest175{176static final String TEXT_RESOURCES_PACKAGE ="sun.text.resources";177static final String UTIL_RESOURCES_PACKAGE ="sun.util.resources";178static final String DEFAULT_DATAFILE ="LocaleData";179static String cldrSuffix = "";180181public static void main(String[] args) throws Exception {182183// set up our flags and our input and output streams based on the184// command-line arguments (exceptions generated here will propagate out185// to the environment)186BufferedReader in = null;187PrintWriter out = null;188boolean writeNewFile = false;189boolean doThrow = true;190191for (int i = 0; i < args.length; i++) {192if (args[i].equals("-w")) {193writeNewFile = true;194doThrow = false;195}196197else if (args[i].equals("-nothrow"))198doThrow = false;199200else if (args[i].equals("-cldr")) {201cldrSuffix = ".cldr";202}203204else if (args[i].equals("-s") && in == null)205in = new BufferedReader(new EscapeReader(new InputStreamReader(System.in,206"ISO8859_1")));207else if (!args[i].startsWith("-") && in == null)208in = new BufferedReader(new EscapeReader(new InputStreamReader(new209FileInputStream(args[i]), "ISO8859_1")));210}211if (in == null) {212File localeData = new File(System.getProperty("test.src", "."), DEFAULT_DATAFILE + cldrSuffix);213in = new BufferedReader(new EscapeReader(new InputStreamReader(new214FileInputStream(localeData), "ISO8859_1")));215}216out = new PrintWriter(new EscapeWriter(new OutputStreamWriter(System.out,217"ISO8859_1")), true);218219// perform the actual test220int errorCount = doTest(in, out, writeNewFile);221222// write out the error count, and throw an exception out into the environment223// if there were any errors224if (errorCount != 0) {225if (!writeNewFile)226out.println("Test failed. " + errorCount + " errors.");227if (doThrow)228throw new Exception("Test failed. " + errorCount + " errors.");229}230else if (!writeNewFile)231out.println("Test passed.");232233in.close();234out.close();235}236237static int doTest(BufferedReader in, PrintWriter out, boolean writeNewFile)238throws Exception {239int errorCount = 0;240241String key = null;242String expectedValue = null;243String line = in.readLine();244while (line != null) {245if (line.startsWith("#") || line.length() == 0) {246if (writeNewFile)247out.println(line);248}249250else {251int index = line.indexOf("=");252if (index == -1) {253key = line;254expectedValue = "";255}256else {257key = line.substring(0, index);258if (index + 1 == line.length())259expectedValue = "";260else261expectedValue = line.substring(index + 1);262}263if (!processLine(key, expectedValue, out, writeNewFile))264++errorCount;265}266line = in.readLine();267}268return errorCount;269}270271static boolean processLine(String key, String expectedValue, PrintWriter out,272boolean writeNewFile) throws Exception {273String rbName, localeName, resTag, qualifier;274String language = "", country = "", variant = "";275int index, oldIndex;276277index = key.indexOf("/");278if (index == -1 || index + 1 == key.length())279throw new Exception("Malformed input file: no slashes in \"" + key + "\"");280rbName = key.substring(0, index);281282oldIndex = index + 1;283index = key.indexOf("/", oldIndex);284if (index == -1 || index + 1 == key.length())285throw new Exception("Malformed input file: \"" + key + "\" is missing locale name");286localeName = key.substring(oldIndex, index);287boolean use_tag = localeName.indexOf("-") != -1;288if (use_tag == false && localeName.length() > 0) {289String[] locDetails = localeName.split("_");290switch (locDetails.length) {291case 1:292language = locDetails[0];293break;294case 2:295language = locDetails[0];296country = locDetails[1];297break;298case 3:299language = locDetails[0];300country = locDetails[1];301variant = locDetails[2];302break;303default:304throw new Exception("locale not specified properly " + locDetails);305}306}307oldIndex = index + 1;308index = key.indexOf("/", oldIndex);309if (index == -1)310index = key.length();311resTag = key.substring(oldIndex, index);312313// TimeZone name may have "/" in it, for example "Asia/Taipei", so use "Asia\/Taipei in LocaleData.314if(resTag.endsWith("\\")) {315resTag = resTag.substring(0, resTag.length() - 1);316oldIndex = index;317index = key.indexOf("/", oldIndex + 1);318if (index == -1) index = key.length();319resTag += key.substring(oldIndex, index);320}321322if (index < key.length() - 1)323qualifier = key.substring(index + 1);324else325qualifier = "";326327String retrievedValue = null;328Object resource = null;329try {330String fullName = null;331if (rbName.equals("CalendarData")332|| rbName.equals("CurrencyNames")333|| rbName.equals("LocaleNames")334|| rbName.equals("TimeZoneNames")) {335fullName = UTIL_RESOURCES_PACKAGE + cldrSuffix + "." + rbName;336} else {337fullName = TEXT_RESOURCES_PACKAGE + cldrSuffix + "." + rbName;338}339Locale locale;340if (use_tag) {341locale = Locale.forLanguageTag(localeName);342} else {343locale = new Locale(language, country, variant);344}345ResourceBundle bundle = LocaleData.getBundle(fullName, locale);346resource = bundle.getObject(resTag);347}348catch (MissingResourceException e) {349}350351if (resource != null) {352if (resource instanceof String) {353retrievedValue = (String)resource;354}355else if (resource instanceof String[]) {356int element = Integer.valueOf(qualifier).intValue();357String[] stringList = (String[])resource;358if (element >= 0 && element < stringList.length)359retrievedValue = stringList[element];360}361else if (resource instanceof String[][]) {362String[][] stringArray = (String[][])resource;363int slash = qualifier.indexOf("/");364if (slash == -1) {365for (int i = 0; i < stringArray.length; i++) {366if (stringArray[i][0].equals(qualifier))367retrievedValue = stringArray[i][1];368}369}370else {371int row = Integer.valueOf(qualifier.substring(0, slash)).intValue();372int column = Integer.valueOf(qualifier.substring(slash + 1)).intValue();373if (row >= 0 && row < stringArray.length && column >= 0 && column <374stringArray[row].length)375retrievedValue = stringArray[row][column];376}377}378}379380if (retrievedValue == null || !retrievedValue.equals(expectedValue)) {381if (retrievedValue == null)382retrievedValue = "<MISSING!>";383384if (writeNewFile)385out.println(key + "=" + retrievedValue);386else {387out.println("Mismatch in " + key + ":");388out.println(" file = \"" + expectedValue + "\"");389out.println(" jvm = \"" + retrievedValue + "\"");390}391return false;392}393else {394if (writeNewFile)395out.println(key + "=" + expectedValue);396}397return true;398}399}400401class EscapeReader extends FilterReader {402public EscapeReader(Reader in) {403super(in);404}405406public int read() throws IOException {407if (buffer != null) {408String b = buffer.toString();409int result = b.charAt(0);410if (b.length() > 1)411buffer = new StringBuffer(b.substring(1));412else413buffer = null;414return result;415}416else {417int result = super.read();418if (result != '\\')419return result;420else {421buffer = new StringBuffer();422result = super.read();423buffer.append((char)result);424if (result == 'u') {425for (int i = 0; i < 4; i++) {426result = super.read();427if (result == -1)428break;429buffer.append((char)result);430}431String number = buffer.toString().substring(1);432result = Integer.parseInt(number, 16);433buffer = null;434return result;435}436return '\\';437}438}439}440441public int read(char[] cbuf, int start, int len) throws IOException {442int p = start;443int end = start + len;444int c = 0;445while (c != -1 && p < end) {446c = read();447if (c != -1)448cbuf[p++] = (char)c;449}450if (c == -1 && p == start)451return -1;452else453return p - start;454}455456private StringBuffer buffer = null;457}458459class EscapeWriter extends FilterWriter {460public EscapeWriter(Writer out) {461super(out);462}463464public void write(int c) throws IOException {465if ((c >= ' ' && c <= '\u007e') || c == '\r' || c == '\n')466super.write(c);467else {468super.write('\\');469super.write('u');470String number = Integer.toHexString(c);471if (number.length() < 4)472number = zeros.substring(0, 4 - number.length()) + number;473super.write(number.charAt(0));474super.write(number.charAt(1));475super.write(number.charAt(2));476super.write(number.charAt(3));477}478}479480public void write(char[] cbuf, int off, int len) throws IOException {481int end = off + len;482while (off < end)483write(cbuf[off++]);484}485486public void write(String str, int off, int len) throws IOException {487int end = off + len;488while (off < end)489write(str.charAt(off++));490}491492private static String zeros = "0000";493}494495496