Class Providers<P extends Provider<?>>

java.lang.Object
opennlp.tools.util.ext.Providers<P>
Type Parameters:
P - The SPI, a sub-interface of Provider.

public final class Providers<P extends Provider<?>> extends Object
Resolves the 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:
  • Field Details

  • 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 of Provider.
      loader - The class loader to look providers up with, or null to resolve one.
      configuration - The source of the configuration keys, or null for the default.
      trusted - Accepts the provider classes that may be used, or null for all.
      Throws:
      IllegalArgumentException - Thrown if spi is null or not a sub-interface of Provider.
      ProviderResolutionException - Thrown if the configuration or the service files cannot be read, or if trusted fails.
  • Method Details

    • of

      public static <P extends Provider<?>> Providers<P> of(Class<P> spi)
      Looks the providers of an SPI up with the thread context class loader, or with the class loader of spi if the thread has none or if it cannot see spi. 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 calls of(Class, ClassLoader).
      Type Parameters:
      P - The SPI.
      Parameters:
      spi - The SPI. Must be a sub-interface of Provider.
      Returns:
      The providers of spi. Never null.
      Throws:
      IllegalArgumentException - Thrown if spi is null or not a sub-interface of Provider.
      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)
      Looks the providers of an SPI up with a class loader.
      Type Parameters:
      P - The SPI.
      Parameters:
      spi - The SPI. Must be a sub-interface of Provider.
      loader - The class loader to look providers up with. Must not be null.
      Returns:
      The providers of spi. Never null.
      Throws:
      IllegalArgumentException - Thrown if an argument is null, or if spi is not a sub-interface of Provider.
      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 the providers of 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 of Provider.
      loader - The class loader to look providers up with. Must not be null.
      configuration - Answers configurationKey(), disabledKey() and allowedKey() with the configured value or null. Must not be null, and must be thread-safe, cheap and free of side effects, as it is called on every resolution.
      Returns:
      The providers of spi. Never null.
      Throws:
      IllegalArgumentException - Thrown if an argument is null, or if spi is not a sub-interface of Provider.
      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 the providers of 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 of Provider.
      loader - The class loader to look providers up with. Must not be null.
      trusted - Accepts the provider classes that may be used. Must not be null.
      Returns:
      The providers of spi. Never null.
      Throws:
      IllegalArgumentException - Thrown if an argument is null, or if spi is not a sub-interface of Provider.
      ProviderResolutionException - Thrown if the configuration or the service files cannot be read, or if trusted throws.
    • 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 of Provider.
      loader - The class loader to look providers up with. Must not be null.
      configuration - Answers the configuration keys. Must not be null.
      trusted - Accepts the provider classes that may be used. Must not be null.
      Returns:
      The providers of spi. Never null.
      Throws:
      IllegalArgumentException - Thrown if an argument is null, or if spi is not a sub-interface of Provider.
      ProviderResolutionException - Thrown if the service files cannot be read, or if trusted throws.
    • requireArguments

      private static void requireArguments(List<String> names, Object... arguments)
      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 of arguments.
      arguments - The arguments to check.
      Throws:
      IllegalArgumentException - Thrown if an argument is null, naming all of them.
    • configurationKey

      public String 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. Never null.
    • disabledKey

      public String 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 by installed(). 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. Never null.
    • allowedKey

      public String 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. Use ofTrusted(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. Never null.
    • installed

      public List<P> installed()
      Returns:
      The providers in lookup order, including unavailable ones and those disabled by name. Unmodifiable and never null.
    • byName

      public Optional<P> byName(String name)
      Resolves an available provider by name, unless the name is disabled. If several available providers have the name, the one with the highest priority is returned. The key from configurationKey() is not applied.
      Parameters:
      name - The case-sensitive provider name. Must not be null or blank.
      Returns:
      The provider, or Optional.empty() if the name is disabled or no available provider has it.
      Throws:
      IllegalArgumentException - Thrown if name is null or blank.
      AmbiguousProviderException - Thrown if several providers of that name have the highest priority.
    • supporting

      public List<P> supporting(ProviderSpec spec)
      Lists the available providers that support a spec, without the disabled ones. The key from configurationKey() is not applied.
      Parameters:
      spec - The spec. Must not be null.
      Returns:
      The providers ordered by descending priority, providers of equal priority in lookup order. Unmodifiable and never null.
      Throws:
      IllegalArgumentException - Thrown if spec is null.
    • select

      public P select(ProviderSpec spec)
      Resolves the provider for a spec. The candidates are the available providers that support spec and are not disabled. If the key from configurationKey() 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 be null.
      Returns:
      The provider. Never null.
      Throws:
      IllegalArgumentException - Thrown if spec is null.
      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 be null.
      disabled - The disabled provider names and class names. Must not be null.
      selected - The selected name, or null to keep every name.
      Returns:
      The available registrations that support spec, ordered by descending priority. A new, modifiable list.
    • isAvailable

      private boolean isAvailable(Providers.Registration<P> registration)
    • supports

      private boolean supports(Providers.Registration<P> registration, ProviderSpec spec)
    • isTied

      private boolean isTied(List<Providers.Registration<P>> sorted)
    • tiedClasses

      private List<String> tiedClasses(List<Providers.Registration<P>> sorted)
    • hint

      private String hint(String selected)
      Parameters:
      selected - The selected name, or null if none is configured.
      Returns:
      The advice added to an AmbiguousProviderException.
    • unsatisfiedMessage

      private String unsatisfiedMessage(ProviderSpec spec, String selected, Set<String> disabled)
      Parameters:
      spec - The spec no provider was resolved for.
      selected - The selected name, or null if none is configured.
      disabled - The disabled provider names and class names.
      Returns:
      The message of an UnsatisfiedProviderException.
    • configuredName

      private String configuredName()
      Returns:
      The name the configuration selects, without surrounding whitespace, or null if none is configured.
    • configured

      private String configured(String key)
      Reads a configuration key through the source of this instance.
      Parameters:
      key - The key to read. Must not be null.
      Returns:
      The configured value, or null if the key is not configured.
      Throws:
      ProviderResolutionException - Thrown if the configuration source fails.
    • disabledNames

      private Set<String> disabledNames()
      Returns:
      The provider names and class names the configuration disables. Never null.
    • names

      private Set<String> names(String value)
    • allowedClasses

      private Set<String> allowedClasses()
      Returns:
      The provider class names and package prefixes the configuration allows, or an empty set when every provider is allowed. Never null.
    • isAllowed

      private boolean isAllowed(Set<String> allowed, String provided)
    • resolveLoader

      private ClassLoader resolveLoader(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. A thread of the common ForkJoinPool carries the system class loader, which usually does not see the SPI of an application.
      Parameters:
      explicit - The class loader an application passed, or null.
      Returns:
      The class loader to look providers up with. Never null.
    • fileConfiguration

      private 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.
      Parameters:
      loader - The class loader to read the configuration with. Must not be null.
      Returns:
      The configuration source. Never null.
      Throws:
      ProviderResolutionException - Thrown if a configuration file cannot be read.
    • readConfiguration

      private Map<String,String> readConfiguration(ClassLoader loader)
      Parameters:
      loader - The class loader to read the configuration with. Must not be null.
      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

      private Providers.ConfigurationFile read(URL resource)
      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 be null.
      Returns:
      The file. Never null.
      Throws:
      ProviderResolutionException - Thrown if resource cannot be read, is not encoded in UTF-8 or holds an invalid "configuration.ordinal"<P extends Provider<?>>.
    • stripByteOrderMark

      private Properties stripByteOrderMark(Properties content)
    • printable

      private String printable(URL resource)
      Returns:
      The location without the parts that may hold credentials, for a log or a message.
    • ordinal

      private int ordinal(URL resource, Properties content)
      Returns:
      The value of "configuration.ordinal"<P extends Provider<?>>, or 0 if the file has none.
      Throws:
      ProviderResolutionException - Thrown if the value is not a number.
    • lookup

      private Providers.Lookup<P> lookup(ClassLoader loader)
      Looks the providers up, skipping the registrations that cannot be used.
      Parameters:
      loader - The class loader to look providers up with. Must not be null.
      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.
    • warnAboutSharedNames

      private void warnAboutSharedNames(List<Providers.Registration<P>> found)
      Reports providers that share a name, which can be a replacement or an unwanted override.
    • isTrusted

      private boolean isTrusted(Class<?> provided)
      Returns:
      true if the predicate accepts the class.
      Throws:
      ProviderResolutionException - Thrown if the predicate throws.
    • codeSource

      private String codeSource(Class<?> provided)
      Returns:
      The location the class was loaded from, or "unknown".
    • lookupFailed

      private ProviderResolutionException lookupFailed(Throwable cause)
    • rethrowFatal

      private void rethrowFatal(Throwable failure)
      Rethrows a VirtualMachineError, such as an OutOfMemoryError or a StackOverflowError, that a provider or a class loader ran into. It leaves the JVM in a state that skipping the provider does not recover from. ServiceLoader wraps what the constructor of a provider throws in a ServiceConfigurationError, so the causes of failure are checked as well.
      Parameters:
      failure - The failure to check. Must not be null.
    • call

      private <R> Optional<R> call(P provider, String method, Supplier<R> 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 returned null or threw.
    • warn

      private void warn(P provider, String method, String failure)
      Reports a provider method that could not be used, once per provider and method at WARN and at DEBUG afterwards, 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

      private boolean isValidName(String name)
      Accepts ASCII names only. A name is compared by String.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 be null.
      Returns:
      true if name can be used as a configuration value.