Class Providers<P extends Provider<?>>
- Type Parameters:
P- The SPI, a sub-interface ofProvider.
providers of one SPI.
The providers are looked up with ServiceLoader when an instance is created, so
of(Class) belongs into the startup of an application rather than into a request, and a
new instance is needed to see providers added later. Availability, support for a spec and the
configuration are read on every call. Instances are thread-safe; the only state that changes is
the set of failures already reported.
Keep the instance in a field owned by the application and not in a static field, since
OpenNLP can be deployed in a class loader shared by several applications.
Resolution is steered by name through configurationKey(), disabledKey() and
allowedKey(), and by the provider class itself through
ofTrusted(Class, ClassLoader, Predicate).
- Since:
- 3.0.0
- See Also:
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionprivate static final recordA configuration file of a class loader.private static final recordThe providers oneServiceLoaderpass of the constructor found, and how many it left out.private static final recordThe entries of a configuration value, kept to parse a value that does not change only once.private static final recordA provider with the name and priority read once at lookup. -
Field Summary
FieldsModifier and TypeFieldDescriptionstatic final StringThe suffix of the configuration key that limits which provider classes may be used, seeallowedKey().private final Stringprivate static final Stringprivate static final charprivate static final Stringprivate final UnaryOperator<String> static final StringThe resource read for configuration keys, once per lookup and class loader, encoded in UTF-8.static final StringThe prefix of the configuration key that selects a provider by name forselect(opennlp.tools.util.ext.ProviderSpec).private final Stringprivate Providers.Parsedstatic final StringThe suffix of the configuration key that disables providers by name, seedisabledKey().private final Stringprivate static final Stringprivate final Stringprivate static final org.slf4j.Loggerprivate static final Stringprivate static final intBounds a lookup whose iterator neither yields a provider nor reaches its end, whichServiceLoaderdoes when it cannot list the service files at all.private static final intprivate static final Stringprivate static final charprivate static final StringStands for an allow list that holds no entry, which allows no provider at all.static final StringThe key that orders several "META-INF/opennlp/providers.properties"<P extends Provider<?>> files,0by default.private static final Stringprivate static final charprivate static final Stringprivate final List<Providers.Registration<P>> private static final Stringprivate static final Stringprivate final intprivate static final Stringprivate static final Stringprivate static final String -
Constructor Summary
ConstructorsModifierConstructorDescriptionprivateProviders(Class<P> spi, ClassLoader loader, UnaryOperator<String> configuration, Predicate<Class<?>> trusted) -
Method Summary
Modifier and TypeMethodDescriptionResolves an availableproviderby name, unless the name is disabled.private <R> Optional<R> Calls a provider method and logs a failure instead of throwing it.private List<Providers.Registration<P>> candidates(ProviderSpec spec, Set<String> disabled, String selected) private StringcodeSource(Class<?> provided) private Stringconfigured(String key) Reads a configuration key through the source of this instance.private Stringprivate UnaryOperator<String> fileConfiguration(ClassLoader loader) Reads "META-INF/opennlp/providers.properties"<P extends Provider<?>> of a class loader, merged in ascending order of "configuration.ordinal"<P extends Provider<?>>, and lets a system property of the same name win over it.private Stringprivate booleanprivate booleanisAvailable(Providers.Registration<P> registration) private booleanisTied(List<Providers.Registration<P>> sorted) private booleanprivate booleanisValidName(String name) Accepts ASCII names only.private Providers.Lookup<P> lookup(ClassLoader loader) Looks the providers up, skipping the registrations that cannot be used.private ProviderResolutionExceptionlookupFailed(Throwable cause) Looks theprovidersof an SPI up with the thread context class loader, or with the class loader ofspiif the thread has none or if it cannot seespi.of(Class<P> spi, ClassLoader loader) Looks theprovidersof an SPI up with a class loader.of(Class<P> spi, ClassLoader loader, UnaryOperator<String> configuration) Looks theprovidersof an SPI up with a class loader and reads the configuration keys from an application's own source instead of "META-INF/opennlp/providers.properties"<P extends Provider<?>> and the system properties.of(Class<P> spi, ClassLoader loader, UnaryOperator<String> configuration, Predicate<Class<?>> trusted) ofTrusted(Class<P> spi, ClassLoader loader, Predicate<Class<?>> trusted) Looks theprovidersof an SPI up with a class loader, using only the provider classes a predicate accepts, which lets an application decide by the code source, the module or the signers of a class instead of by its name.private intordinal(URL resource, Properties content) private Stringprivate Providers.ConfigurationFileReads one configuration file, without caching its jar, so that an application can be undeployed and its files replaced.readConfiguration(ClassLoader loader) private static voidrequireArguments(List<String> names, Object... arguments) Checks the arguments of a factory method at once, so that a caller sees every missing one.private ClassLoaderresolveLoader(ClassLoader explicit) Resolves the class loader to look providers up with: the thread context class loader when it sees this SPI, the class loader of the SPI otherwise.private voidrethrowFatal(Throwable failure) Rethrows aVirtualMachineError, such as anOutOfMemoryErroror aStackOverflowError, that a provider or a class loader ran into.select(ProviderSpec spec) private PropertiesstripByteOrderMark(Properties content) supporting(ProviderSpec spec) private booleansupports(Providers.Registration<P> registration, ProviderSpec spec) tiedClasses(List<Providers.Registration<P>> sorted) private StringunsatisfiedMessage(ProviderSpec spec, String selected, Set<String> disabled) private voidReports a provider method that could not be used, once per provider and method atWARNand atDEBUGafterwards, so a resolution on a request path does not flood the log.private voidwarnAboutSharedNames(List<Providers.Registration<P>> found) Reports providers that share a name, which can be a replacement or an unwanted override.
-
Field Details
-
CONFIGURATION_KEY_PREFIX
The prefix of the configuration key that selects a provider by name forselect(opennlp.tools.util.ext.ProviderSpec). The full key is the prefix followed by the fully qualified name of the SPI, seeconfigurationKey().- See Also:
-
DISABLED_KEY_SUFFIX
The suffix of the configuration key that disables providers by name, seedisabledKey().- See Also:
-
ALLOWED_KEY_SUFFIX
The suffix of the configuration key that limits which provider classes may be used, seeallowedKey().- See Also:
-
CONFIGURATION_FILE
The resource read for configuration keys, once per lookup and class loader, encoded in UTF-8. Several files are merged by their "configuration.ordinal"<P extends Provider<?>>, so the highest one wins, and a system property of the same name wins over all of them. Every jar of the class loader can carry this file. In a native image it is read only when it is registered as a resource.- See Also:
-
ORDINAL_KEY
The key that orders several "META-INF/opennlp/providers.properties"<P extends Provider<?>> files,0by default.- See Also:
-
logger
private static final org.slf4j.Logger logger -
NAME_SEPARATOR
private static final char NAME_SEPARATOR- See Also:
-
SERVICE_PREFIX
- See Also:
-
PACKAGE_SEPARATOR_PATH
private static final char PACKAGE_SEPARATOR_PATH- See Also:
-
CLASS_SUFFIX
- See Also:
-
NOTHING_ALLOWED
Stands for an allow list that holds no entry, which allows no provider at all.- See Also:
-
PACKAGE_SEPARATOR
- See Also:
-
BYTE_ORDER_MARK
private static final char BYTE_ORDER_MARK- See Also:
-
MAX_NAME_LENGTH
private static final int MAX_NAME_LENGTH- See Also:
-
LOOKUP_FAILED
- See Also:
-
SKIPPED_ENTRY
- See Also:
-
SKIPPED_CALL
- See Also:
-
NAME_METHOD
- See Also:
-
PRIORITY_METHOD
- See Also:
-
AVAILABLE_METHOD
- See Also:
-
SUPPORTS_METHOD
- See Also:
-
SAME_PRIORITY
- See Also:
-
INVALID_NAME
- See Also:
-
MAX_CONSECUTIVE_FAILURES
private static final int MAX_CONSECUTIVE_FAILURESBounds a lookup whose iterator neither yields a provider nor reaches its end, whichServiceLoaderdoes when it cannot list the service files at all. The bound is far above the number of broken registrations a class path can hold, so a lookup that only skips unusable providers is not cut short.- See Also:
-
spi
-
configurationKey
-
disabledKey
-
allowedKey
-
configuration
-
trusted
-
loaderName
-
registrations
-
installed
-
skipped
private final int skipped -
warned
-
disabled
-
-
Constructor Details
-
Providers
private Providers(Class<P> spi, ClassLoader loader, UnaryOperator<String> configuration, Predicate<Class<?>> trusted) - Parameters:
spi- The SPI. Must be a sub-interface ofProvider.loader- The class loader to look providers up with, ornullto resolve one.configuration- The source of the configuration keys, ornullfor the default.trusted- Accepts the provider classes that may be used, ornullfor all.- Throws:
IllegalArgumentException- Thrown ifspiisnullor not a sub-interface ofProvider.ProviderResolutionException- Thrown if the configuration or the service files cannot be read, or iftrustedfails.
-
-
Method Details
-
of
Looks theprovidersof an SPI up with the thread context class loader, or with the class loader ofspiif the thread has none or if it cannot seespi. On a thread whose context class loader is not the application's, such as a thread of a pool or of a container, this finds the providers of the SPI's own class loader only, so a library or a framework integration captures the class loader at startup and callsof(Class, ClassLoader).- Type Parameters:
P- The SPI.- Parameters:
spi- The SPI. Must be a sub-interface ofProvider.- Returns:
- The providers of
spi. Nevernull. - Throws:
IllegalArgumentException- Thrown ifspiisnullor not a sub-interface ofProvider.ProviderResolutionException- Thrown if the configuration or the service files cannot be read.
-
of
Looks theprovidersof an SPI up with a class loader.- Type Parameters:
P- The SPI.- Parameters:
spi- The SPI. Must be a sub-interface ofProvider.loader- The class loader to look providers up with. Must not benull.- Returns:
- The providers of
spi. Nevernull. - Throws:
IllegalArgumentException- Thrown if an argument isnull, or ifspiis not a sub-interface ofProvider.ProviderResolutionException- Thrown if the configuration or the service files cannot be read.
-
of
public static <P extends Provider<?>> Providers<P> of(Class<P> spi, ClassLoader loader, UnaryOperator<String> configuration) Looks theprovidersof an SPI up with a class loader and reads the configuration keys from an application's own source instead of "META-INF/opennlp/providers.properties"<P extends Provider<?>> and the system properties. Applications that share a class loader hierarchy, such as several deployments in one server, use this to configure resolution per application.- Type Parameters:
P- The SPI.- Parameters:
spi- The SPI. Must be a sub-interface ofProvider.loader- The class loader to look providers up with. Must not benull.configuration- AnswersconfigurationKey(),disabledKey()andallowedKey()with the configured value ornull. Must not benull, and must be thread-safe, cheap and free of side effects, as it is called on every resolution.- Returns:
- The providers of
spi. Nevernull. - Throws:
IllegalArgumentException- Thrown if an argument isnull, or ifspiis not a sub-interface ofProvider.ProviderResolutionException- Thrown if the service files cannot be read.
-
ofTrusted
public static <P extends Provider<?>> Providers<P> ofTrusted(Class<P> spi, ClassLoader loader, Predicate<Class<?>> trusted) Looks theprovidersof an SPI up with a class loader, using only the provider classes a predicate accepts, which lets an application decide by the code source, the module or the signers of a class instead of by its name.The predicate is applied to each provider class the configuration permits, after the class has been loaded and before it is initialized and instantiated, so a rejected provider runs neither its static initializer nor its constructor. The predicate must not initialize the class either. An exception from it ends the lookup.
- Type Parameters:
P- The SPI.- Parameters:
spi- The SPI. Must be a sub-interface ofProvider.loader- The class loader to look providers up with. Must not benull.trusted- Accepts the provider classes that may be used. Must not benull.- Returns:
- The providers of
spi. Nevernull. - Throws:
IllegalArgumentException- Thrown if an argument isnull, or ifspiis not a sub-interface ofProvider.ProviderResolutionException- Thrown if the configuration or the service files cannot be read, or iftrustedthrows.
-
of
public static <P extends Provider<?>> Providers<P> of(Class<P> spi, ClassLoader loader, UnaryOperator<String> configuration, Predicate<Class<?>> trusted) - Type Parameters:
P- The SPI.- Parameters:
spi- The SPI. Must be a sub-interface ofProvider.loader- The class loader to look providers up with. Must not benull.configuration- Answers the configuration keys. Must not benull.trusted- Accepts the provider classes that may be used. Must not benull.- Returns:
- The providers of
spi. Nevernull. - Throws:
IllegalArgumentException- Thrown if an argument isnull, or ifspiis not a sub-interface ofProvider.ProviderResolutionException- Thrown if the service files cannot be read, or iftrustedthrows.
-
requireArguments
Checks the arguments of a factory method at once, so that a caller sees every missing one.- Parameters:
names- The names of the arguments, in the order ofarguments.arguments- The arguments to check.- Throws:
IllegalArgumentException- Thrown if an argument isnull, naming all of them.
-
configurationKey
- Returns:
- The configuration key that selects a provider by name for
select(opennlp.tools.util.ext.ProviderSpec): "opennlp.provider."<P extends Provider<?>> followed by the fully qualified name of the SPI. Nevernull.
-
disabledKey
- Returns:
- The configuration key that disables providers of this SPI, a comma separated list of
provider names and provider class names:
configurationKey()followed by ".disabled"<P extends Provider<?>>. A provider disabled by name is not resolved but stays listed byinstalled(). A provider disabled by class name is not instantiated at all, which needs the class name to be configured before the providers are looked up. Nevernull.
-
allowedKey
- Returns:
- The configuration key that limits which provider classes of this SPI may be used:
configurationKey()followed by ".allowed"<P extends Provider<?>>. The value is a comma separated list of provider class names and of package prefixes, which end with a dot; an unset or blank value allows every provider, a value that holds only separators allows none. It matches class names, not their origin. UseofTrusted(Class, ClassLoader, Predicate)to validate provider classes. Unlike the other keys it is read from a system property or from the source an application passes only, never from "META-INF/opennlp/providers.properties"<P extends Provider<?>>, which any jar can carry. Providers are checked against it before they are instantiated, so it has to be configured before the lookup. Nevernull.
-
installed
- Returns:
- The providers in lookup order, including unavailable ones and those disabled by
name. Unmodifiable and never
null.
-
byName
Resolves an availableproviderby name, unless the name is disabled. If several available providers have the name, the one with the highest priority is returned. The key fromconfigurationKey()is not applied.- Parameters:
name- The case-sensitive provider name. Must not benullor blank.- Returns:
- The provider, or
Optional.empty()if the name is disabled or no available provider has it. - Throws:
IllegalArgumentException- Thrown ifnameisnullor blank.AmbiguousProviderException- Thrown if several providers of that name have the highest priority.
-
supporting
Lists the availableprovidersthat support aspec, without the disabled ones. The key fromconfigurationKey()is not applied.- Parameters:
spec- The spec. Must not benull.- Returns:
- The providers ordered by descending priority, providers of equal priority in lookup
order. Unmodifiable and never
null. - Throws:
IllegalArgumentException- Thrown ifspecisnull.
-
select
Resolves theproviderfor aspec. The candidates are the available providers that supportspecand are not disabled. If the key fromconfigurationKey()holds a nonblank value, only candidates with that name, surrounding whitespace ignored, remain. The candidate with the highest priority is returned.- Parameters:
spec- The spec. Must not benull.- Returns:
- The provider. Never
null. - Throws:
IllegalArgumentException- Thrown ifspecisnull.UnsatisfiedProviderException- Thrown if no candidate remains.AmbiguousProviderException- Thrown if several candidates have the highest priority.
-
candidates
private List<Providers.Registration<P>> candidates(ProviderSpec spec, Set<String> disabled, String selected) - Parameters:
spec- The spec. Must not benull.disabled- The disabled provider names and class names. Must not benull.selected- The selected name, ornullto keep every name.- Returns:
- The available registrations that support
spec, ordered by descending priority. A new, modifiable list.
-
isAvailable
-
supports
-
isTied
-
tiedClasses
-
hint
- Parameters:
selected- The selected name, ornullif none is configured.- Returns:
- The advice added to an
AmbiguousProviderException.
-
unsatisfiedMessage
- Parameters:
spec- The spec no provider was resolved for.selected- The selected name, ornullif none is configured.disabled- The disabled provider names and class names.- Returns:
- The message of an
UnsatisfiedProviderException.
-
configuredName
- Returns:
- The name the configuration selects, without surrounding whitespace, or
nullif none is configured.
-
configured
Reads a configuration key through the source of this instance.- Parameters:
key- The key to read. Must not benull.- Returns:
- The configured value, or
nullif the key is not configured. - Throws:
ProviderResolutionException- Thrown if the configuration source fails.
-
disabledNames
- Returns:
- The provider names and class names the configuration disables. Never
null.
-
names
-
allowedClasses
- Returns:
- The provider class names and package prefixes the configuration allows, or an empty
set when every provider is allowed. Never
null.
-
isAllowed
-
resolveLoader
Resolves the class loader to look providers up with: the thread context class loader when it sees this SPI, the class loader of the SPI otherwise. A thread of the commonForkJoinPoolcarries the system class loader, which usually does not see the SPI of an application.- Parameters:
explicit- The class loader an application passed, ornull.- Returns:
- The class loader to look providers up with. Never
null.
-
fileConfiguration
Reads "META-INF/opennlp/providers.properties"<P extends Provider<?>> of a class loader, merged in ascending order of "configuration.ordinal"<P extends Provider<?>>, and lets a system property of the same name win over it.- Parameters:
loader- The class loader to read the configuration with. Must not benull.- Returns:
- The configuration source. Never
null. - Throws:
ProviderResolutionException- Thrown if a configuration file cannot be read.
-
readConfiguration
- Parameters:
loader- The class loader to read the configuration with. Must not benull.- Returns:
- The merged content of the configuration files. Never
null. - Throws:
ProviderResolutionException- Thrown if the class loader cannot list the configuration files or one of them cannot be read.
-
read
Reads one configuration file, without caching its jar, so that an application can be undeployed and its files replaced.- Parameters:
resource- The configuration file to read. Must not benull.- Returns:
- The file. Never
null. - Throws:
ProviderResolutionException- Thrown ifresourcecannot be read, is not encoded in UTF-8 or holds an invalid "configuration.ordinal"<P extends Provider<?>>.
-
stripByteOrderMark
-
printable
- Returns:
- The location without the parts that may hold credentials, for a log or a message.
-
ordinal
- Returns:
- The value of "configuration.ordinal"<P extends Provider<?>>, or
0if the file has none. - Throws:
ProviderResolutionException- Thrown if the value is not a number.
-
lookup
Looks the providers up, skipping the registrations that cannot be used.- Parameters:
loader- The class loader to look providers up with. Must not benull.- Returns:
- The registrations in lookup order and the number of skipped ones. Never
null. - Throws:
ProviderResolutionException- Thrown if the service files cannot be read or the lookup does not advance.
-
isTrusted
- Returns:
trueif the predicate accepts the class.- Throws:
ProviderResolutionException- Thrown if the predicate throws.
-
codeSource
- Returns:
- The location the class was loaded from, or
"unknown".
-
lookupFailed
-
rethrowFatal
Rethrows aVirtualMachineError, such as anOutOfMemoryErroror aStackOverflowError, that a provider or a class loader ran into. It leaves the JVM in a state that skipping the provider does not recover from.ServiceLoaderwraps what the constructor of a provider throws in aServiceConfigurationError, so the causes offailureare checked as well.- Parameters:
failure- The failure to check. Must not benull.
-
call
Calls a provider method and logs a failure instead of throwing it.- Type Parameters:
R- The result type.- Parameters:
provider- The provider to call.method- The name of the called method, for the log message.call- The call.- Returns:
- The result, or
Optional.empty()if the call returnednullor threw.
-
warn
Reports a provider method that could not be used, once per provider and method atWARNand atDEBUGafterwards, so a resolution on a request path does not flood the log.- Parameters:
provider- The provider that failed.method- The name of the called method.failure- The failure to report.
-
isValidName
Accepts ASCII names only. A name is compared byString.equals(java.lang.Object)with a configuration value, and a non-ASCII name, such as one with an umlaut, can be written precomposed or decomposed, or be changed by the platform encoding of a command line or an environment.- Parameters:
name- The name of a provider. Must not benull.- Returns:
trueifnamecan be used as a configuration value.
-