8245241: Incorrect locale provider preference is not logged

Reviewed-by: joehw, dfuchs
This commit is contained in:
Naoto Sato 2020-05-21 13:55:06 -07:00
parent e3be308329
commit b5b6ae32d2
7 changed files with 111 additions and 114 deletions

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2012, 2019, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2012, 2020, 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
@ -26,8 +26,8 @@
package sun.util.locale.provider;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.DecimalFormat;
import java.util.ServiceConfigurationError;
import java.util.spi.LocaleServiceProvider;
/**
@ -50,16 +50,20 @@ public class HostLocaleProviderAdapter extends AuxLocaleProviderAdapter {
@SuppressWarnings("unchecked")
protected <P extends LocaleServiceProvider> P findInstalledProvider(final Class<P> c) {
try {
Method getter = HostLocaleProviderAdapterImpl.class.getMethod(
"get" + c.getSimpleName(), (Class<?>[]) null);
return (P)getter.invoke(null, (Object[]) null);
} catch (NoSuchMethodException |
IllegalAccessException |
IllegalArgumentException |
InvocationTargetException ex) {
LocaleServiceProviderPool.config(HostLocaleProviderAdapter.class, ex.toString());
return (P)Class.forName(
"sun.util.locale.provider.HostLocaleProviderAdapterImpl")
.getMethod("get" + c.getSimpleName(), (Class<?>[]) null)
.invoke(null, (Object[]) null);
} catch (ClassNotFoundException |
NoSuchMethodException ex) {
// permissible exceptions as platform may not support host adapter
return null;
} catch (IllegalAccessException |
IllegalArgumentException |
InvocationTargetException ex) {
throw new ServiceConfigurationError(
"Host locale provider cannot be located.", ex);
}
return null;
}
/**

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2012, 2016, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2012, 2020, 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
@ -25,6 +25,7 @@
package sun.util.locale.provider;
import java.lang.reflect.InvocationTargetException;
import java.text.spi.BreakIteratorProvider;
import java.text.spi.CollatorProvider;
import java.text.spi.DateFormatProvider;
@ -37,6 +38,7 @@ import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.ServiceConfigurationError;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
@ -50,6 +52,8 @@ import sun.security.action.GetPropertyAction;
import sun.text.spi.JavaTimeDateTimePatternProvider;
import sun.util.spi.CalendarProvider;
import static java.lang.System.*;
/**
* The LocaleProviderAdapter abstract class.
*
@ -60,7 +64,7 @@ public abstract class LocaleProviderAdapter {
/**
* Adapter type.
*/
public static enum Type {
public enum Type {
JRE("sun.util.locale.provider.JRELocaleProviderAdapter", "sun.util.resources", "sun.text.resources"),
CLDR("sun.util.cldr.CLDRLocaleProviderAdapter", "sun.util.resources.cldr", "sun.text.resources.cldr"),
SPI("sun.util.locale.provider.SPILocaleProviderAdapter"),
@ -71,11 +75,11 @@ public abstract class LocaleProviderAdapter {
private final String UTIL_RESOURCES_PACKAGE;
private final String TEXT_RESOURCES_PACKAGE;
private Type(String className) {
Type(String className) {
this(className, null, null);
}
private Type(String className, String util, String text) {
Type(String className, String util, String text) {
CLASSNAME = className;
UTIL_RESOURCES_PACKAGE = util;
TEXT_RESOURCES_PACKAGE = text;
@ -113,12 +117,13 @@ public abstract class LocaleProviderAdapter {
/**
* Adapter lookup cache.
*/
private static ConcurrentMap<Class<? extends LocaleServiceProvider>, ConcurrentMap<Locale, LocaleProviderAdapter>>
private static final ConcurrentMap<Class<? extends LocaleServiceProvider>, ConcurrentMap<Locale, LocaleProviderAdapter>>
adapterCache = new ConcurrentHashMap<>();
static {
String order = GetPropertyAction.privilegedGetProperty("java.locale.providers");
List<Type> typeList = new ArrayList<>();
ArrayList<Type> typeList = new ArrayList<>();
String invalidTypeMessage = null;
// Check user specified adapter preference
if (order != null && !order.isEmpty()) {
@ -133,10 +138,9 @@ public abstract class LocaleProviderAdapter {
if (!typeList.contains(aType)) {
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());
} catch (IllegalArgumentException e) {
// construct a log message.
invalidTypeMessage = "Invalid locale provider adapter \"" + type + "\" ignored.";
}
}
}
@ -144,7 +148,7 @@ public abstract class LocaleProviderAdapter {
defaultLocaleProviderAdapter = Type.CLDR;
if (!typeList.isEmpty()) {
// bona fide preference exists
if (!(typeList.contains(Type.CLDR) || (typeList.contains(Type.JRE)))) {
if (!(typeList.contains(Type.CLDR) || typeList.contains(Type.JRE))) {
// Append FALLBACK as the last resort when no ResourceBundleBasedAdapter is available.
typeList.add(Type.FALLBACK);
defaultLocaleProviderAdapter = Type.FALLBACK;
@ -155,6 +159,15 @@ public abstract class LocaleProviderAdapter {
typeList.add(Type.JRE);
}
adapterPreference = Collections.unmodifiableList(typeList);
// Emit logs, if any, after 'adapterPreference' is initialized which is needed
// for logging.
if (invalidTypeMessage != null) {
// could be caused by the user specifying wrong
// provider name or format in the system property
getLogger(LocaleProviderAdapter.class.getCanonicalName())
.log(Logger.Level.INFO, invalidTypeMessage);
}
}
/**
@ -167,30 +180,25 @@ public abstract class LocaleProviderAdapter {
case SPI:
case HOST:
case FALLBACK:
LocaleProviderAdapter adapter = null;
LocaleProviderAdapter cached = adapterInstances.get(type);
if (cached == null) {
LocaleProviderAdapter adapter = adapterInstances.get(type);
if (adapter == null) {
try {
// lazily load adapters here
@SuppressWarnings("deprecation")
Object tmp = Class.forName(type.getAdapterClassName()).newInstance();
adapter = (LocaleProviderAdapter)tmp;
cached = adapterInstances.putIfAbsent(type, adapter);
adapter = (LocaleProviderAdapter)Class.forName(type.getAdapterClassName())
.getDeclaredConstructor().newInstance();
LocaleProviderAdapter cached = adapterInstances.putIfAbsent(type, adapter);
if (cached != null) {
adapter = cached;
}
} catch (ClassNotFoundException |
} catch (NoSuchMethodException |
InvocationTargetException |
ClassNotFoundException |
IllegalAccessException |
InstantiationException |
UnsupportedOperationException e) {
LocaleServiceProviderPool.config(LocaleProviderAdapter.class, e.toString());
adapterInstances.putIfAbsent(type, NONEXISTENT_ADAPTER);
if (defaultLocaleProviderAdapter == type) {
defaultLocaleProviderAdapter = Type.FALLBACK;
}
throw new ServiceConfigurationError("Locale provider adapter \"" +
type + "\"cannot be instantiated.", e);
}
} else if (cached != NONEXISTENT_ADAPTER) {
adapter = cached;
}
return adapter;
default:
@ -440,14 +448,4 @@ public abstract class LocaleProviderAdapter {
public abstract LocaleResources getLocaleResources(Locale locale);
public abstract Locale[] getAvailableLocales();
private static final LocaleProviderAdapter NONEXISTENT_ADAPTER = new NonExistentAdapter();
private static final class NonExistentAdapter extends FallbackLocaleProviderAdapter {
@Override
public LocaleProviderAdapter.Type getAdapterType() {
return null;
}
private NonExistentAdapter() {};
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2005, 2019, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2005, 2020, 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
@ -38,7 +38,6 @@ import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.spi.LocaleServiceProvider;
import sun.util.logging.PlatformLogger;
/**
* An instance of this class holds a set of the third party implementations of a particular
@ -121,11 +120,6 @@ public final class LocaleServiceProviderPool {
providerClass = c;
}
static void config(Class<? extends Object> caller, String message) {
PlatformLogger logger = PlatformLogger.getLogger(caller.getCanonicalName());
logger.config(message);
}
/**
* Lazy loaded set of available locales.
* Loading all locales is a very long operation.
@ -282,9 +276,10 @@ public final class LocaleServiceProviderPool {
if (providersObj != null) {
return providersObj;
} else if (isObjectProvider) {
config(LocaleServiceProviderPool.class,
"A locale sensitive service object provider returned null, " +
"which should not happen. Provider: " + lsp + " Locale: " + locale);
System.getLogger(LocaleServiceProviderPool.class.getCanonicalName())
.log(System.Logger.Level.INFO,
"A locale sensitive service object provider returned null, " +
"which should not happen. Provider: " + lsp + " Locale: " + locale);
}
}
}
@ -341,9 +336,8 @@ public final class LocaleServiceProviderPool {
// ResourceBundle.Control.getCandidateLocales. The result
// returned by getCandidateLocales are already normalized
// (no extensions) for service look up.
List<Locale> lookupLocales = Control.getNoFallbackControl(Control.FORMAT_DEFAULT)
return Control.getNoFallbackControl(Control.FORMAT_DEFAULT)
.getCandidateLocales("", locale);
return lookupLocales;
}
/**
@ -370,8 +364,9 @@ public final class LocaleServiceProviderPool {
// should have well-formed fields except
// for ja_JP_JP and th_TH_TH. Therefore,
// it should never enter in this catch clause.
config(LocaleServiceProviderPool.class,
"A locale(" + locale + ") has non-empty extensions, but has illformed fields.");
System.getLogger(LocaleServiceProviderPool.class.getCanonicalName())
.log(System.Logger.Level.INFO,
"A locale(" + locale + ") has non-empty extensions, but has illformed fields.");
// Fallback - script field will be lost.
lookupLocale = new Locale(locale.getLanguage(), locale.getCountry(), locale.getVariant());
@ -402,9 +397,9 @@ public final class LocaleServiceProviderPool {
* @param params provider specific params
* @return localized object from the provider
*/
public S getObject(P lsp,
Locale locale,
String key,
Object... params);
S getObject(P lsp,
Locale locale,
String key,
Object... params);
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2012, 2018, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2012, 2020, 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
@ -43,9 +43,9 @@ import java.text.spi.NumberFormatProvider;
import java.util.Arrays;
import java.util.Locale;
import java.util.Map;
import java.util.ServiceConfigurationError;
import java.util.ServiceLoader;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.spi.CalendarDataProvider;
import java.util.spi.CalendarNameProvider;
import java.util.spi.CurrencyNameProvider;
@ -72,7 +72,7 @@ public class SPILocaleProviderAdapter extends AuxLocaleProviderAdapter {
@Override
protected <P extends LocaleServiceProvider> P findInstalledProvider(final Class<P> c) {
try {
return AccessController.doPrivileged(new PrivilegedExceptionAction<P>() {
return AccessController.doPrivileged(new PrivilegedExceptionAction<>() {
@Override
@SuppressWarnings(value={"unchecked", "deprecation"})
public P run() {
@ -91,8 +91,8 @@ public class SPILocaleProviderAdapter extends AuxLocaleProviderAdapter {
} catch (ClassNotFoundException |
InstantiationException |
IllegalAccessException e) {
LocaleServiceProviderPool.config(SPILocaleProviderAdapter.class, e.toString());
return null;
throw new ServiceConfigurationError(
"SPI locale provider cannot be instantiated.", e);
}
}
@ -102,9 +102,9 @@ public class SPILocaleProviderAdapter extends AuxLocaleProviderAdapter {
}
});
} catch (PrivilegedActionException e) {
LocaleServiceProviderPool.config(SPILocaleProviderAdapter.class, e.toString());
throw new ServiceConfigurationError(
"SPI locale provider cannot be instantiated.", e);
}
return null;
}
/*
@ -112,7 +112,7 @@ public class SPILocaleProviderAdapter extends AuxLocaleProviderAdapter {
* following "<provider class name>Delegate" convention.
*/
private interface Delegate<P extends LocaleServiceProvider> {
default public void addImpl(P impl) {
default void addImpl(P impl) {
for (Locale l : impl.getAvailableLocales()) {
getDelegateMap().putIfAbsent(l, impl);
}
@ -121,7 +121,7 @@ public class SPILocaleProviderAdapter extends AuxLocaleProviderAdapter {
/*
* Obtain the real SPI implementation, using locale fallback
*/
default public P getImpl(Locale locale) {
default P getImpl(Locale locale) {
for (Locale l : LocaleServiceProviderPool.getLookupLocales(locale.stripExtensions())) {
P ret = getDelegateMap().get(l);
if (ret != null) {
@ -131,13 +131,13 @@ public class SPILocaleProviderAdapter extends AuxLocaleProviderAdapter {
return null;
}
public Map<Locale, P> getDelegateMap();
Map<Locale, P> getDelegateMap();
default public Locale[] getAvailableLocalesDelegate() {
return getDelegateMap().keySet().stream().toArray(Locale[]::new);
default Locale[] getAvailableLocalesDelegate() {
return getDelegateMap().keySet().toArray(new Locale[0]);
}
default public boolean isSupportedLocaleDelegate(Locale locale) {
default boolean isSupportedLocaleDelegate(Locale locale) {
Map<Locale, P> map = getDelegateMap();
Locale override = CalendarDataUtility.findRegionOverride(locale);

View File

@ -1,34 +0,0 @@
/*
* Copyright (c) 2012, 2014, 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;
/**
* LocaleProviderAdapter implementation for the Unix locale data
*
* @author Naoto Sato
*/
public class HostLocaleProviderAdapterImpl {
}

View File

@ -23,10 +23,16 @@
import java.text.*;
import java.text.spi.*;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.LogManager;
import java.util.logging.LogRecord;
import java.util.logging.StreamHandler;
import java.util.spi.*;
import java.util.stream.IntStream;
import sun.util.locale.provider.LocaleProviderAdapter;
import static java.util.logging.LogManager.*;
public class LocaleProviders {
private static final boolean IS_WINDOWS = System.getProperty("os.name").startsWith("Windows");
@ -92,6 +98,10 @@ public class LocaleProviders {
bug8232860Test();
break;
case "bug8245241Test":
bug8245241Test(args[1]);
break;
default:
throw new RuntimeException("Test method '"+methodName+"' not found.");
}
@ -227,7 +237,7 @@ public class LocaleProviders {
System.out.println(new SimpleDateFormat("z", new Locale(lang, ctry)).parse("UTC"));
} catch (ParseException pe) {
// ParseException is fine in this test, as it's not "UTC"
}
}
}
static void bug8013903Test() {
@ -374,4 +384,24 @@ public class LocaleProviders {
"provider is not HOST: " + type);
}
}
static void bug8245241Test(String expected) {
LogRecord[] lra = new LogRecord[1];
StreamHandler handler = new StreamHandler() {
@Override
public void publish(LogRecord record) {
lra[0] = record;
}
};
getLogManager().getLogger("").addHandler(handler);
DateFormat.getDateInstance(); // this will init LocaleProviderAdapter
handler.flush();
if (lra[0] == null ||
lra[0].getLevel() != Level.INFO ||
!lra[0].getMessage().equals(expected)) {
throw new RuntimeException("Expected log was not emitted. LogRecord: " + lra[0]);
}
}
}

View File

@ -25,7 +25,7 @@
* @test
* @bug 6336885 7196799 7197573 7198834 8000245 8000615 8001440 8008577
* 8010666 8013086 8013233 8013903 8015960 8028771 8054482 8062006
* 8150432 8215913 8220227 8228465 8232871 8232860 8236495
* 8150432 8215913 8220227 8228465 8232871 8232860 8236495 8245241
* @summary tests for "java.locale.providers" system property
* @library /test/lib
* @build LocaleProviders
@ -162,6 +162,10 @@ public class LocaleProvidersRun {
//testing 8232860 fix. (macOS/Windows only)
testRun("HOST", "bug8232860Test", "", "", "");
//testing 8245241 fix.
testRun("FOO", "bug8245241Test",
"Invalid locale provider adapter \"FOO\" ignored.", "", "");
}
private static void testRun(String prefList, String methodName,