1 /*
   2  * Copyright (c) 2012, 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.ResourceBundle;
  32 import java.util.Set;
  33 import java.util.TreeMap;
  34 import java.util.spi.CalendarNameProvider;
  35 
  36 /**
  37  * Concrete implementation of the  {@link java.util.spi.CalendarDataProvider
  38  * CalendarDataProvider} class for the JRE LocaleProviderAdapter.
  39  *
  40  * @author Masayoshi Okutsu
  41  * @author Naoto Sato
  42  */
  43 public class CalendarNameProviderImpl extends CalendarNameProvider implements AvailableLanguageTags {
  44     private final LocaleProviderAdapter.Type type;
  45     private final Set<String> langtags;
  46 
  47     public CalendarNameProviderImpl(LocaleProviderAdapter.Type type, Set<String> langtags) {
  48         this.type = type;
  49         this.langtags = langtags;
  50     }
  51 
  52     @Override
  53     public String getDisplayName(String calendarType, int field, int value, int style, Locale locale) {
  54         String name = null;
  55         String key = getResourceKey(calendarType, field, style);
  56         if (key != null) {
  57             ResourceBundle rb = LocaleProviderAdapter.forType(type).getLocaleData().getDateFormatData(locale);
  58             if (rb.containsKey(key)) {
  59                 String[] strings = rb.getStringArray(key);
  60                 if (strings.length > 0) {
  61                     if (field == DAY_OF_WEEK || field == YEAR) {
  62                         --value;
  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         }
  76         return name;
  77     }
  78 
  79     private static int[] REST_OF_STYLES = {
  80         SHORT_STANDALONE, LONG_FORMAT, LONG_STANDALONE,
  81         NARROW_FORMAT, NARROW_STANDALONE
  82     };
  83     @Override
  84     public Map<String, Integer> getDisplayNames(String calendarType, int field, int style, Locale locale) {
  85         Map<String, Integer> names;
  86         if (style == ALL_STYLES) {
  87             names = getDisplayNamesImpl(calendarType, field, SHORT_FORMAT, locale);
  88             for (int st : REST_OF_STYLES) {
  89                 names.putAll(getDisplayNamesImpl(calendarType, field, st, locale));
  90             }
  91         } else {
  92             // specific style
  93             names = getDisplayNamesImpl(calendarType, field, style, locale);
  94         }
  95         return names.isEmpty() ? null : names;
  96     }
  97 
  98     private Map<String, Integer> getDisplayNamesImpl(String calendarType, int field,
  99                                                      int style, Locale locale) {
 100         String key = getResourceKey(calendarType, field, style);
 101         Map<String, Integer> map = new TreeMap<>(LengthBasedComparator.INSTANCE);
 102         if (key != null) {
 103             ResourceBundle rb = LocaleProviderAdapter.forType(type).getLocaleData().getDateFormatData(locale);
 104             if (rb.containsKey(key)) {
 105                 String[] strings = rb.getStringArray(key);
 106                 if (!hasDuplicates(strings)) {
 107                     if (field == YEAR) {
 108                         if (strings.length > 0) {
 109                             map.put(strings[0], 1);
 110                         }
 111                     } else {
 112                         int base = (field == DAY_OF_WEEK) ? 1 : 0;
 113                         for (int i = 0; i < strings.length; i++) {
 114                             String name = strings[i];
 115                             // Ignore any empty string (some standalone month names
 116                             // are not defined)
 117                             if (name.length() == 0) {
 118                                 continue;
 119                             }
 120                             map.put(name, base + i);
 121                         }
 122                     }
 123                 }
 124             }
 125         }
 126         return map;
 127     }
 128 
 129     private int getBaseStyle(int style) {
 130         return style & ~(SHORT_STANDALONE - SHORT_FORMAT);
 131     }
 132 
 133     /**
 134      * Comparator implementation for TreeMap which iterates keys from longest
 135      * to shortest.
 136      */
 137     private static class LengthBasedComparator implements Comparator<String> {
 138         private static final LengthBasedComparator INSTANCE = new LengthBasedComparator();
 139 
 140         private LengthBasedComparator() {
 141         }
 142 
 143         @Override
 144         public int compare(String o1, String o2) {
 145             int n = o2.length() - o1.length();
 146             return (n == 0) ? o1.compareTo(o2) : n;
 147         }
 148     }
 149 
 150     @Override
 151     public Locale[] getAvailableLocales() {
 152         return LocaleProviderAdapter.toLocaleArray(langtags);
 153     }
 154 
 155     @Override
 156     public boolean isSupportedLocale(Locale locale) {
 157         if (Locale.ROOT.equals(locale)) {
 158             return true;
 159         }
 160         String calendarType = null;
 161         if (locale.hasExtensions()) {
 162             calendarType = locale.getUnicodeLocaleType("ca");
 163             locale = locale.stripExtensions();
 164         }
 165 
 166         if (calendarType != null) {
 167             switch (calendarType) {
 168             case "buddhist":
 169             case "japanese":
 170             case "gregory":
 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 (isStandalone) {
 248                 key.append("standalone.");
 249             }
 250             key.append("Month").append(toStyleName(baseStyle));
 251             break;
 252 
 253         case DAY_OF_WEEK:
 254             // support standalone narrow day names
 255             if (isStandalone && isNarrow) {
 256                 key.append("standalone.");
 257             }
 258             key.append("Day").append(toStyleName(baseStyle));
 259             break;
 260 
 261         case AM_PM:
 262             if (isNarrow) {
 263                 key.append("narrow.");
 264             }
 265             key.append("AmPmMarkers");
 266             break;
 267         }
 268         return key.length() > 0 ? key.toString() : null;
 269     }
 270 
 271     private String toStyleName(int baseStyle) {
 272         switch (baseStyle) {
 273         case SHORT:
 274             return "Abbreviations";
 275         case NARROW_FORMAT:
 276             return "Narrows";
 277         }
 278         return "Names";
 279     }
 280 }