LocaleResources.java 18.3 KB
Newer Older
1
/*
2
 * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.  Oracle designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Oracle in the LICENSE file that accompanied this code.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */

/*
 * (C) Copyright Taligent, Inc. 1996, 1997 - All Rights Reserved
 * (C) Copyright IBM Corp. 1996 - 1998 - All Rights Reserved
 *
 * The original version of this source code and documentation
 * is copyrighted and owned by Taligent, Inc., a wholly-owned
 * subsidiary of IBM. These materials are provided under terms
 * of a License Agreement between Taligent and Sun. This technology
 * is protected by multiple US and International patents.
 *
 * This notice and attribution to Taligent may not be removed.
 * Taligent is a registered trademark of Taligent, Inc.
 *
 */

package sun.util.locale.provider;

N
naoto 已提交
43 44
import java.lang.ref.ReferenceQueue;
import java.lang.ref.SoftReference;
45 46
import java.text.MessageFormat;
import java.util.Calendar;
N
naoto 已提交
47
import java.util.LinkedHashSet;
48
import java.util.Locale;
N
naoto 已提交
49
import java.util.Map;
50
import java.util.ResourceBundle;
N
naoto 已提交
51
import java.util.Set;
52 53
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
N
naoto 已提交
54 55 56
import sun.util.calendar.ZoneInfo;
import sun.util.resources.LocaleData;
import sun.util.resources.OpenListResourceBundle;
57
import sun.util.resources.ParallelListResourceBundle;
58
import sun.util.resources.TimeZoneNamesBundle;
59 60

/**
N
naoto 已提交
61
 * Central accessor to locale-dependent resources for JRE/CLDR provider adapters.
62 63
 *
 * @author Masayoshi Okutsu
N
naoto 已提交
64
 * @author Naoto Sato
65 66 67 68
 */
public class LocaleResources {

    private final Locale locale;
N
naoto 已提交
69 70
    private final LocaleData localeData;
    private final LocaleProviderAdapter.Type type;
71 72

    // Resource cache
N
naoto 已提交
73 74
    private ConcurrentMap<String, ResourceReference> cache = new ConcurrentHashMap<>();
    private ReferenceQueue<Object> referenceQueue = new ReferenceQueue<>();
75

N
naoto 已提交
76 77 78 79 80 81 82 83 84 85 86 87
    // cache key prefixes
    private static final String BREAK_ITERATOR_INFO = "BII.";
    private static final String CALENDAR_DATA = "CALD.";
    private static final String COLLATION_DATA_CACHEKEY = "COLD";
    private static final String DECIMAL_FORMAT_SYMBOLS_DATA_CACHEKEY = "DFSD";
    private static final String CURRENCY_NAMES = "CN.";
    private static final String LOCALE_NAMES = "LN.";
    private static final String TIME_ZONE_NAMES = "TZN.";
    private static final String ZONE_IDS_CACHEKEY = "ZID";
    private static final String CALENDAR_NAMES = "CALN.";
    private static final String NUMBER_PATTERNS_CACHEKEY = "NP";
    private static final String DATE_TIME_PATTERN = "DTP.";
88

N
naoto 已提交
89 90 91 92
    // null singleton cache value
    private static final Object NULLOBJECT = new Object();

    LocaleResources(ResourceBundleBasedAdapter adapter, Locale locale) {
93
        this.locale = locale;
N
naoto 已提交
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138
        this.localeData = adapter.getLocaleData();
        type = ((LocaleProviderAdapter)adapter).getAdapterType();
    }

    private void removeEmptyReferences() {
        Object ref;
        while ((ref = referenceQueue.poll()) != null) {
            cache.remove(((ResourceReference)ref).getCacheKey());
        }
    }

    Object getBreakIteratorInfo(String key) {
        Object biInfo;
        String cacheKey = BREAK_ITERATOR_INFO + key;

        removeEmptyReferences();
        ResourceReference data = cache.get(cacheKey);
        if (data == null || ((biInfo = data.get()) == null)) {
           biInfo = localeData.getBreakIteratorInfo(locale).getObject(key);
           cache.put(cacheKey, new ResourceReference(cacheKey, biInfo, referenceQueue));
       }

       return biInfo;
    }

    int getCalendarData(String key) {
        Integer caldata;
        String cacheKey = CALENDAR_DATA  + key;

        removeEmptyReferences();

        ResourceReference data = cache.get(cacheKey);
        if (data == null || ((caldata = (Integer) data.get()) == null)) {
            ResourceBundle rb = localeData.getCalendarData(locale);
            if (rb.containsKey(key)) {
                caldata = Integer.parseInt(rb.getString(key));
            } else {
                caldata = 0;
            }

            cache.put(cacheKey,
                      new ResourceReference(cacheKey, (Object) caldata, referenceQueue));
        }

        return caldata;
139 140
    }

N
naoto 已提交
141 142 143 144 145 146 147 148 149 150
    public String getCollationData() {
        String key = "Rule";
        String coldata = "";

        removeEmptyReferences();
        ResourceReference data = cache.get(COLLATION_DATA_CACHEKEY);
        if (data == null || ((coldata = (String) data.get()) == null)) {
            ResourceBundle rb = localeData.getCollationData(locale);
            if (rb.containsKey(key)) {
                coldata = rb.getString(key);
151
            }
N
naoto 已提交
152 153
            cache.put(COLLATION_DATA_CACHEKEY,
                      new ResourceReference(COLLATION_DATA_CACHEKEY, (Object) coldata, referenceQueue));
154
        }
N
naoto 已提交
155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254

        return coldata;
    }

    public Object[] getDecimalFormatSymbolsData() {
        Object[] dfsdata;

        removeEmptyReferences();
        ResourceReference data = cache.get(DECIMAL_FORMAT_SYMBOLS_DATA_CACHEKEY);
        if (data == null || ((dfsdata = (Object[]) data.get()) == null)) {
            // Note that only dfsdata[0] is prepared here in this method. Other
            // elements are provided by the caller, yet they are cached here.
            ResourceBundle rb = localeData.getNumberFormatData(locale);
            dfsdata = new Object[3];

            // NumberElements look up. First, try the Unicode extension
            String numElemKey;
            String numberType = locale.getUnicodeLocaleType("nu");
            if (numberType != null) {
                numElemKey = numberType + ".NumberElements";
                if (rb.containsKey(numElemKey)) {
                    dfsdata[0] = rb.getStringArray(numElemKey);
                }
            }

            // Next, try DefaultNumberingSystem value
            if (dfsdata[0] == null && rb.containsKey("DefaultNumberingSystem")) {
                numElemKey = rb.getString("DefaultNumberingSystem") + ".NumberElements";
                if (rb.containsKey(numElemKey)) {
                    dfsdata[0] = rb.getStringArray(numElemKey);
                }
            }

            // Last resort. No need to check the availability.
            // Just let it throw MissingResourceException when needed.
            if (dfsdata[0] == null) {
                dfsdata[0] = rb.getStringArray("NumberElements");
            }

            cache.put(DECIMAL_FORMAT_SYMBOLS_DATA_CACHEKEY,
                      new ResourceReference(DECIMAL_FORMAT_SYMBOLS_DATA_CACHEKEY, (Object) dfsdata, referenceQueue));
        }

        return dfsdata;
    }

    public String getCurrencyName(String key) {
        Object currencyName = null;
        String cacheKey = CURRENCY_NAMES + key;

        removeEmptyReferences();
        ResourceReference data = cache.get(cacheKey);

        if (data != null && ((currencyName = data.get()) != null)) {
            if (currencyName.equals(NULLOBJECT)) {
                currencyName = null;
            }

            return (String) currencyName;
        }

        OpenListResourceBundle olrb = localeData.getCurrencyNames(locale);

        if (olrb.containsKey(key)) {
            currencyName = olrb.getObject(key);
            cache.put(cacheKey,
                      new ResourceReference(cacheKey, currencyName, referenceQueue));
        }

        return (String) currencyName;
    }

    public String getLocaleName(String key) {
        Object localeName = null;
        String cacheKey = LOCALE_NAMES + key;

        removeEmptyReferences();
        ResourceReference data = cache.get(cacheKey);

        if (data != null && ((localeName = data.get()) != null)) {
            if (localeName.equals(NULLOBJECT)) {
                localeName = null;
            }

            return (String) localeName;
        }

        OpenListResourceBundle olrb = localeData.getLocaleNames(locale);

        if (olrb.containsKey(key)) {
            localeName = olrb.getObject(key);
            cache.put(cacheKey,
                      new ResourceReference(cacheKey, localeName, referenceQueue));
        }

        return (String) localeName;
    }

    String[] getTimeZoneNames(String key, int size) {
        String[] names = null;
255
        String cacheKey = TIME_ZONE_NAMES + size + '.' + key;
N
naoto 已提交
256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332

        removeEmptyReferences();
        ResourceReference data = cache.get(cacheKey);

        if (data == null || ((names = (String[]) data.get()) == null)) {
            TimeZoneNamesBundle tznb = localeData.getTimeZoneNames(locale);
            if (tznb.containsKey(key)) {
                names = tznb.getStringArray(key, size);
                cache.put(cacheKey,
                          new ResourceReference(cacheKey, (Object) names, referenceQueue));
            }
        }

        return names;
    }

    @SuppressWarnings("unchecked")
    Set<String> getZoneIDs() {
        Set<String> zoneIDs = null;

        removeEmptyReferences();
        ResourceReference data = cache.get(ZONE_IDS_CACHEKEY);
        if (data == null || ((zoneIDs = (Set<String>) data.get()) == null)) {
            TimeZoneNamesBundle rb = localeData.getTimeZoneNames(locale);
            zoneIDs = rb.keySet();
            cache.put(ZONE_IDS_CACHEKEY,
                      new ResourceReference(ZONE_IDS_CACHEKEY, (Object) zoneIDs, referenceQueue));
        }

        return zoneIDs;
    }

    // zoneStrings are cached separately in TimeZoneNameUtility.
    String[][] getZoneStrings() {
        TimeZoneNamesBundle rb = localeData.getTimeZoneNames(locale);
        Set<String> keyset = getZoneIDs();
        // Use a LinkedHashSet to preseve the order
        Set<String[]> value = new LinkedHashSet<>();
        for (String key : keyset) {
            value.add(rb.getStringArray(key));
        }

        // Add aliases data for CLDR
        if (type == LocaleProviderAdapter.Type.CLDR) {
            // Note: TimeZoneNamesBundle creates a String[] on each getStringArray call.
            Map<String, String> aliases = ZoneInfo.getAliasTable();
            for (String alias : aliases.keySet()) {
                if (!keyset.contains(alias)) {
                    String tzid = aliases.get(alias);
                    if (keyset.contains(tzid)) {
                        String[] val = rb.getStringArray(tzid);
                        val[0] = alias;
                        value.add(val);
                    }
                }
            }
        }
        return value.toArray(new String[0][]);
    }

    String[] getCalendarNames(String key) {
        String[] names = null;
        String cacheKey = CALENDAR_NAMES + key;

        removeEmptyReferences();
        ResourceReference data = cache.get(cacheKey);

        if (data == null || ((names = (String[]) data.get()) == null)) {
            ResourceBundle rb = localeData.getDateFormatData(locale);
            if (rb.containsKey(key)) {
                names = rb.getStringArray(key);
                cache.put(cacheKey,
                          new ResourceReference(cacheKey, (Object) names, referenceQueue));
            }
        }

        return names;
333 334
    }

335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353
    String[] getJavaTimeNames(String key) {
        String[] names = null;
        String cacheKey = CALENDAR_NAMES + key;

        removeEmptyReferences();
        ResourceReference data = cache.get(cacheKey);

        if (data == null || ((names = (String[]) data.get()) == null)) {
            ResourceBundle rb = getJavaTimeFormatData();
            if (rb.containsKey(key)) {
                names = rb.getStringArray(key);
                cache.put(cacheKey,
                          new ResourceReference(cacheKey, (Object) names, referenceQueue));
            }
        }

        return names;
    }

354 355 356 357
    public String getDateTimePattern(int timeStyle, int dateStyle, Calendar cal) {
        if (cal == null) {
            cal = Calendar.getInstance(locale);
        }
S
sherman 已提交
358 359 360 361 362 363 364 365 366 367 368 369
        return getDateTimePattern(null, timeStyle, dateStyle, cal.getCalendarType());
    }

    /**
     * Returns a date-time format pattern
     * @param timeStyle style of time; one of FULL, LONG, MEDIUM, SHORT in DateFormat,
     *                  or -1 if not required
     * @param dateStyle style of time; one of FULL, LONG, MEDIUM, SHORT in DateFormat,
     *                  or -1 if not required
     * @param calType   the calendar type for the pattern
     * @return the pattern string
     */
370
    public String getJavaTimeDateTimePattern(int timeStyle, int dateStyle, String calType) {
S
sherman 已提交
371 372
        calType = CalendarDataUtility.normalizeCalendarType(calType);
        String pattern;
373
        pattern = getDateTimePattern("java.time.", timeStyle, dateStyle, calType);
S
sherman 已提交
374 375 376 377 378 379 380 381
        if (pattern == null) {
            pattern = getDateTimePattern(null, timeStyle, dateStyle, calType);
        }
        return pattern;
    }

    private String getDateTimePattern(String prefix, int timeStyle, int dateStyle, String calType) {
        String pattern;
382 383
        String timePattern = null;
        String datePattern = null;
S
sherman 已提交
384

385
        if (timeStyle >= 0) {
S
sherman 已提交
386 387 388 389 390 391
            if (prefix != null) {
                timePattern = getDateTimePattern(prefix, "TimePatterns", timeStyle, calType);
            }
            if (timePattern == null) {
                timePattern = getDateTimePattern(null, "TimePatterns", timeStyle, calType);
            }
392 393
        }
        if (dateStyle >= 0) {
S
sherman 已提交
394 395 396 397 398 399
            if (prefix != null) {
                datePattern = getDateTimePattern(prefix, "DatePatterns", dateStyle, calType);
            }
            if (datePattern == null) {
                datePattern = getDateTimePattern(null, "DatePatterns", dateStyle, calType);
            }
400 401 402
        }
        if (timeStyle >= 0) {
            if (dateStyle >= 0) {
S
sherman 已提交
403 404 405 406 407 408 409
                String dateTimePattern = null;
                if (prefix != null) {
                    dateTimePattern = getDateTimePattern(prefix, "DateTimePatterns", 0, calType);
                }
                if (dateTimePattern == null) {
                    dateTimePattern = getDateTimePattern(null, "DateTimePatterns", 0, calType);
                }
410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432
                switch (dateTimePattern) {
                case "{1} {0}":
                    pattern = datePattern + " " + timePattern;
                    break;
                case "{0} {1}":
                    pattern = timePattern + " " + datePattern;
                    break;
                default:
                    pattern = MessageFormat.format(dateTimePattern, timePattern, datePattern);
                    break;
                }
            } else {
                pattern = timePattern;
            }
        } else if (dateStyle >= 0) {
            pattern = datePattern;
        } else {
            throw new IllegalArgumentException("No date or time style specified");
        }
        return pattern;
    }

    public String[] getNumberPatterns() {
N
naoto 已提交
433 434 435 436 437 438 439
        String[] numberPatterns = null;

        removeEmptyReferences();
        ResourceReference data = cache.get(NUMBER_PATTERNS_CACHEKEY);

        if (data == null || ((numberPatterns = (String[]) data.get()) == null)) {
            ResourceBundle resource = localeData.getNumberFormatData(locale);
440
            numberPatterns = resource.getStringArray("NumberPatterns");
N
naoto 已提交
441 442
            cache.put(NUMBER_PATTERNS_CACHEKEY,
                      new ResourceReference(NUMBER_PATTERNS_CACHEKEY, (Object) numberPatterns, referenceQueue));
443
        }
N
naoto 已提交
444

445 446 447
        return numberPatterns;
    }

448 449 450 451 452
    /**
     * Returns the FormatData resource bundle of this LocaleResources.
     * The FormatData should be used only for accessing extra
     * resources required by JSR 310.
     */
453 454 455 456 457 458
    public ResourceBundle getJavaTimeFormatData() {
        ResourceBundle rb = localeData.getDateFormatData(locale);
        if (rb instanceof ParallelListResourceBundle) {
            localeData.setSupplementary((ParallelListResourceBundle) rb);
        }
        return rb;
459 460
    }

S
sherman 已提交
461 462 463 464 465 466 467 468 469 470 471
    private String getDateTimePattern(String prefix, String key, int styleIndex, String calendarType) {
        StringBuilder sb = new StringBuilder();
        if (prefix != null) {
            sb.append(prefix);
        }
        if (!"gregory".equals(calendarType)) {
            sb.append(calendarType).append('.');
        }
        sb.append(key);
        String resourceKey = sb.toString();
        String cacheKey = sb.insert(0, DATE_TIME_PATTERN).toString();
N
naoto 已提交
472 473 474

        removeEmptyReferences();
        ResourceReference data = cache.get(cacheKey);
S
sherman 已提交
475
        Object value = NULLOBJECT;
N
naoto 已提交
476

S
sherman 已提交
477
        if (data == null || ((value = data.get()) == null)) {
478
            ResourceBundle r = (prefix != null) ? getJavaTimeFormatData() : localeData.getDateFormatData(locale);
479
            if (r.containsKey(resourceKey)) {
S
sherman 已提交
480
                value = r.getStringArray(resourceKey);
481 482
            } else {
                assert !resourceKey.equals(key);
S
sherman 已提交
483 484 485
                if (r.containsKey(key)) {
                    value = r.getStringArray(key);
                }
486
            }
N
naoto 已提交
487
            cache.put(cacheKey,
S
sherman 已提交
488
                      new ResourceReference(cacheKey, value, referenceQueue));
489
        }
S
sherman 已提交
490 491 492 493 494
        if (value == NULLOBJECT) {
            assert prefix != null;
            return null;
        }
        return ((String[])value)[styleIndex];
495
    }
N
naoto 已提交
496 497 498 499 500 501 502 503 504 505 506 507 508

    private static class ResourceReference extends SoftReference<Object> {
        private final String cacheKey;

        ResourceReference(String cacheKey, Object o, ReferenceQueue<Object> q) {
            super(o, q);
            this.cacheKey = cacheKey;
        }

        String getCacheKey() {
            return cacheKey;
        }
    }
509
}