1 /*
   2  * Copyright (c) 2012, 2013, 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 package sun.util.locale.provider;
  26 
  27 import static java.util.Calendar.*;
  28 import java.util.Comparator;
  29 import java.util.Locale;
  30 import java.util.Map;
  31 import java.util.Set;
  32 import java.util.TreeMap;
  33 import java.util.spi.CalendarNameProvider;
  34 
  35 /**
  36  * Concrete implementation of the  {@link java.util.spi.CalendarDataProvider
  37  * CalendarDataProvider} class for the JRE LocaleProviderAdapter.
  38  *
  39  * @author Masayoshi Okutsu
  40  * @author Naoto Sato
  41  */
  42 public class CalendarNameProviderImpl extends CalendarNameProvider implements AvailableLanguageTags {
  43     private final LocaleProviderAdapter.Type type;
  44     private final Set<String> langtags;
  45 
  46     public CalendarNameProviderImpl(LocaleProviderAdapter.Type type, Set<String> langtags) {
  47         this.type = type;
  48         this.langtags = langtags;
  49     }
  50 
  51     @Override
  52     public String getDisplayName(String calendarType, int field, int value, int style, Locale locale) {
  53         String name = null;
  54         String key = getResourceKey(calendarType, field, style);
  55         if (key != null) {
  56             String[] strings = LocaleProviderAdapter.forType(type).getLocaleResources(locale).getCalendarNames(key);
  57             if (strings != null && strings.length > 0) {
  58                 if (field == DAY_OF_WEEK || field == YEAR) {
  59                     --value;
  60                 }
  61                 if (value < 0 || value >= strings.length) {
  62                     return null;
  63                 }
  64                 name = strings[value];
  65                 // If name is empty in standalone, try its `format' style.
  66                 if (name.length() == 0
  67                         && (style == SHORT_STANDALONE || style == LONG_STANDALONE
  68                             || style == NARROW_STANDALONE)) {
  69                     name = getDisplayName(calendarType, field, value,
  70                                           getBaseStyle(style),
  71                                           locale);
  72                 }
  73             }
  74         }
  75         return name;
  76     }
  77 
  78     private static int[] REST_OF_STYLES = {
  79         SHORT_STANDALONE, LONG_FORMAT, LONG_STANDALONE,
  80         NARROW_FORMAT, NARROW_STANDALONE
  81     };
  82     @Override
  83     public Map<String, Integer> getDisplayNames(String calendarType, int field, int style, Locale locale) {
  84         Map<String, Integer> names;
  85         if (style == ALL_STYLES) {
  86             names = getDisplayNamesImpl(calendarType, field, SHORT_FORMAT, locale);
  87             for (int st : REST_OF_STYLES) {
  88                 names.putAll(getDisplayNamesImpl(calendarType, field, st, locale));
  89             }
  90         } else {
  91             // specific style
  92             names = getDisplayNamesImpl(calendarType, field, style, locale);
  93         }
  94         return names.isEmpty() ? null : names;
  95     }
  96 
  97     private Map<String, Integer> getDisplayNamesImpl(String calendarType, int field,
  98                                                      int style, Locale locale) {
  99         String key = getResourceKey(calendarType, field, style);
 100         Map<String, Integer> map = new TreeMap<>(LengthBasedComparator.INSTANCE);
 101         if (key != null) {
 102             String[] strings = LocaleProviderAdapter.forType(type).getLocaleResources(locale).getCalendarNames(key);
 103             if (strings != null) {
 104                 if (!hasDuplicates(strings)) {
 105                     if (field == YEAR) {
 106                         if (strings.length > 0) {
 107                             map.put(strings[0], 1);
 108                         }
 109                     } else {
 110                         int base = (field == DAY_OF_WEEK) ? 1 : 0;
 111                         for (int i = 0; i < strings.length; i++) {
 112                             String name = strings[i];
 113                             // Ignore any empty string (some standalone month names
 114                             // are not defined)
 115                             if (name.length() == 0) {
 116                                 continue;
 117                             }
 118                             map.put(name, base + i);
 119                         }
 120                     }
 121                 }
 122             }
 123         }
 124         return map;
 125     }
 126 
 127     private int getBaseStyle(int style) {
 128         return style & ~(SHORT_STANDALONE - SHORT_FORMAT);
 129     }
 130 
 131     /**
 132      * Comparator implementation for TreeMap which iterates keys from longest
 133      * to shortest.
 134      */
 135     private static class LengthBasedComparator implements Comparator<String> {
 136         private static final LengthBasedComparator INSTANCE = new LengthBasedComparator();
 137 
 138         private LengthBasedComparator() {
 139         }
 140 
 141         @Override
 142         public int compare(String o1, String o2) {
 143             int n = o2.length() - o1.length();
 144             return (n == 0) ? o1.compareTo(o2) : n;
 145         }
 146     }
 147 
 148     @Override
 149     public Locale[] getAvailableLocales() {
 150         return LocaleProviderAdapter.toLocaleArray(langtags);
 151     }
 152 
 153     @Override
 154     public boolean isSupportedLocale(Locale locale) {
 155         if (Locale.ROOT.equals(locale)) {
 156             return true;
 157         }
 158         String calendarType = null;
 159         if (locale.hasExtensions()) {
 160             calendarType = locale.getUnicodeLocaleType("ca");
 161             locale = locale.stripExtensions();
 162         }
 163 
 164         if (calendarType != null) {
 165             switch (calendarType) {
 166             case "buddhist":
 167             case "japanese":
 168             case "gregory":
 169             case "islamic":
 170             case "roc":
 171                 break;
 172             default:
 173                 // Unknown calendar type
 174                 return false;
 175             }
 176         }
 177         if (langtags.contains(locale.toLanguageTag())) {
 178             return true;
 179         }
 180         if (type == LocaleProviderAdapter.Type.JRE) {
 181             String oldname = locale.toString().replace('_', '-');
 182             return langtags.contains(oldname);
 183         }
 184         return false;
 185     }
 186 
 187     @Override
 188     public Set<String> getAvailableLanguageTags() {
 189         return langtags;
 190     }
 191 
 192     private boolean hasDuplicates(String[] strings) {
 193         int len = strings.length;
 194         for (int i = 0; i < len - 1; i++) {
 195             String a = strings[i];
 196             if (a != null) {
 197                 for (int j = i + 1; j < len; j++) {
 198                     if (a.equals(strings[j]))  {
 199                         return true;
 200                     }
 201                 }
 202             }
 203         }
 204         return false;
 205     }
 206 
 207     private String getResourceKey(String type, int field, int style) {
 208         int baseStyle = getBaseStyle(style);
 209         boolean isStandalone = (style != baseStyle);
 210 
 211         if ("gregory".equals(type)) {
 212             type = null;
 213         }
 214         boolean isNarrow = (baseStyle == NARROW_FORMAT);
 215         StringBuilder key = new StringBuilder();
 216         switch (field) {
 217         case ERA:
 218             if (type != null) {
 219                 key.append(type).append('.');
 220             }
 221             if (isNarrow) {
 222                 key.append("narrow.");
 223             } else {
 224                 // JRE and CLDR use different resource key conventions
 225                 // due to historical reasons. (JRE DateFormatSymbols.getEras returns
 226                 // abbreviations while other getShort*() return abbreviations.)
 227                 if (this.type == LocaleProviderAdapter.Type.JRE) {
 228                     if (baseStyle == SHORT) {
 229                         key.append("short.");
 230                     }
 231                 } else { // CLDR
 232                     if (baseStyle == LONG) {
 233                         key.append("long.");
 234                     }
 235                 }
 236             }
 237             key.append("Eras");
 238             break;
 239 
 240         case YEAR:
 241             if (!isNarrow) {
 242                 key.append(type).append(".FirstYear");
 243             }
 244             break;
 245 
 246         case MONTH:
 247             if ("islamic".equals(type)) {
 248                 key.append(type).append('.');
 249             }
 250             if (isStandalone) {
 251                 key.append("standalone.");
 252             }
 253             key.append("Month").append(toStyleName(baseStyle));
 254             break;
 255 
 256         case DAY_OF_WEEK:
 257             // support standalone narrow day names
 258             if (isStandalone && isNarrow) {
 259                 key.append("standalone.");
 260             }
 261             key.append("Day").append(toStyleName(baseStyle));
 262             break;
 263 
 264         case AM_PM:
 265             if (isNarrow) {
 266                 key.append("narrow.");
 267             }
 268             key.append("AmPmMarkers");
 269             break;
 270         }
 271         return key.length() > 0 ? key.toString() : null;
 272     }
 273 
 274     private String toStyleName(int baseStyle) {
 275         switch (baseStyle) {
 276         case SHORT:
 277             return "Abbreviations";
 278         case NARROW_FORMAT:
 279             return "Narrows";
 280         }
 281         return "Names";
 282     }
 283 }