1 /*
   2  * Copyright (c) 2012, 2018, 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.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package build.tools.cldrconverter;
  27 
  28 import java.util.ArrayList;
  29 import java.util.Arrays;
  30 import java.util.EnumSet;
  31 import java.util.HashMap;
  32 import java.util.Iterator;
  33 import java.util.List;
  34 import java.util.Map;
  35 import java.util.Objects;
  36 import java.util.stream.Collectors;
  37 
  38 class Bundle {
  39     static enum Type {
  40         LOCALENAMES, CURRENCYNAMES, TIMEZONENAMES, CALENDARDATA, FORMATDATA;
  41 
  42         static EnumSet<Type> ALL_TYPES = EnumSet.of(LOCALENAMES,
  43                                                     CURRENCYNAMES,
  44                                                     TIMEZONENAMES,
  45                                                     CALENDARDATA,
  46                                                     FORMATDATA);
  47     }
  48 
  49     private final static Map<String, Bundle> bundles = new HashMap<>();
  50 
  51     private final static String[] NUMBER_PATTERN_KEYS = {
  52         "NumberPatterns/decimal",
  53         "NumberPatterns/currency",
  54         "NumberPatterns/percent"
  55     };
  56 
  57     private final static String[] COMPACT_NUMBER_PATTERN_KEYS = {
  58             "short.CompactNumberPatterns",
  59             "long.CompactNumberPatterns"};
  60 
  61     private final static String[] NUMBER_ELEMENT_KEYS = {
  62         "NumberElements/decimal",
  63         "NumberElements/group",
  64         "NumberElements/list",
  65         "NumberElements/percent",
  66         "NumberElements/zero",
  67         "NumberElements/pattern",
  68         "NumberElements/minus",
  69         "NumberElements/exponential",
  70         "NumberElements/permille",
  71         "NumberElements/infinity",
  72         "NumberElements/nan"
  73     };
  74 
  75     private final static String[] TIME_PATTERN_KEYS = {
  76         "DateTimePatterns/full-time",
  77         "DateTimePatterns/long-time",
  78         "DateTimePatterns/medium-time",
  79         "DateTimePatterns/short-time",
  80     };
  81 
  82     private final static String[] DATE_PATTERN_KEYS = {
  83         "DateTimePatterns/full-date",
  84         "DateTimePatterns/long-date",
  85         "DateTimePatterns/medium-date",
  86         "DateTimePatterns/short-date",
  87     };
  88 
  89     private final static String[] DATETIME_PATTERN_KEYS = {
  90         "DateTimePatterns/full-dateTime",
  91         "DateTimePatterns/long-dateTime",
  92         "DateTimePatterns/medium-dateTime",
  93         "DateTimePatterns/short-dateTime",
  94     };
  95 
  96     private final static String[] ERA_KEYS = {
  97         "long.Eras",
  98         "Eras",
  99         "narrow.Eras"
 100     };
 101 
 102     // Keys for individual time zone names
 103     private final static String TZ_GEN_LONG_KEY = "timezone.displayname.generic.long";
 104     private final static String TZ_GEN_SHORT_KEY = "timezone.displayname.generic.short";
 105     private final static String TZ_STD_LONG_KEY = "timezone.displayname.standard.long";
 106     private final static String TZ_STD_SHORT_KEY = "timezone.displayname.standard.short";
 107     private final static String TZ_DST_LONG_KEY = "timezone.displayname.daylight.long";
 108     private final static String TZ_DST_SHORT_KEY = "timezone.displayname.daylight.short";
 109     private final static String[] ZONE_NAME_KEYS = {
 110         TZ_STD_LONG_KEY,
 111         TZ_STD_SHORT_KEY,
 112         TZ_DST_LONG_KEY,
 113         TZ_DST_SHORT_KEY,
 114         TZ_GEN_LONG_KEY,
 115         TZ_GEN_SHORT_KEY
 116     };
 117 
 118     private final String id;
 119     private final String cldrPath;
 120     private final EnumSet<Type> bundleTypes;
 121     private final String currencies;
 122     private Map<String, Object> targetMap;
 123 
 124     static Bundle getBundle(String id) {
 125         return bundles.get(id);
 126     }
 127 
 128     @SuppressWarnings("ConvertToStringSwitch")
 129     Bundle(String id, String cldrPath, String bundles, String currencies) {
 130         this.id = id;
 131         this.cldrPath = cldrPath;
 132         if ("localenames".equals(bundles)) {
 133             bundleTypes = EnumSet.of(Type.LOCALENAMES);
 134         } else if ("currencynames".equals(bundles)) {
 135             bundleTypes = EnumSet.of(Type.CURRENCYNAMES);
 136         } else {
 137             bundleTypes = Type.ALL_TYPES;
 138         }
 139         if (currencies == null) {
 140             currencies = "local";
 141         }
 142         this.currencies = currencies;
 143         addBundle();
 144     }
 145 
 146     private void addBundle() {
 147         Bundle.bundles.put(id, this);
 148     }
 149 
 150     String getID() {
 151         return id;
 152     }
 153 
 154     String getJavaID() {
 155         // Tweak ISO compatibility for bundle generation
 156         return id.replaceFirst("^he", "iw")
 157             .replaceFirst("^id", "in")
 158             .replaceFirst("^yi", "ji");
 159     }
 160 
 161     boolean isRoot() {
 162         return "root".equals(id);
 163     }
 164 
 165     String getCLDRPath() {
 166         return cldrPath;
 167     }
 168 
 169     EnumSet<Type> getBundleTypes() {
 170         return bundleTypes;
 171     }
 172 
 173     String getCurrencies() {
 174         return currencies;
 175     }
 176 
 177     /**
 178      * Generate a map that contains all the data that should be
 179      * visible for the bundle's locale
 180      */
 181     Map<String, Object> getTargetMap() throws Exception {
 182         if (targetMap != null) {
 183             return targetMap;
 184         }
 185 
 186         String[] cldrBundles = getCLDRPath().split(",");
 187 
 188         // myMap contains resources for id.
 189         Map<String, Object> myMap = new HashMap<>();
 190         int index;
 191         for (index = 0; index < cldrBundles.length; index++) {
 192             if (cldrBundles[index].equals(id)) {
 193                 myMap.putAll(CLDRConverter.getCLDRBundle(cldrBundles[index]));
 194                 CLDRConverter.handleAliases(myMap);
 195                 break;
 196             }
 197         }
 198 
 199         // parentsMap contains resources from id's parents.
 200         Map<String, Object> parentsMap = new HashMap<>();
 201         for (int i = cldrBundles.length - 1; i > index; i--) {
 202             if (!("no".equals(cldrBundles[i]) || cldrBundles[i].startsWith("no_"))) {
 203                 parentsMap.putAll(CLDRConverter.getCLDRBundle(cldrBundles[i]));
 204                 CLDRConverter.handleAliases(parentsMap);
 205             }
 206         }
 207         // Duplicate myMap as parentsMap for "root" so that the
 208         // fallback works. This is a hack, though.
 209         if ("root".equals(cldrBundles[0])) {
 210             assert parentsMap.isEmpty();
 211             parentsMap.putAll(myMap);
 212         }
 213 
 214         // merge individual strings into arrays
 215 
 216         // if myMap has any of the NumberPatterns members
 217         for (String k : NUMBER_PATTERN_KEYS) {
 218             if (myMap.containsKey(k)) {
 219                 String[] numberPatterns = new String[NUMBER_PATTERN_KEYS.length];
 220                 for (int i = 0; i < NUMBER_PATTERN_KEYS.length; i++) {
 221                     String key = NUMBER_PATTERN_KEYS[i];
 222                     String value = (String) myMap.remove(key);
 223                     if (value == null) {
 224                         value = (String) parentsMap.remove(key);
 225                     }
 226                     if (value.length() == 0) {
 227                         CLDRConverter.warning("empty pattern for " + key);
 228                     }
 229                     numberPatterns[i] = value;
 230                 }
 231                 myMap.put("NumberPatterns", numberPatterns);
 232                 break;
 233             }
 234         }
 235 
 236         for (String k : COMPACT_NUMBER_PATTERN_KEYS) {
 237             List<String> patterns = (List<String>) myMap.remove(k);
 238             if (patterns != null) {
 239                 // Replace any null entry with empty strings.
 240                 patterns = patterns.stream()
 241                         .map(s -> s == null ? "" : s).collect(Collectors.toList());
 242                 myMap.put(k, patterns);
 243             }
 244         }
 245 
 246         // if myMap has any of NUMBER_ELEMENT_KEYS, create a complete NumberElements.
 247         String defaultScript = (String) myMap.get("DefaultNumberingSystem");
 248         @SuppressWarnings("unchecked")
 249         List<String> scripts = (List<String>) myMap.get("numberingScripts");
 250         if (defaultScript == null && scripts != null) {
 251             // Some locale data has no default script for numbering even with mutiple scripts.
 252             // Take the first one as default in that case.
 253             defaultScript = scripts.get(0);
 254             myMap.put("DefaultNumberingSystem", defaultScript);
 255         }
 256         if (scripts != null) {
 257             for (String script : scripts) {
 258                 for (String k : NUMBER_ELEMENT_KEYS) {
 259                     String[] numberElements = new String[NUMBER_ELEMENT_KEYS.length];
 260                     for (int i = 0; i < NUMBER_ELEMENT_KEYS.length; i++) {
 261                         String key = script + "." + NUMBER_ELEMENT_KEYS[i];
 262                         String value = (String) myMap.remove(key);
 263                         if (value == null) {
 264                             if (key.endsWith("/pattern")) {
 265                                 value = "#";
 266                             } else {
 267                                 value = (String) parentsMap.get(key);
 268                                 if (value == null) {
 269                                     // the last resort is "latn"
 270                                     key = "latn." + NUMBER_ELEMENT_KEYS[i];
 271                                     value = (String) parentsMap.get(key);
 272                                     if (value == null) {
 273                                         throw new InternalError("NumberElements: null for " + key);
 274                                     }
 275                                 }
 276                             }
 277                         }
 278                         numberElements[i] = value;
 279                     }
 280                     myMap.put(script + "." + "NumberElements", numberElements);
 281                     break;
 282                 }
 283             }
 284         }
 285 
 286         // another hack: parentsMap is not used for date-time resources.
 287         if ("root".equals(id)) {
 288             parentsMap = null;
 289         }
 290 
 291         for (CalendarType calendarType : CalendarType.values()) {
 292             String calendarPrefix = calendarType.keyElementName();
 293             // handle multiple inheritance for month and day names
 294             handleMultipleInheritance(myMap, parentsMap, calendarPrefix + "MonthNames");
 295             handleMultipleInheritance(myMap, parentsMap, calendarPrefix + "MonthAbbreviations");
 296             handleMultipleInheritance(myMap, parentsMap, calendarPrefix + "MonthNarrows");
 297             handleMultipleInheritance(myMap, parentsMap, calendarPrefix + "DayNames");
 298             handleMultipleInheritance(myMap, parentsMap, calendarPrefix + "DayAbbreviations");
 299             handleMultipleInheritance(myMap, parentsMap, calendarPrefix + "DayNarrows");
 300             handleMultipleInheritance(myMap, parentsMap, calendarPrefix + "AmPmMarkers");
 301             handleMultipleInheritance(myMap, parentsMap, calendarPrefix + "narrow.AmPmMarkers");
 302             handleMultipleInheritance(myMap, parentsMap, calendarPrefix + "abbreviated.AmPmMarkers");
 303             handleMultipleInheritance(myMap, parentsMap, calendarPrefix + "QuarterNames");
 304             handleMultipleInheritance(myMap, parentsMap, calendarPrefix + "QuarterAbbreviations");
 305             handleMultipleInheritance(myMap, parentsMap, calendarPrefix + "QuarterNarrows");
 306 
 307             adjustEraNames(myMap, calendarType);
 308 
 309             handleDateTimeFormatPatterns(TIME_PATTERN_KEYS, myMap, parentsMap, calendarType, "TimePatterns");
 310             handleDateTimeFormatPatterns(DATE_PATTERN_KEYS, myMap, parentsMap, calendarType, "DatePatterns");
 311             handleDateTimeFormatPatterns(DATETIME_PATTERN_KEYS, myMap, parentsMap, calendarType, "DateTimePatterns");
 312         }
 313 
 314         // First, weed out any empty timezone or metazone names from myMap.
 315         // Fill in any missing abbreviations if locale is "en".
 316         for (Iterator<String> it = myMap.keySet().iterator(); it.hasNext();) {
 317             String key = it.next();
 318             if (key.startsWith(CLDRConverter.TIMEZONE_ID_PREFIX)
 319                     || key.startsWith(CLDRConverter.METAZONE_ID_PREFIX)) {
 320                 @SuppressWarnings("unchecked")
 321                 Map<String, String> nameMap = (Map<String, String>) myMap.get(key);
 322                 if (nameMap.isEmpty()) {
 323                     // Some zones have only exemplarCity, which become empty.
 324                     // Remove those from the map.
 325                     it.remove();
 326                     continue;
 327                 }
 328 
 329                 if (id.equals("en")) {
 330                     fillInJREs(key, nameMap);
 331                 }
 332             }
 333         }
 334         for (Iterator<String> it = myMap.keySet().iterator(); it.hasNext();) {
 335             String key = it.next();
 336                 if (key.startsWith(CLDRConverter.TIMEZONE_ID_PREFIX)
 337                     || key.startsWith(CLDRConverter.METAZONE_ID_PREFIX)) {
 338                 @SuppressWarnings("unchecked")
 339                 Map<String, String> nameMap = (Map<String, String>) myMap.get(key);
 340 
 341                 // Convert key/value pairs to an array.
 342                 String[] names = new String[ZONE_NAME_KEYS.length];
 343                 int ix = 0;
 344                 for (String nameKey : ZONE_NAME_KEYS) {
 345                     String name = nameMap.get(nameKey);
 346                     if (name == null && parentsMap != null) {
 347                         @SuppressWarnings("unchecked")
 348                         Map<String, String> parentNames = (Map<String, String>) parentsMap.get(key);
 349                         if (parentNames != null) {
 350                             name = parentNames.get(nameKey);
 351                         }
 352                     }
 353                     names[ix++] = name;
 354                 }
 355                 if (hasNulls(names)) {
 356                     String metaKey = toMetaZoneKey(key);
 357                     if (metaKey != null) {
 358                         Object obj = myMap.get(metaKey);
 359                         if (obj instanceof String[]) {
 360                             String[] metaNames = (String[]) obj;
 361                             for (int i = 0; i < names.length; i++) {
 362                                 if (names[i] == null) {
 363                                     names[i] = metaNames[i];
 364                                 }
 365                             }
 366                         } else if (obj instanceof Map) {
 367                             @SuppressWarnings("unchecked")
 368                             Map<String, String> m = (Map<String, String>) obj;
 369                             for (int i = 0; i < names.length; i++) {
 370                                 if (names[i] == null) {
 371                                     names[i] = m.get(ZONE_NAME_KEYS[i]);
 372                                 }
 373                             }
 374                         }
 375                     }
 376                 }
 377                 // replace the Map with the array
 378                 if (names != null) {
 379                     myMap.put(key, names);
 380                 } else {
 381                     it.remove();
 382                 }
 383             }
 384         }
 385         // replace empty era names with parentMap era names
 386         for (String key : ERA_KEYS) {
 387             Object value = myMap.get(key);
 388             if (value != null && value instanceof String[]) {
 389                 String[] eraStrings = (String[]) value;
 390                 for (String eraString : eraStrings) {
 391                     if (eraString == null || eraString.isEmpty()) {
 392                         fillInElements(parentsMap, key, value);
 393                     }
 394                 }
 395             }
 396         }
 397 
 398         // Remove all duplicates
 399         if (Objects.nonNull(parentsMap)) {
 400             for (Iterator<String> it = myMap.keySet().iterator(); it.hasNext();) {
 401                 String key = it.next();
 402                 if (!key.equals("numberingScripts") && // real body "NumberElements" may differ
 403                     Objects.deepEquals(parentsMap.get(key), myMap.get(key))) {
 404                     it.remove();
 405                 }
 406             }
 407         }
 408 
 409         targetMap = myMap;
 410         return myMap;
 411     }
 412 
 413     private void handleMultipleInheritance(Map<String, Object> map, Map<String, Object> parents, String key) {
 414         String formatKey = key + "/format";
 415         Object format = map.get(formatKey);
 416         if (format != null) {
 417             map.remove(formatKey);
 418             map.put(key, format);
 419             if (fillInElements(parents, formatKey, format)) {
 420                 map.remove(key);
 421             }
 422         }
 423         String standaloneKey = key + "/stand-alone";
 424         Object standalone = map.get(standaloneKey);
 425         if (standalone != null) {
 426             map.remove(standaloneKey);
 427             String realKey = key;
 428             if (format != null) {
 429                 realKey = "standalone." + key;
 430             }
 431             map.put(realKey, standalone);
 432             if (fillInElements(parents, standaloneKey, standalone)) {
 433                 map.remove(realKey);
 434             }
 435         }
 436     }
 437 
 438     /**
 439      * Fills in any empty elements with its parent element. Returns true if the resulting array is
 440      * identical to its parent array.
 441      *
 442      * @param parents
 443      * @param key
 444      * @param value
 445      * @return true if the resulting array is identical to its parent array.
 446      */
 447     private boolean fillInElements(Map<String, Object> parents, String key, Object value) {
 448         if (parents == null) {
 449             return false;
 450         }
 451         if (value instanceof String[]) {
 452             Object pvalue = parents.get(key);
 453             if (pvalue != null && pvalue instanceof String[]) {
 454                 String[] strings = (String[]) value;
 455                 String[] pstrings = (String[]) pvalue;
 456                 for (int i = 0; i < strings.length; i++) {
 457                     if (strings[i] == null || strings[i].length() == 0) {
 458                         strings[i] = pstrings[i];
 459                     }
 460                 }
 461                 return Arrays.equals(strings, pstrings);
 462             }
 463         }
 464         return false;
 465     }
 466 
 467     /*
 468      * Adjusts String[] for era names because JRE's Calendars use different
 469      * ERA value indexes in the Buddhist, Japanese Imperial, and Islamic calendars.
 470      */
 471     private void adjustEraNames(Map<String, Object> map, CalendarType type) {
 472         String[][] eraNames = new String[ERA_KEYS.length][];
 473         String[] realKeys = new String[ERA_KEYS.length];
 474         int index = 0;
 475         for (String key : ERA_KEYS) {
 476             String realKey = type.keyElementName() + key;
 477             String[] value = (String[]) map.get(realKey);
 478             if (value != null) {
 479                 switch (type) {
 480                 case GREGORIAN:
 481                     break;
 482 
 483                 case JAPANESE:
 484                     {
 485                         String[] newValue = new String[value.length + 1];
 486                         String[] julianEras = (String[]) map.get(key);
 487                         if (julianEras != null && julianEras.length >= 2) {
 488                             newValue[0] = julianEras[1];
 489                         } else {
 490                             newValue[0] = "";
 491                         }
 492                         System.arraycopy(value, 0, newValue, 1, value.length);
 493                         value = newValue;
 494                     }
 495                     break;
 496 
 497                 case BUDDHIST:
 498                     // Replace the value
 499                     value = new String[] {"BC", value[0]};
 500                     break;
 501 
 502                 case ISLAMIC:
 503                     // Replace the value
 504                     value = new String[] {"", value[0]};
 505                     break;
 506                 }
 507                 if (!key.equals(realKey)) {
 508                     map.put(realKey, value);
 509                 }
 510             }
 511             realKeys[index] = realKey;
 512             eraNames[index++] = value;
 513         }
 514         for (int i = 0; i < eraNames.length; i++) {
 515             if (eraNames[i] == null) {
 516                 map.put(realKeys[i], null);
 517             }
 518         }
 519     }
 520 
 521     private void handleDateTimeFormatPatterns(String[] patternKeys, Map<String, Object> myMap, Map<String, Object> parentsMap,
 522                                               CalendarType calendarType, String name) {
 523         String calendarPrefix = calendarType.keyElementName();
 524         for (String k : patternKeys) {
 525             if (myMap.containsKey(calendarPrefix + k)) {
 526                 int len = patternKeys.length;
 527                 List<String> rawPatterns = new ArrayList<>(len);
 528                 List<String> patterns = new ArrayList<>(len);
 529                 for (int i = 0; i < len; i++) {
 530                     String key = calendarPrefix + patternKeys[i];
 531                     String pattern = (String) myMap.remove(key);
 532                     if (pattern == null) {
 533                         pattern = (String) parentsMap.remove(key);
 534                     }
 535                     rawPatterns.add(i, pattern);
 536                     if (pattern != null) {
 537                         patterns.add(i, translateDateFormatLetters(calendarType, pattern));
 538                     } else {
 539                         patterns.add(i, null);
 540                     }
 541                 }
 542                 // If patterns is empty or has any nulls, discard patterns.
 543                 if (patterns.isEmpty()) {
 544                     return;
 545                 }
 546                 String key = calendarPrefix + name;
 547                 if (!rawPatterns.equals(patterns)) {
 548                     myMap.put("java.time." + key, rawPatterns.toArray(new String[len]));
 549                 }
 550                 myMap.put(key, patterns.toArray(new String[len]));
 551                 break;
 552             }
 553         }
 554     }
 555 
 556     private String translateDateFormatLetters(CalendarType calendarType, String cldrFormat) {
 557         String pattern = cldrFormat;
 558         int length = pattern.length();
 559         boolean inQuote = false;
 560         StringBuilder jrePattern = new StringBuilder(length);
 561         int count = 0;
 562         char lastLetter = 0;
 563 
 564         for (int i = 0; i < length; i++) {
 565             char c = pattern.charAt(i);
 566 
 567             if (c == '\'') {
 568                 // '' is treated as a single quote regardless of being
 569                 // in a quoted section.
 570                 if ((i + 1) < length) {
 571                     char nextc = pattern.charAt(i + 1);
 572                     if (nextc == '\'') {
 573                         i++;
 574                         if (count != 0) {
 575                             convert(calendarType, lastLetter, count, jrePattern);
 576                             lastLetter = 0;
 577                             count = 0;
 578                         }
 579                         jrePattern.append("''");
 580                         continue;
 581                     }
 582                 }
 583                 if (!inQuote) {
 584                     if (count != 0) {
 585                         convert(calendarType, lastLetter, count, jrePattern);
 586                         lastLetter = 0;
 587                         count = 0;
 588                     }
 589                     inQuote = true;
 590                 } else {
 591                     inQuote = false;
 592                 }
 593                 jrePattern.append(c);
 594                 continue;
 595             }
 596             if (inQuote) {
 597                 jrePattern.append(c);
 598                 continue;
 599             }
 600             if (!(c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z')) {
 601                 if (count != 0) {
 602                     convert(calendarType, lastLetter, count, jrePattern);
 603                     lastLetter = 0;
 604                     count = 0;
 605                 }
 606                 jrePattern.append(c);
 607                 continue;
 608             }
 609 
 610             if (lastLetter == 0 || lastLetter == c) {
 611                 lastLetter = c;
 612                 count++;
 613                 continue;
 614             }
 615             convert(calendarType, lastLetter, count, jrePattern);
 616             lastLetter = c;
 617             count = 1;
 618         }
 619 
 620         if (inQuote) {
 621             throw new InternalError("Unterminated quote in date-time pattern: " + cldrFormat);
 622         }
 623 
 624         if (count != 0) {
 625             convert(calendarType, lastLetter, count, jrePattern);
 626         }
 627         if (cldrFormat.contentEquals(jrePattern)) {
 628             return cldrFormat;
 629         }
 630         return jrePattern.toString();
 631     }
 632 
 633     private String toMetaZoneKey(String tzKey) {
 634         if (tzKey.startsWith(CLDRConverter.TIMEZONE_ID_PREFIX)) {
 635             String tz = tzKey.substring(CLDRConverter.TIMEZONE_ID_PREFIX.length());
 636             String meta = CLDRConverter.handlerMetaZones.get(tz);
 637             if (meta != null) {
 638                 return CLDRConverter.METAZONE_ID_PREFIX + meta;
 639             }
 640         }
 641         return null;
 642     }
 643 
 644     static List<Object[]> jreTimeZoneNames = Arrays.asList(TimeZoneNames.getContents());
 645     private void fillInJREs(String key, Map<String, String> map) {
 646         String tzid = null;
 647 
 648         if (key.startsWith(CLDRConverter.METAZONE_ID_PREFIX)) {
 649             // Look for tzid
 650             String meta = key.substring(CLDRConverter.METAZONE_ID_PREFIX.length());
 651             if (meta.equals("GMT")) {
 652                 tzid = meta;
 653             } else {
 654                 for (String tz : CLDRConverter.handlerMetaZones.keySet()) {
 655                     if (CLDRConverter.handlerMetaZones.get(tz).equals(meta)) {
 656                         tzid = tz;
 657                         break;
 658                     }
 659                 }
 660             }
 661         } else {
 662             tzid = key.substring(CLDRConverter.TIMEZONE_ID_PREFIX.length());
 663         }
 664 
 665         if (tzid != null) {
 666             for (Object[] jreZone : jreTimeZoneNames) {
 667                 if (jreZone[0].equals(tzid)) {
 668                     for (int i = 0; i < ZONE_NAME_KEYS.length; i++) {
 669                         if (map.get(ZONE_NAME_KEYS[i]) == null) {
 670                             String[] jreNames = (String[])jreZone[1];
 671                             map.put(ZONE_NAME_KEYS[i], jreNames[i]);
 672                         }
 673                     }
 674                     break;
 675                 }
 676             }
 677         }
 678     }
 679 
 680     private void convert(CalendarType calendarType, char cldrLetter, int count, StringBuilder sb) {
 681         switch (cldrLetter) {
 682         case 'G':
 683             if (calendarType != CalendarType.GREGORIAN) {
 684                 // Adjust the number of 'G's for JRE SimpleDateFormat
 685                 if (count == 5) {
 686                     // CLDR narrow -> JRE short
 687                     count = 1;
 688                 } else if (count == 1) {
 689                     // CLDR abbr -> JRE long
 690                     count = 4;
 691                 }
 692             }
 693             appendN(cldrLetter, count, sb);
 694             break;
 695 
 696         // TODO: support 'c' and 'e' in JRE SimpleDateFormat
 697         // Use 'u' and 'E' for now.
 698         case 'c':
 699         case 'e':
 700             switch (count) {
 701             case 1:
 702                 sb.append('u');
 703                 break;
 704             case 3:
 705             case 4:
 706                 appendN('E', count, sb);
 707                 break;
 708             case 5:
 709                 appendN('E', 3, sb);
 710                 break;
 711             }
 712             break;
 713 
 714         case 'l':
 715             // 'l' is deprecated as a pattern character. Should be ignored.
 716             break;
 717 
 718         case 'u':
 719             // Use 'y' for now.
 720             appendN('y', count, sb);
 721             break;
 722 
 723         case 'v':
 724         case 'V':
 725             appendN('z', count, sb);
 726             break;
 727 
 728         case 'Z':
 729             if (count == 4 || count == 5) {
 730                 sb.append("XXX");
 731             }
 732             break;
 733 
 734         case 'U':
 735         case 'q':
 736         case 'Q':
 737         case 'g':
 738         case 'j':
 739         case 'A':
 740             throw new InternalError(String.format("Unsupported letter: '%c', count=%d, id=%s%n",
 741                                                   cldrLetter, count, id));
 742         default:
 743             appendN(cldrLetter, count, sb);
 744             break;
 745         }
 746     }
 747 
 748     private void appendN(char c, int n, StringBuilder sb) {
 749         for (int i = 0; i < n; i++) {
 750             sb.append(c);
 751         }
 752     }
 753 
 754     private static boolean hasNulls(Object[] array) {
 755         for (int i = 0; i < array.length; i++) {
 756             if (array[i] == null) {
 757                 return true;
 758             }
 759         }
 760         return false;
 761     }
 762 }