1 /*
   2  * Copyright (c) 2007, 2017, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  */
  23 /*
  24  * @test
  25  * @bug 4052473 4052679 4055602 4066550 4067619 4068012 4068073 4070174 4070452
  26  *      4070178 4070450 4070695 4070725 4070795 4071003 4071183 4071782 4072013
  27  *      4072388 4072773 4075404 4084356 4087238 4092361 4094033 4094371 4098518
  28  *      4099810 4103218 4103220 4103861 4112136 4113638 4113654 4117054 4122468
  29  *      4122840 4139860 4156708 4175306 4215747 4209960 4290801 4900884 4942982
  30  *      4518811 4945388 4936845 4794068 4461740 4965260 4984277 4826794 5032580
  31  *      5102005 5074431 6182685 6208712 6277020 6245766 6351682 6386647 6379382
  32  *      6414459 6455680 6498742 6558863 6488119 6547501 6497154 6558856 6481177
  33  *      6379214 6485516 6486607 4225362 4494727 6533691 6531591 6531593 6570259
  34  *      6509039 6609737 6610748 6645271 6507067 6873931 6450945 6645268 6646611
  35  *      6645405 6650730 6910489 6573250 6870908 6585666 6716626 6914413 6916787
  36  *      6919624 6998391 7019267 7020960 7025837 7020583 7036905 7066203 7101495
  37  *      7003124 7085757 7028073 7171028 7189611 8000983 7195759 8004489 8006509
  38  *      7114053 7074882 7040556 8008577 8013836 8021121 6192407 6931564 8027695
  39  *      8017142 8037343 8055222 8042126 8074791 8075173 8080774 8129361 8134916
  40  *      8145136 8145952 8164784 8037111 8081643 7037368 8178872 8185841 8190918
  41  *      8187946 8195478
  42  * @summary Verify locale data
  43  * @modules java.base/sun.util.resources
  44  * @modules jdk.localedata
  45  * @run main LocaleDataTest
  46  * @run main LocaleDataTest -cldr
  47  *
  48  */
  49 
  50 /*
  51  *
  52  * (C) Copyright Taligent, Inc. 1996, 1997 - All Rights Reserved
  53  * (C) Copyright IBM Corp. 1996 - 1998 - All Rights Reserved
  54  *
  55  * Portions copyright (c) 2007 Sun Microsystems, Inc.
  56  * All Rights Reserved.
  57  *
  58  * The original version of this source code and documentation
  59  * is copyrighted and owned by Taligent, Inc., a wholly-owned
  60  * subsidiary of IBM. These materials are provided under terms
  61  * of a License Agreement between Taligent and Sun. This technology
  62  * is protected by multiple US and International patents.
  63  *
  64  * This notice and attribution to Taligent may not be removed.
  65  * Taligent is a registered trademark of Taligent, Inc.
  66  *
  67  * Permission to use, copy, modify, and distribute this software
  68  * and its documentation for NON-COMMERCIAL purposes and without
  69  * fee is hereby granted provided that this copyright notice
  70  * appears in all copies. Please refer to the file "copyright.html"
  71  * for further important copyright and licensing information.
  72  *
  73  * SUN MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF
  74  * THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
  75  * TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
  76  * PARTICULAR PURPOSE, OR NON-INFRINGEMENT. SUN SHALL NOT BE LIABLE FOR
  77  * ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR
  78  * DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
  79  *
  80  */
  81 
  82 /*    This test is a generalized test for verifying changes to the locale data.
  83  *    It is driven by an external file that specifies the particular pieces of locale
  84  *    data to check.  That file is in .properties file format: a series of key/value
  85  *    pairs delimited by newline characters, with the keys separated from the values
  86  *    by = signs.  The keys are similar in syntax to a Unix pathname, with keys at
  87  *    successive levels of containment in the resource-data hierarchy separated by
  88  *    slashes.  The file is in ISO 8859-1 encoding, with control characters and
  89  *    non-ASCII characters denoted with backslash-u escape sequences.  The program also allows
  90  *    blank lines and comment lines to be interspersed with the data.  Comment lines
  91  *    begin with '#'.
  92  *
  93  *    A data file for this test would look something like this:<pre>
  94  *        FormatData//MonthNames/0=January
  95  *        FormatData//MonthNames/1=February
  96  *        LocaleNames//US=United States
  97  *        LocaleNames//FR=France
  98  *        FormatData/fr_FR/MonthNames/0=janvier
  99  *        FormatData/fr_FR/MonthNames/1=f\u00e9vrier
 100  *        LocaleNames/fr_FR/US=\u00c9tats-Unis
 101  *        LocaleNames/fr_FR/FR=France</pre>
 102  *
 103  *    Second field which designates locale is in the form of:
 104  *    1) Legacy locale notation using '_' as a locale component(language/country/variant) separator.
 105  *    language is a mandatory component. country and variant are optional, however,
 106  *    variant cannot exist without country. So for example, while "ja"/"ja_JP"/"ja_JP_JP" are valid,
 107  *    "_JP"/"ja__JP" are invalid.
 108  *
 109  *    2) BCP47 language tag notation in which we can specify language tag with '-' as a subtag
 110  *       separator. Language tag can be specified with '-' in locale field like this:
 111  *       <pre>LocaleNames/sr-Latn/SR=Surinam
 112  *        FormatData/sr-Latn-BA/DayNames/2=utorak</pre>
 113  *
 114  *    The command-line syntax of this test is
 115  *        <tt>java LocaleDataTest [-w] [{ -s | <filename> }] [-cldr]</tt>
 116  *
 117  *    This program always sends its results to standard output.   If -w is not specified,
 118  *    this program prints out only the differences between the data file and the actual
 119  *    resource data.  If -w is specified, the program prints out every entry, comment,
 120  *    and blank line from the data file.  Where there is a difference between the data
 121  *    file and the resource data, the data is the data from the resources.  This feature
 122  *    can be used to quickly generate a new data file.
 123  *
 124  *    The user can specify an optional filename or -s.  If the user specifies a filename,
 125  *    the program uses that file as the data file.  If the user specifies -s, the program
 126  *    reads its input from standard input rather than from a file.  If the user specifies
 127  *    neither, the program reads its input from a file called LocaleData in the same
 128  *    directory the program itself resides in.
 129  *
 130  *    The -nothrow option prevents the program from throwing an exception when it
 131  *    gets an error.  -w implies -nothrow.
 132  *
 133  *    -cldr option specifies to test CLDR locale data. The default data file name for this
 134  *    option is "LocaleData.cldr".
 135  *
 136  *    Other command-line options can be specified, but are ignored.
 137  *
 138  *    It's important to note what this test will NOT test.  Certain changes to the locale
 139  *    data are meant to have certain effects on the internationalization frameworks.  For
 140  *    instance, we could ensure round-trip formatting/parsing integrity for the full
 141  *    date/time format of SimpleDateFormat by making sure that the full date and time
 142  *    patterns include sufficient data.  The test of this is not whether changes were
 143  *    made to the locale data; it's whether using this data gives round-trip integrity.
 144  *    Likewise, changing the currency patterns to use \u00a4 instead of local currency
 145  *    symbols isn't something that can be tested by this test; instead, you want to
 146  *    actually format currency values and make sure the proper currency symbol was used.
 147  *
 148  *    This test by itself doesn't do an exhaustive comparison of locale data.  It is
 149  *    possible to do this manually, however:  Use the GenerateKeyList tool to produce
 150  *    a complete list of keys for the two versions of the locales you want to compare,
 151  *    and then diff them.  This will flag additions and deletions.  Generate a data file
 152  *    for the base version of the data using the -w option and the output from
 153  *    GenerateKeyList, and then use the resultant file as the data file when you run
 154  *    this test against the new version of the data.
 155  */
 156 
 157 import java.io.BufferedReader;
 158 import java.io.File;
 159 import java.io.FileInputStream;
 160 import java.io.FilterReader;
 161 import java.io.FilterWriter;
 162 import java.io.IOException;
 163 import java.io.InputStreamReader;
 164 import java.io.OutputStreamWriter;
 165 import java.io.PrintWriter;
 166 import java.io.Reader;
 167 import java.io.Writer;
 168 import java.util.Locale;
 169 import java.util.MissingResourceException;
 170 import java.util.ResourceBundle;
 171 import sun.util.resources.LocaleData;
 172 
 173 public class LocaleDataTest
 174 {
 175     static final String TEXT_RESOURCES_PACKAGE ="sun.text.resources";
 176     static final String UTIL_RESOURCES_PACKAGE ="sun.util.resources";
 177     static final String DEFAULT_DATAFILE ="LocaleData";
 178     static String cldrSuffix = "";
 179 
 180     public static void main(String[] args) throws Exception {
 181 
 182         // set up our flags and our input and output streams based on the
 183         // command-line arguments (exceptions generated here will propagate out
 184         // to the environment)
 185         BufferedReader in = null;
 186         PrintWriter out = null;
 187         boolean writeNewFile = false;
 188         boolean doThrow = true;
 189 
 190         for (int i = 0; i < args.length; i++) {
 191             if (args[i].equals("-w")) {
 192                 writeNewFile = true;
 193                 doThrow = false;
 194             }
 195 
 196             else if (args[i].equals("-nothrow"))
 197                 doThrow = false;
 198 
 199             else if (args[i].equals("-cldr")) {
 200                 cldrSuffix = ".cldr";
 201             }
 202 
 203             else if (args[i].equals("-s") && in == null)
 204                 in = new BufferedReader(new EscapeReader(new InputStreamReader(System.in,
 205                                 "ISO8859_1")));
 206             else if (!args[i].startsWith("-") && in == null)
 207                 in = new BufferedReader(new EscapeReader(new InputStreamReader(new
 208                                 FileInputStream(args[i]), "ISO8859_1")));
 209         }
 210         if (in == null) {
 211             File localeData = new File(System.getProperty("test.src", "."), DEFAULT_DATAFILE + cldrSuffix);
 212             in = new BufferedReader(new EscapeReader(new InputStreamReader(new
 213                             FileInputStream(localeData), "ISO8859_1")));
 214         }
 215         out = new PrintWriter(new EscapeWriter(new OutputStreamWriter(System.out,
 216                         "ISO8859_1")), true);
 217 
 218         // perform the actual test
 219         int errorCount = doTest(in, out, writeNewFile);
 220 
 221         // write out the error count, and throw an exception out into the environment
 222         // if there were any errors
 223         if (errorCount != 0) {
 224             if (!writeNewFile)
 225                 out.println("Test failed.  " + errorCount + " errors.");
 226             if (doThrow)
 227                 throw new Exception("Test failed.  " + errorCount + " errors.");
 228         }
 229         else if (!writeNewFile)
 230             out.println("Test passed.");
 231 
 232         in.close();
 233         out.close();
 234     }
 235 
 236     static int doTest(BufferedReader in, PrintWriter out, boolean writeNewFile)
 237                     throws Exception {
 238         int errorCount = 0;
 239 
 240         String key = null;
 241         String expectedValue = null;
 242         String line = in.readLine();
 243         while (line != null) {
 244             if (line.startsWith("#") || line.length() == 0) {
 245                 if (writeNewFile)
 246                     out.println(line);
 247             }
 248 
 249             else {
 250                 int index  = line.indexOf("=");
 251                 if (index == -1) {
 252                     key = line;
 253                     expectedValue = "";
 254                 }
 255                 else {
 256                     key = line.substring(0, index);
 257                     if (index + 1 == line.length())
 258                         expectedValue = "";
 259                     else
 260                         expectedValue = line.substring(index + 1);
 261                 }
 262                 if (!processLine(key, expectedValue, out, writeNewFile))
 263                     ++errorCount;
 264             }
 265             line = in.readLine();
 266         }
 267         return errorCount;
 268     }
 269 
 270     static boolean processLine(String key, String expectedValue, PrintWriter out,
 271                     boolean writeNewFile) throws Exception {
 272         String rbName, localeName, resTag, qualifier;
 273         String language = "", country = "", variant = "";
 274         int index, oldIndex;
 275 
 276         index = key.indexOf("/");
 277         if (index == -1 || index + 1 == key.length())
 278             throw new Exception("Malformed input file: no slashes in \"" + key + "\"");
 279         rbName = key.substring(0, index);
 280 
 281         oldIndex = index + 1;
 282         index = key.indexOf("/", oldIndex);
 283         if (index == -1 || index + 1 == key.length())
 284             throw new Exception("Malformed input file: \"" + key + "\" is missing locale name");
 285         localeName = key.substring(oldIndex, index);
 286         boolean use_tag = localeName.indexOf("-") != -1;
 287         if (use_tag == false && localeName.length() > 0) {
 288             String[] locDetails = localeName.split("_");
 289             switch (locDetails.length) {
 290                 case 1:
 291                     language = locDetails[0];
 292                     break;
 293                 case 2:
 294                     language = locDetails[0];
 295                     country = locDetails[1];
 296                     break;
 297                 case 3:
 298                     language = locDetails[0];
 299                     country = locDetails[1];
 300                     variant = locDetails[2];
 301                     break;
 302                 default:
 303                     throw new Exception("locale not specified properly " + locDetails);
 304             }
 305         }
 306         oldIndex = index + 1;
 307         index = key.indexOf("/", oldIndex);
 308         if (index == -1)
 309             index = key.length();
 310         resTag = key.substring(oldIndex, index);
 311 
 312         // TimeZone name may have "/" in it, for example "Asia/Taipei", so use "Asia\/Taipei in LocaleData.
 313         if(resTag.endsWith("\\")) {
 314             resTag = resTag.substring(0, resTag.length() - 1);
 315             oldIndex = index;
 316             index = key.indexOf("/", oldIndex + 1);
 317             if (index == -1) index = key.length();
 318             resTag += key.substring(oldIndex, index);
 319         }
 320 
 321         if (index < key.length() - 1)
 322             qualifier = key.substring(index + 1);
 323         else
 324             qualifier = "";
 325 
 326         String retrievedValue = null;
 327         Object resource = null;
 328         try {
 329             String fullName = null;
 330             if (rbName.equals("CalendarData")
 331                     || rbName.equals("CurrencyNames")
 332                     || rbName.equals("LocaleNames")
 333                     || rbName.equals("TimeZoneNames")) {
 334                 fullName = UTIL_RESOURCES_PACKAGE + cldrSuffix + "." + rbName;
 335             } else {
 336                 fullName = TEXT_RESOURCES_PACKAGE + cldrSuffix + "." + rbName;
 337             }
 338             Locale locale;
 339             if (use_tag) {
 340                 locale = Locale.forLanguageTag(localeName);
 341             } else {
 342                 locale = new Locale(language, country, variant);
 343             }
 344             ResourceBundle bundle = LocaleData.getBundle(fullName, locale);
 345             resource = bundle.getObject(resTag);
 346         }
 347         catch (MissingResourceException e) {
 348         }
 349 
 350         if (resource != null) {
 351             if (resource instanceof String) {
 352                 retrievedValue = (String)resource;
 353             }
 354             else if (resource instanceof String[]) {
 355                 int element = Integer.valueOf(qualifier).intValue();
 356                 String[] stringList = (String[])resource;
 357                 if (element >= 0 && element < stringList.length)
 358                     retrievedValue = stringList[element];
 359             }
 360             else if (resource instanceof String[][]) {
 361                 String[][] stringArray = (String[][])resource;
 362                 int slash = qualifier.indexOf("/");
 363                 if (slash == -1) {
 364                     for (int i = 0; i < stringArray.length; i++) {
 365                         if (stringArray[i][0].equals(qualifier))
 366                             retrievedValue = stringArray[i][1];
 367                     }
 368                 }
 369                 else {
 370                     int row = Integer.valueOf(qualifier.substring(0, slash)).intValue();
 371                     int column = Integer.valueOf(qualifier.substring(slash + 1)).intValue();
 372                     if (row >= 0 && row < stringArray.length && column >= 0 && column <
 373                                     stringArray[row].length)
 374                         retrievedValue = stringArray[row][column];
 375                 }
 376             }
 377         }
 378 
 379         if (retrievedValue == null || !retrievedValue.equals(expectedValue)) {
 380             if (retrievedValue == null)
 381                 retrievedValue = "<MISSING!>";
 382 
 383             if (writeNewFile)
 384                 out.println(key + "=" + retrievedValue);
 385             else {
 386                 out.println("Mismatch in " + key + ":");
 387                 out.println("  file = \"" + expectedValue + "\"");
 388                 out.println("   jvm = \"" + retrievedValue + "\"");
 389             }
 390             return false;
 391         }
 392         else {
 393             if (writeNewFile)
 394                 out.println(key + "=" + expectedValue);
 395         }
 396         return true;
 397     }
 398 }
 399 
 400 class EscapeReader extends FilterReader {
 401     public EscapeReader(Reader in) {
 402         super(in);
 403     }
 404 
 405     public int read() throws IOException {
 406         if (buffer != null) {
 407             String b = buffer.toString();
 408             int result = b.charAt(0);
 409             if (b.length() > 1)
 410                 buffer = new StringBuffer(b.substring(1));
 411             else
 412                 buffer = null;
 413             return result;
 414         }
 415         else {
 416             int result = super.read();
 417             if (result != '\\')
 418                 return result;
 419             else {
 420                 buffer = new StringBuffer();
 421                 result = super.read();
 422                 buffer.append((char)result);
 423                 if (result == 'u') {
 424                     for (int i = 0; i < 4; i++) {
 425                         result = super.read();
 426                         if (result == -1)
 427                             break;
 428                         buffer.append((char)result);
 429                     }
 430                     String number = buffer.toString().substring(1);
 431                     result = Integer.parseInt(number, 16);
 432                     buffer = null;
 433                     return result;
 434                 }
 435                 return '\\';
 436             }
 437         }
 438     }
 439 
 440     public int read(char[] cbuf, int start, int len) throws IOException {
 441         int p = start;
 442         int end = start + len;
 443         int c = 0;
 444         while (c != -1 && p < end) {
 445             c = read();
 446             if (c != -1)
 447                 cbuf[p++] = (char)c;
 448         }
 449         if (c == -1 && p == start)
 450             return -1;
 451         else
 452             return p - start;
 453     }
 454 
 455     private StringBuffer buffer = null;
 456 }
 457 
 458 class EscapeWriter extends FilterWriter {
 459     public EscapeWriter(Writer out) {
 460         super(out);
 461     }
 462 
 463     public void write(int c) throws IOException {
 464         if ((c >= ' ' && c <= '\u007e') || c == '\r' || c == '\n')
 465             super.write(c);
 466         else {
 467             super.write('\\');
 468             super.write('u');
 469             String number = Integer.toHexString(c);
 470             if (number.length() < 4)
 471                 number = zeros.substring(0, 4 - number.length()) + number;
 472             super.write(number.charAt(0));
 473             super.write(number.charAt(1));
 474             super.write(number.charAt(2));
 475             super.write(number.charAt(3));
 476         }
 477     }
 478 
 479     public void write(char[] cbuf, int off, int len) throws IOException {
 480         int end = off + len;
 481         while (off < end)
 482             write(cbuf[off++]);
 483     }
 484 
 485     public void write(String str, int off, int len) throws IOException {
 486         int end = off + len;
 487         while (off < end)
 488             write(str.charAt(off++));
 489     }
 490 
 491     private static String zeros = "0000";
 492 }