1 /*
   2  * Copyright (c) 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 sun.util.cldr;
  27 
  28 import static sun.util.locale.provider.LocaleProviderAdapter.Type;
  29 
  30 import java.text.MessageFormat;
  31 import java.util.Arrays;
  32 import java.util.Locale;
  33 import java.util.Objects;
  34 import java.util.ResourceBundle;
  35 import java.util.Set;
  36 import java.util.TimeZone;
  37 import java.util.stream.Collectors;
  38 import sun.util.calendar.ZoneInfoFile;
  39 import sun.util.locale.provider.LocaleProviderAdapter;
  40 import sun.util.locale.provider.LocaleResources;
  41 import sun.util.locale.provider.TimeZoneNameProviderImpl;
  42 import sun.util.locale.provider.TimeZoneNameUtility;
  43 
  44 /**
  45  * Concrete implementation of the
  46  * {@link java.util.spi.TimeZoneNameProvider TimeZoneNameProvider} class
  47  * for the CLDR LocaleProviderAdapter.
  48  *
  49  * @author Naoto Sato
  50  */
  51 public class CLDRTimeZoneNameProviderImpl extends TimeZoneNameProviderImpl {
  52 
  53     private static final String NO_INHERITANCE_MARKER = "\u2205\u2205\u2205";
  54     private static class AVAILABLE_IDS {
  55         static final String[] INSTANCE =
  56             Arrays.stream(ZoneInfoFile.getZoneIds())
  57                 .sorted()
  58                 .toArray(String[]::new);
  59     }
  60 
  61     // display name array indexes
  62     private static final int INDEX_TZID         = 0;
  63     private static final int INDEX_STD_LONG     = 1;
  64     private static final int INDEX_STD_SHORT    = 2;
  65     private static final int INDEX_DST_LONG     = 3;
  66     private static final int INDEX_DST_SHORT    = 4;
  67     private static final int INDEX_GEN_LONG     = 5;
  68     private static final int INDEX_GEN_SHORT    = 6;
  69 
  70     public CLDRTimeZoneNameProviderImpl(Type type, Set<String> langtags) {
  71         super(type, langtags);
  72     }
  73 
  74     @Override
  75     protected String[] getDisplayNameArray(String id, Locale locale) {
  76         String tzid = TimeZoneNameUtility.canonicalTZID(id).orElse(id);
  77         String[] namesSuper = super.getDisplayNameArray(tzid, locale);
  78 
  79         if (Objects.nonNull(namesSuper)) {
  80             // CLDR's resource bundle has an translated entry for this id.
  81             // Fix up names if needed, either missing or no-inheritance
  82             namesSuper[INDEX_TZID] = id;
  83 
  84             // Check if standard long name exists. If not, try to retrieve the name
  85             // from language only locale resources. E.g., "Europe/London"
  86             // for en-GB only contains DST names
  87             if (!exists(namesSuper, INDEX_STD_LONG) && !locale.getCountry().isEmpty()) {
  88                 String[] names =
  89                         getDisplayNameArray(id, Locale.forLanguageTag(locale.getLanguage()));
  90                 if (exists(names, INDEX_STD_LONG)) {
  91                     namesSuper[INDEX_STD_LONG] = names[INDEX_STD_LONG];
  92                 }
  93             }
  94 
  95             for(int i = INDEX_STD_LONG; i < namesSuper.length; i++) { // index 0 is the 'id' itself
  96                 switch (namesSuper[i]) {
  97                 case "":
  98                     // Fill in empty elements
  99                     deriveFallbackName(namesSuper, i, locale,
 100                             namesSuper[INDEX_DST_LONG].isEmpty());
 101                     break;
 102                 case NO_INHERITANCE_MARKER:
 103                     // CLDR's "no inheritance marker"
 104                     namesSuper[i] = toGMTFormat(id, i == INDEX_DST_LONG || i == INDEX_DST_SHORT,
 105                                                 i % 2 != 0, locale);
 106                     break;
 107                 default:
 108                     break;
 109                 }
 110             }
 111             return namesSuper;
 112         } else {
 113             // Derive the names for this id. Validate the id first.
 114             if (Arrays.binarySearch(AVAILABLE_IDS.INSTANCE, id) >= 0) {
 115                 String[] names = new String[INDEX_GEN_SHORT + 1];
 116                 names[INDEX_TZID] = id;
 117                 deriveFallbackNames(names, locale);
 118                 return names;
 119             }
 120         }
 121 
 122         return null;
 123     }
 124 
 125     @Override
 126     protected String[][] getZoneStrings(Locale locale) {
 127         // Use English for the ROOT locale
 128         locale = locale.equals(Locale.ROOT) ? Locale.ENGLISH : locale;
 129         String[][] ret = super.getZoneStrings(locale);
 130 
 131         // Fill in for the empty names.
 132         // English names are prefilled for performance.
 133         if (!locale.equals(Locale.ENGLISH) &&
 134             !locale.equals(Locale.US)) {
 135             for (int zoneIndex = 0; zoneIndex < ret.length; zoneIndex++) {
 136                 deriveFallbackNames(ret[zoneIndex], locale);
 137             }
 138         }
 139         return ret;
 140     }
 141 
 142     // Derive fallback time zone name according to LDML's logic
 143     private void deriveFallbackNames(String[] names, Locale locale) {
 144         for (int i = INDEX_STD_LONG; i <= INDEX_GEN_SHORT; i++) {
 145             deriveFallbackName(names, i, locale, false);
 146         }
 147     }
 148 
 149     private void deriveFallbackName(String[] names, int index, Locale locale, boolean noDST) {
 150         if (exists(names, index)) {
 151             return;
 152         }
 153 
 154         // Check if COMPAT can substitute the name
 155         if (LocaleProviderAdapter.getAdapterPreference().contains(Type.JRE)) {
 156             String[] compatNames = (String[])LocaleProviderAdapter.forJRE()
 157                 .getLocaleResources(locale)
 158                 .getTimeZoneNames(names[INDEX_TZID]);
 159             if (compatNames != null) {
 160                 for (int i = INDEX_STD_LONG; i <= INDEX_GEN_SHORT; i++) {
 161                     // Assumes COMPAT has no empty slots
 162                     if (i == index || !exists(names, i)) {
 163                         names[i] = compatNames[i];
 164                     }
 165                 }
 166                 return;
 167             }
 168         }
 169 
 170         // Type Fallback
 171         if (noDST && typeFallback(names, index)) {
 172             return;
 173         }
 174 
 175         // Region Fallback
 176         if (regionFormatFallback(names, index, locale)) {
 177             return;
 178         }
 179 
 180         // last resort
 181         String id = names[INDEX_TZID].toUpperCase(Locale.ROOT);
 182         if (!id.startsWith("UT")) {
 183             names[index] = toGMTFormat(names[INDEX_TZID],
 184                                        index == INDEX_DST_LONG || index == INDEX_DST_SHORT,
 185                                        index % 2 != 0,
 186                                        locale);
 187             // aliases of "GMT" timezone.
 188             if ((exists(names, INDEX_STD_LONG)) && (id.startsWith("Etc/")
 189                     || id.startsWith("GMT") || id.startsWith("Greenwich"))) {
 190                 switch (id) {
 191                 case "Etc/GMT":
 192                 case "Etc/GMT-0":
 193                 case "Etc/GMT+0":
 194                 case "Etc/GMT0":
 195                 case "GMT+0":
 196                 case "GMT-0":
 197                 case "GMT0":
 198                 case "Greenwich":
 199                     names[INDEX_DST_LONG] = names[INDEX_GEN_LONG] = names[INDEX_STD_LONG];
 200                     break;
 201                 }
 202             }
 203         }
 204     }
 205 
 206     private boolean exists(String[] names, int index) {
 207         return Objects.nonNull(names)
 208                 && Objects.nonNull(names[index])
 209                 && !names[index].isEmpty();
 210     }
 211 
 212     private boolean typeFallback(String[] names, int index) {
 213         // check generic
 214         int genIndex = INDEX_GEN_SHORT - index % 2;
 215         if (!exists(names, index) && exists(names, genIndex)) {
 216             names[index] = names[genIndex];
 217         } else {
 218             // check standard
 219             int stdIndex = INDEX_STD_SHORT - index % 2;
 220             if (!exists(names, index) && exists(names, stdIndex)) {
 221                 names[index] = names[stdIndex];
 222             }
 223         }
 224 
 225         return exists(names, index);
 226     }
 227 
 228     private boolean regionFormatFallback(String[] names, int index, Locale l) {
 229         String id = names[INDEX_TZID];
 230         LocaleResources lr = LocaleProviderAdapter.forType(Type.CLDR).getLocaleResources(l);
 231         ResourceBundle fd = lr.getJavaTimeFormatData();
 232 
 233         String rgn = (String) lr.getTimeZoneNames("timezone.excity." + id);
 234         if (rgn == null && !id.startsWith("Etc") && !id.startsWith("SystemV")) {
 235             int slash = id.lastIndexOf('/');
 236             if (slash > 0) {
 237                 rgn = id.substring(slash + 1).replaceAll("_", " ");
 238             }
 239         }
 240 
 241         if (rgn != null) {
 242             String fmt = "";
 243             switch (index) {
 244             case INDEX_STD_LONG:
 245                 fmt = fd.getString("timezone.regionFormat.standard");
 246                 break;
 247             case INDEX_DST_LONG:
 248                 fmt = fd.getString("timezone.regionFormat.daylight");
 249                 break;
 250             case INDEX_GEN_LONG:
 251                 fmt = fd.getString("timezone.regionFormat");
 252                 break;
 253             }
 254             if (!fmt.isEmpty()) {
 255                 names[index] = MessageFormat.format(fmt, rgn);
 256             }
 257         }
 258 
 259         return exists(names, index);
 260     }
 261 
 262     private String toGMTFormat(String id, boolean daylight, boolean isShort, Locale l) {
 263         TimeZone tz = ZoneInfoFile.getZoneInfo(id);
 264         int offset = (tz.getRawOffset() + (daylight ? tz.getDSTSavings() : 0)) / 60000;
 265         LocaleResources lr = LocaleProviderAdapter.forType(Type.CLDR).getLocaleResources(l);
 266         ResourceBundle fd = lr.getJavaTimeFormatData();
 267 
 268         if (offset == 0) {
 269             return fd.getString("timezone.gmtZeroFormat");
 270         } else {
 271             String gmtFormat = fd.getString("timezone.gmtFormat");
 272             String hourFormat = fd.getString("timezone.hourFormat");
 273 
 274             if (offset > 0) {
 275                 hourFormat = hourFormat.substring(0, hourFormat.indexOf(";"));
 276             } else {
 277                 hourFormat = hourFormat.substring(hourFormat.indexOf(";") + 1);
 278                 offset = -offset;
 279             }
 280             hourFormat = hourFormat
 281                 .replaceFirst("H+", (isShort ? "\\%1\\$d" : "\\%1\\$02d"))
 282                 .replaceFirst("m+", "\\%2\\$02d");
 283             return MessageFormat.format(gmtFormat,
 284                     String.format(hourFormat, offset / 60, offset % 60));
 285         }
 286     }
 287 }