LocaleProviderAdapter.java 14.4 KB
Newer Older
1 2 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
/*
 * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
 * 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.
 */

package sun.util.locale.provider;

import java.security.AccessController;
import java.text.spi.BreakIteratorProvider;
import java.text.spi.CollatorProvider;
import java.text.spi.DateFormatProvider;
import java.text.spi.DateFormatSymbolsProvider;
import java.text.spi.DecimalFormatSymbolsProvider;
import java.text.spi.NumberFormatProvider;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.ResourceBundle;
import java.util.Set;
N
naoto 已提交
40 41
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
42
import java.util.spi.CalendarDataProvider;
43
import java.util.spi.CalendarNameProvider;
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
import java.util.spi.CurrencyNameProvider;
import java.util.spi.LocaleNameProvider;
import java.util.spi.LocaleServiceProvider;
import java.util.spi.TimeZoneNameProvider;
import sun.util.cldr.CLDRLocaleProviderAdapter;

/**
 * The LocaleProviderAdapter abstract class.
 *
 * @author Naoto Sato
 * @author Masayoshi Okutsu
 */
public abstract class LocaleProviderAdapter {
    /**
     * Adapter type.
     */
    public static enum Type {
        JRE("sun.util.resources", "sun.text.resources"),
        CLDR("sun.util.resources.cldr", "sun.text.resources.cldr"),
        SPI,
64 65
        HOST,
        FALLBACK("sun.util.resources", "sun.text.resources");
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116

        private final String UTIL_RESOURCES_PACKAGE;
        private final String TEXT_RESOURCES_PACKAGE;

        private Type() {
            this(null, null);
        }

        private Type(String util, String text) {
            UTIL_RESOURCES_PACKAGE = util;
            TEXT_RESOURCES_PACKAGE = text;
        }

        public String getUtilResourcesPackage() {
            return UTIL_RESOURCES_PACKAGE;
        }

        public String getTextResourcesPackage() {
            return TEXT_RESOURCES_PACKAGE;
        }
    }

    /**
     * LocaleProviderAdapter preference list. The default list is intended
     * to behave the same manner in JDK7.
     */
    private static Type[] adapterPreference = {
        Type.JRE,
        Type.SPI,
    };

    /**
     * JRE Locale Data Adapter instance
     */
    private static LocaleProviderAdapter jreLocaleProviderAdapter = new JRELocaleProviderAdapter();

    /**
     * SPI Locale Data Adapter instance
     */
    private static LocaleProviderAdapter spiLocaleProviderAdapter = new SPILocaleProviderAdapter();

    /**
     * CLDR Locale Data Adapter instance, if any.
     */
    private static LocaleProviderAdapter cldrLocaleProviderAdapter = null;

    /**
     * HOST Locale Data Adapter instance, if any.
     */
    private static LocaleProviderAdapter hostLocaleProviderAdapter = null;

117 118 119 120 121 122
    /**
     * FALLBACK Locale Data Adapter instance. It's basically the same with JRE, but only kicks
     * in for the root locale.
     */
    private static LocaleProviderAdapter fallbackLocaleProviderAdapter = null;

N
naoto 已提交
123 124 125 126 127 128
    /**
     * Adapter lookup cache.
     */
    private static ConcurrentMap<Class<? extends LocaleServiceProvider>, ConcurrentMap<Locale, LocaleProviderAdapter>>
        adapterCache = new ConcurrentHashMap<>();

129 130 131
    static {
        String order = AccessController.doPrivileged(
                           new sun.security.action.GetPropertyAction("java.locale.providers"));
132 133 134 135 136 137 138
        // Override adapterPreference with the properties one
        if (order != null && order.length() != 0) {
            String[] types = order.split(",");
            List<Type> typeList = new ArrayList<>();
            for (String type : types) {
                try {
                    Type aType = Type.valueOf(type.trim().toUpperCase(Locale.ROOT));
139

140 141 142 143 144 145 146 147
                    // load adapter if necessary
                    switch (aType) {
                        case CLDR:
                            cldrLocaleProviderAdapter = new CLDRLocaleProviderAdapter();
                            break;
                        case HOST:
                            hostLocaleProviderAdapter = new HostLocaleProviderAdapter();
                            break;
148
                    }
149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165
                    typeList.add(aType);
                } catch (IllegalArgumentException | UnsupportedOperationException e) {
                    // could be caused by the user specifying wrong
                    // provider name or format in the system property
                    LocaleServiceProviderPool.config(LocaleProviderAdapter.class, e.toString());
                }
            }

            if (!typeList.isEmpty()) {
                if (!typeList.contains(Type.JRE)) {
                    // Append FALLBACK as the last resort.
                    fallbackLocaleProviderAdapter = new FallbackLocaleProviderAdapter();
                    typeList.add(Type.FALLBACK);
                }
                adapterPreference = typeList.toArray(new Type[0]);
            }
        }
166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
    }


    /**
     * Returns the singleton instance for each adapter type
     */
    public static LocaleProviderAdapter forType(Type type) {
        switch (type) {
        case JRE:
            return jreLocaleProviderAdapter;
        case CLDR:
            return cldrLocaleProviderAdapter;
        case SPI:
            return spiLocaleProviderAdapter;
        case HOST:
            return hostLocaleProviderAdapter;
182 183
        case FALLBACK:
            return fallbackLocaleProviderAdapter;
184 185 186 187 188 189 190 191 192 193 194
        default:
            throw new InternalError("unknown locale data adapter type");
        }
    }

    public static LocaleProviderAdapter forJRE() {
        return jreLocaleProviderAdapter;
    }

    public static LocaleProviderAdapter getResourceBundleBased() {
        for (Type type : getAdapterPreference()) {
195
            if (type == Type.JRE || type == Type.CLDR || type == Type.FALLBACK) {
196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219
                return forType(type);
            }
        }
        // Shouldn't happen.
        throw new InternalError();
    }
    /**
     * Returns the preference order of LocaleProviderAdapter.Type
     */
    public static Type[] getAdapterPreference() {
        return adapterPreference;
    }

    /**
     * Returns a LocaleProviderAdapter for the given locale service provider that
     * best matches the given locale. This method returns the LocaleProviderAdapter
     * for JRE if none is found for the given locale.
     *
     * @param providerClass the class for the locale service provider
     * @param locale the desired locale.
     * @return a LocaleProviderAdapter
     */
    public static LocaleProviderAdapter getAdapter(Class<? extends LocaleServiceProvider> providerClass,
                                               Locale locale) {
N
naoto 已提交
220 221 222 223 224 225 226 227 228 229 230 231 232
        LocaleProviderAdapter adapter;

        // cache lookup
        ConcurrentMap<Locale, LocaleProviderAdapter> adapterMap = adapterCache.get(providerClass);
        if (adapterMap != null) {
            if ((adapter = adapterMap.get(locale)) != null) {
                return adapter;
            }
        } else {
            adapterMap = new ConcurrentHashMap<>();
            adapterCache.putIfAbsent(providerClass, adapterMap);
        }

233
        // Fast look-up for the given locale
N
naoto 已提交
234
        adapter = findAdapter(providerClass, locale);
235
        if (adapter != null) {
N
naoto 已提交
236
            adapterMap.putIfAbsent(locale, adapter);
237 238 239 240 241 242 243 244 245 246 247 248 249
            return adapter;
        }

        // Try finding an adapter in the normal candidate locales path of the given locale.
        List<Locale> lookupLocales = ResourceBundle.Control.getControl(ResourceBundle.Control.FORMAT_DEFAULT)
                                        .getCandidateLocales("", locale);
        for (Locale loc : lookupLocales) {
            if (loc.equals(locale)) {
                // We've already done with this loc.
                continue;
            }
            adapter = findAdapter(providerClass, loc);
            if (adapter != null) {
N
naoto 已提交
250
                adapterMap.putIfAbsent(locale, adapter);
251 252 253 254
                return adapter;
            }
        }

255
        // returns the adapter for FALLBACK as the last resort
N
naoto 已提交
256
        adapterMap.putIfAbsent(locale, fallbackLocaleProviderAdapter);
257
        return fallbackLocaleProviderAdapter;
258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275
    }

    private static LocaleProviderAdapter findAdapter(Class<? extends LocaleServiceProvider> providerClass,
                                                 Locale locale) {
        for (Type type : getAdapterPreference()) {
            LocaleProviderAdapter adapter = forType(type);
            LocaleServiceProvider provider = adapter.getLocaleServiceProvider(providerClass);
            if (provider != null) {
                if (provider.isSupportedLocale(locale)) {
                    return adapter;
                }
            }
        }
        return null;
    }

    /**
     * A utility method for implementing the default LocaleServiceProvider.isSupportedLocale
276
     * for the JRE, CLDR, and FALLBACK adapters.
277 278
     */
    static boolean isSupportedLocale(Locale locale, LocaleProviderAdapter.Type type, Set<String> langtags) {
279 280
        assert type == Type.JRE || type == Type.CLDR || type == Type.FALLBACK;
        if (Locale.ROOT.equals(locale)) {
281 282
            return true;
        }
283 284 285 286 287 288

        if (type == Type.FALLBACK) {
            // no other locales except ROOT are supported for FALLBACK
            return false;
        }

289 290 291 292
        locale = locale.stripExtensions();
        if (langtags.contains(locale.toLanguageTag())) {
            return true;
        }
293
        if (type == Type.JRE) {
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 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413
            String oldname = locale.toString().replace('_', '-');
            return langtags.contains(oldname);
        }
        return false;
    }

    public static Locale[] toLocaleArray(Set<String> tags) {
        Locale[] locs = new Locale[tags.size() + 1];
        int index = 0;
        locs[index++] = Locale.ROOT;
        for (String tag : tags) {
            switch (tag) {
            case "ja-JP-JP":
                locs[index++] = JRELocaleConstants.JA_JP_JP;
                break;
            case "th-TH-TH":
                locs[index++] = JRELocaleConstants.TH_TH_TH;
                break;
            default:
                locs[index++] = Locale.forLanguageTag(tag);
                break;
            }
        }
        return locs;
    }

    /**
     * Returns the type of this LocaleProviderAdapter
     */
    public abstract LocaleProviderAdapter.Type getAdapterType();

    /**
     * Getter method for Locale Service Providers.
     */
    public abstract <P extends LocaleServiceProvider> P getLocaleServiceProvider(Class<P> c);

    /**
     * Returns a BreakIteratorProvider for this LocaleProviderAdapter, or null if no
     * BreakIteratorProvider is available.
     *
     * @return a BreakIteratorProvider
     */
    public abstract BreakIteratorProvider getBreakIteratorProvider();

    /**
     * Returns a ollatorProvider for this LocaleProviderAdapter, or null if no
     * ollatorProvider is available.
     *
     * @return a ollatorProvider
     */
    public abstract CollatorProvider getCollatorProvider();

    /**
     * Returns a DateFormatProvider for this LocaleProviderAdapter, or null if no
     * DateFormatProvider is available.
     *
     * @return a DateFormatProvider
     */
    public abstract DateFormatProvider getDateFormatProvider();

    /**
     * Returns a DateFormatSymbolsProvider for this LocaleProviderAdapter, or null if no
     * DateFormatSymbolsProvider is available.
     *
     * @return a DateFormatSymbolsProvider
     */
    public abstract DateFormatSymbolsProvider getDateFormatSymbolsProvider();

    /**
     * Returns a DecimalFormatSymbolsProvider for this LocaleProviderAdapter, or null if no
     * DecimalFormatSymbolsProvider is available.
     *
     * @return a DecimalFormatSymbolsProvider
     */
    public abstract DecimalFormatSymbolsProvider getDecimalFormatSymbolsProvider();

    /**
     * Returns a NumberFormatProvider for this LocaleProviderAdapter, or null if no
     * NumberFormatProvider is available.
     *
     * @return a NumberFormatProvider
     */
    public abstract NumberFormatProvider getNumberFormatProvider();

    /*
     * Getter methods for java.util.spi.* providers
     */

    /**
     * Returns a CurrencyNameProvider for this LocaleProviderAdapter, or null if no
     * CurrencyNameProvider is available.
     *
     * @return a CurrencyNameProvider
     */
    public abstract CurrencyNameProvider getCurrencyNameProvider();

    /**
     * Returns a LocaleNameProvider for this LocaleProviderAdapter, or null if no
     * LocaleNameProvider is available.
     *
     * @return a LocaleNameProvider
     */
    public abstract LocaleNameProvider getLocaleNameProvider();

    /**
     * Returns a TimeZoneNameProvider for this LocaleProviderAdapter, or null if no
     * TimeZoneNameProvider is available.
     *
     * @return a TimeZoneNameProvider
     */
    public abstract TimeZoneNameProvider getTimeZoneNameProvider();

    /**
     * Returns a CalendarDataProvider for this LocaleProviderAdapter, or null if no
     * CalendarDataProvider is available.
     *
     * @return a CalendarDataProvider
     */
    public abstract CalendarDataProvider getCalendarDataProvider();

414 415 416 417 418 419 420 421
    /**
     * Returns a CalendarNameProvider for this LocaleProviderAdapter, or null if no
     * CalendarNameProvider is available.
     *
     * @return a CalendarNameProvider
     */
    public abstract CalendarNameProvider getCalendarNameProvider();

422 423 424 425
    public abstract LocaleResources getLocaleResources(Locale locale);

    public abstract Locale[] getAvailableLocales();
}