0N/A/*
3909N/A * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
0N/A * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
0N/A *
0N/A * This code is free software; you can redistribute it and/or modify it
0N/A * under the terms of the GNU General Public License version 2 only, as
2362N/A * published by the Free Software Foundation. Oracle designates this
0N/A * particular file as subject to the "Classpath" exception as provided
2362N/A * by Oracle in the LICENSE file that accompanied this code.
0N/A *
0N/A * This code is distributed in the hope that it will be useful, but WITHOUT
0N/A * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
0N/A * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
0N/A * version 2 for more details (a copy is included in the LICENSE file that
0N/A * accompanied this code).
0N/A *
0N/A * You should have received a copy of the GNU General Public License version
0N/A * 2 along with this work; if not, write to the Free Software Foundation,
0N/A * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
0N/A *
2362N/A * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
2362N/A * or visit www.oracle.com if you need additional information or have any
2362N/A * questions.
0N/A */
0N/A
0N/Apackage java.util;
0N/A
0N/Aimport java.io.BufferedReader;
0N/Aimport java.io.IOException;
0N/Aimport java.io.InputStream;
0N/Aimport java.io.InputStreamReader;
0N/Aimport java.net.URL;
0N/Aimport java.util.ArrayList;
0N/Aimport java.util.Enumeration;
0N/Aimport java.util.Iterator;
0N/Aimport java.util.List;
0N/Aimport java.util.NoSuchElementException;
0N/A
0N/A
0N/A/**
0N/A * A simple service-provider loading facility.
0N/A *
0N/A * <p> A <i>service</i> is a well-known set of interfaces and (usually
0N/A * abstract) classes. A <i>service provider</i> is a specific implementation
0N/A * of a service. The classes in a provider typically implement the interfaces
0N/A * and subclass the classes defined in the service itself. Service providers
0N/A * can be installed in an implementation of the Java platform in the form of
0N/A * extensions, that is, jar files placed into any of the usual extension
0N/A * directories. Providers can also be made available by adding them to the
0N/A * application's class path or by some other platform-specific means.
0N/A *
0N/A * <p> For the purpose of loading, a service is represented by a single type,
0N/A * that is, a single interface or abstract class. (A concrete class can be
0N/A * used, but this is not recommended.) A provider of a given service contains
0N/A * one or more concrete classes that extend this <i>service type</i> with data
0N/A * and code specific to the provider. The <i>provider class</i> is typically
0N/A * not the entire provider itself but rather a proxy which contains enough
0N/A * information to decide whether the provider is able to satisfy a particular
0N/A * request together with code that can create the actual provider on demand.
0N/A * The details of provider classes tend to be highly service-specific; no
0N/A * single class or interface could possibly unify them, so no such type is
0N/A * defined here. The only requirement enforced by this facility is that
0N/A * provider classes must have a zero-argument constructor so that they can be
0N/A * instantiated during loading.
0N/A *
0N/A * <p><a name="format"> A service provider is identified by placing a
0N/A * <i>provider-configuration file</i> in the resource directory
0N/A * <tt>META-INF/services</tt>. The file's name is the fully-qualified <a
0N/A * href="../lang/ClassLoader.html#name">binary name</a> of the service's type.
0N/A * The file contains a list of fully-qualified binary names of concrete
0N/A * provider classes, one per line. Space and tab characters surrounding each
0N/A * name, as well as blank lines, are ignored. The comment character is
0N/A * <tt>'#'</tt> (<tt>'&#92;u0023'</tt>, <font size="-1">NUMBER SIGN</font>); on
0N/A * each line all characters following the first comment character are ignored.
0N/A * The file must be encoded in UTF-8.
0N/A *
0N/A * <p> If a particular concrete provider class is named in more than one
0N/A * configuration file, or is named in the same configuration file more than
0N/A * once, then the duplicates are ignored. The configuration file naming a
0N/A * particular provider need not be in the same jar file or other distribution
0N/A * unit as the provider itself. The provider must be accessible from the same
0N/A * class loader that was initially queried to locate the configuration file;
0N/A * note that this is not necessarily the class loader from which the file was
0N/A * actually loaded.
0N/A *
0N/A * <p> Providers are located and instantiated lazily, that is, on demand. A
0N/A * service loader maintains a cache of the providers that have been loaded so
0N/A * far. Each invocation of the {@link #iterator iterator} method returns an
0N/A * iterator that first yields all of the elements of the cache, in
0N/A * instantiation order, and then lazily locates and instantiates any remaining
0N/A * providers, adding each one to the cache in turn. The cache can be cleared
0N/A * via the {@link #reload reload} method.
0N/A *
0N/A * <p> Service loaders always execute in the security context of the caller.
0N/A * Trusted system code should typically invoke the methods in this class, and
0N/A * the methods of the iterators which they return, from within a privileged
0N/A * security context.
0N/A *
0N/A * <p> Instances of this class are not safe for use by multiple concurrent
0N/A * threads.
0N/A *
0N/A * <p> Unless otherwise specified, passing a <tt>null</tt> argument to any
0N/A * method in this class will cause a {@link NullPointerException} to be thrown.
0N/A *
0N/A *
0N/A * <p><span style="font-weight: bold; padding-right: 1em">Example</span>
0N/A * Suppose we have a service type <tt>com.example.CodecSet</tt> which is
0N/A * intended to represent sets of encoder/decoder pairs for some protocol. In
0N/A * this case it is an abstract class with two abstract methods:
0N/A *
0N/A * <blockquote><pre>
0N/A * public abstract Encoder getEncoder(String encodingName);
0N/A * public abstract Decoder getDecoder(String encodingName);</pre></blockquote>
0N/A *
0N/A * Each method returns an appropriate object or <tt>null</tt> if the provider
0N/A * does not support the given encoding. Typical providers support more than
0N/A * one encoding.
0N/A *
0N/A * <p> If <tt>com.example.impl.StandardCodecs</tt> is an implementation of the
0N/A * <tt>CodecSet</tt> service then its jar file also contains a file named
0N/A *
0N/A * <blockquote><pre>
0N/A * META-INF/services/com.example.CodecSet</pre></blockquote>
0N/A *
0N/A * <p> This file contains the single line:
0N/A *
0N/A * <blockquote><pre>
0N/A * com.example.impl.StandardCodecs # Standard codecs</pre></blockquote>
0N/A *
0N/A * <p> The <tt>CodecSet</tt> class creates and saves a single service instance
0N/A * at initialization:
0N/A *
0N/A * <blockquote><pre>
0N/A * private static ServiceLoader&lt;CodecSet&gt; codecSetLoader
0N/A * = ServiceLoader.load(CodecSet.class);</pre></blockquote>
0N/A *
0N/A * <p> To locate an encoder for a given encoding name it defines a static
0N/A * factory method which iterates through the known and available providers,
0N/A * returning only when it has located a suitable encoder or has run out of
0N/A * providers.
0N/A *
0N/A * <blockquote><pre>
0N/A * public static Encoder getEncoder(String encodingName) {
0N/A * for (CodecSet cp : codecSetLoader) {
0N/A * Encoder enc = cp.getEncoder(encodingName);
0N/A * if (enc != null)
0N/A * return enc;
0N/A * }
0N/A * return null;
0N/A * }</pre></blockquote>
0N/A *
0N/A * <p> A <tt>getDecoder</tt> method is defined similarly.
0N/A *
0N/A *
0N/A * <p><span style="font-weight: bold; padding-right: 1em">Usage Note</span> If
0N/A * the class path of a class loader that is used for provider loading includes
0N/A * remote network URLs then those URLs will be dereferenced in the process of
0N/A * searching for provider-configuration files.
0N/A *
0N/A * <p> This activity is normal, although it may cause puzzling entries to be
0N/A * created in web-server logs. If a web server is not configured correctly,
0N/A * however, then this activity may cause the provider-loading algorithm to fail
0N/A * spuriously.
0N/A *
0N/A * <p> A web server should return an HTTP 404 (Not Found) response when a
0N/A * requested resource does not exist. Sometimes, however, web servers are
0N/A * erroneously configured to return an HTTP 200 (OK) response along with a
0N/A * helpful HTML error page in such cases. This will cause a {@link
0N/A * ServiceConfigurationError} to be thrown when this class attempts to parse
0N/A * the HTML page as a provider-configuration file. The best solution to this
0N/A * problem is to fix the misconfigured web server to return the correct
0N/A * response code (HTTP 404) along with the HTML error page.
0N/A *
0N/A * @param <S>
0N/A * The type of the service to be loaded by this loader
0N/A *
0N/A * @author Mark Reinhold
0N/A * @since 1.6
0N/A */
0N/A
0N/Apublic final class ServiceLoader<S>
0N/A implements Iterable<S>
0N/A{
0N/A
0N/A private static final String PREFIX = "META-INF/services/";
0N/A
0N/A // The class or interface representing the service being loaded
0N/A private Class<S> service;
0N/A
0N/A // The class loader used to locate, load, and instantiate providers
0N/A private ClassLoader loader;
0N/A
0N/A // Cached providers, in instantiation order
3323N/A private LinkedHashMap<String,S> providers = new LinkedHashMap<>();
0N/A
0N/A // The current lazy-lookup iterator
0N/A private LazyIterator lookupIterator;
0N/A
0N/A /**
0N/A * Clear this loader's provider cache so that all providers will be
0N/A * reloaded.
0N/A *
0N/A * <p> After invoking this method, subsequent invocations of the {@link
0N/A * #iterator() iterator} method will lazily look up and instantiate
0N/A * providers from scratch, just as is done by a newly-created loader.
0N/A *
0N/A * <p> This method is intended for use in situations in which new providers
0N/A * can be installed into a running Java virtual machine.
0N/A */
0N/A public void reload() {
0N/A providers.clear();
0N/A lookupIterator = new LazyIterator(service, loader);
0N/A }
0N/A
0N/A private ServiceLoader(Class<S> svc, ClassLoader cl) {
0N/A service = svc;
0N/A loader = cl;
0N/A reload();
0N/A }
0N/A
0N/A private static void fail(Class service, String msg, Throwable cause)
0N/A throws ServiceConfigurationError
0N/A {
0N/A throw new ServiceConfigurationError(service.getName() + ": " + msg,
0N/A cause);
0N/A }
0N/A
0N/A private static void fail(Class service, String msg)
0N/A throws ServiceConfigurationError
0N/A {
0N/A throw new ServiceConfigurationError(service.getName() + ": " + msg);
0N/A }
0N/A
0N/A private static void fail(Class service, URL u, int line, String msg)
0N/A throws ServiceConfigurationError
0N/A {
0N/A fail(service, u + ":" + line + ": " + msg);
0N/A }
0N/A
0N/A // Parse a single line from the given configuration file, adding the name
0N/A // on the line to the names list.
0N/A //
0N/A private int parseLine(Class service, URL u, BufferedReader r, int lc,
0N/A List<String> names)
0N/A throws IOException, ServiceConfigurationError
0N/A {
0N/A String ln = r.readLine();
0N/A if (ln == null) {
0N/A return -1;
0N/A }
0N/A int ci = ln.indexOf('#');
0N/A if (ci >= 0) ln = ln.substring(0, ci);
0N/A ln = ln.trim();
0N/A int n = ln.length();
0N/A if (n != 0) {
0N/A if ((ln.indexOf(' ') >= 0) || (ln.indexOf('\t') >= 0))
0N/A fail(service, u, lc, "Illegal configuration-file syntax");
0N/A int cp = ln.codePointAt(0);
0N/A if (!Character.isJavaIdentifierStart(cp))
0N/A fail(service, u, lc, "Illegal provider-class name: " + ln);
0N/A for (int i = Character.charCount(cp); i < n; i += Character.charCount(cp)) {
0N/A cp = ln.codePointAt(i);
0N/A if (!Character.isJavaIdentifierPart(cp) && (cp != '.'))
0N/A fail(service, u, lc, "Illegal provider-class name: " + ln);
0N/A }
0N/A if (!providers.containsKey(ln) && !names.contains(ln))
0N/A names.add(ln);
0N/A }
0N/A return lc + 1;
0N/A }
0N/A
0N/A // Parse the content of the given URL as a provider-configuration file.
0N/A //
0N/A // @param service
0N/A // The service type for which providers are being sought;
0N/A // used to construct error detail strings
0N/A //
0N/A // @param u
0N/A // The URL naming the configuration file to be parsed
0N/A //
0N/A // @return A (possibly empty) iterator that will yield the provider-class
0N/A // names in the given configuration file that are not yet members
0N/A // of the returned set
0N/A //
0N/A // @throws ServiceConfigurationError
0N/A // If an I/O error occurs while reading from the given URL, or
0N/A // if a configuration-file format error is detected
0N/A //
0N/A private Iterator<String> parse(Class service, URL u)
0N/A throws ServiceConfigurationError
0N/A {
0N/A InputStream in = null;
0N/A BufferedReader r = null;
3323N/A ArrayList<String> names = new ArrayList<>();
0N/A try {
0N/A in = u.openStream();
0N/A r = new BufferedReader(new InputStreamReader(in, "utf-8"));
0N/A int lc = 1;
0N/A while ((lc = parseLine(service, u, r, lc, names)) >= 0);
0N/A } catch (IOException x) {
0N/A fail(service, "Error reading configuration file", x);
0N/A } finally {
0N/A try {
0N/A if (r != null) r.close();
0N/A if (in != null) in.close();
0N/A } catch (IOException y) {
0N/A fail(service, "Error closing configuration file", y);
0N/A }
0N/A }
0N/A return names.iterator();
0N/A }
0N/A
0N/A // Private inner class implementing fully-lazy provider lookup
0N/A //
0N/A private class LazyIterator
0N/A implements Iterator<S>
0N/A {
0N/A
0N/A Class<S> service;
0N/A ClassLoader loader;
0N/A Enumeration<URL> configs = null;
0N/A Iterator<String> pending = null;
0N/A String nextName = null;
0N/A
0N/A private LazyIterator(Class<S> service, ClassLoader loader) {
0N/A this.service = service;
0N/A this.loader = loader;
0N/A }
0N/A
0N/A public boolean hasNext() {
0N/A if (nextName != null) {
0N/A return true;
0N/A }
0N/A if (configs == null) {
0N/A try {
0N/A String fullName = PREFIX + service.getName();
0N/A if (loader == null)
0N/A configs = ClassLoader.getSystemResources(fullName);
0N/A else
0N/A configs = loader.getResources(fullName);
0N/A } catch (IOException x) {
0N/A fail(service, "Error locating configuration files", x);
0N/A }
0N/A }
0N/A while ((pending == null) || !pending.hasNext()) {
0N/A if (!configs.hasMoreElements()) {
0N/A return false;
0N/A }
0N/A pending = parse(service, configs.nextElement());
0N/A }
0N/A nextName = pending.next();
0N/A return true;
0N/A }
0N/A
0N/A public S next() {
0N/A if (!hasNext()) {
0N/A throw new NoSuchElementException();
0N/A }
0N/A String cn = nextName;
0N/A nextName = null;
5419N/A Class<?> c = null;
0N/A try {
5419N/A c = Class.forName(cn, false, loader);
0N/A } catch (ClassNotFoundException x) {
0N/A fail(service,
0N/A "Provider " + cn + " not found");
5419N/A }
5419N/A if (!service.isAssignableFrom(c)) {
5419N/A fail(service,
5419N/A "Provider " + cn + " not a subtype");
5419N/A }
5419N/A try {
5419N/A S p = service.cast(c.newInstance());
5419N/A providers.put(cn, p);
5419N/A return p;
0N/A } catch (Throwable x) {
0N/A fail(service,
0N/A "Provider " + cn + " could not be instantiated: " + x,
0N/A x);
0N/A }
0N/A throw new Error(); // This cannot happen
0N/A }
0N/A
0N/A public void remove() {
0N/A throw new UnsupportedOperationException();
0N/A }
0N/A
0N/A }
0N/A
0N/A /**
0N/A * Lazily loads the available providers of this loader's service.
0N/A *
0N/A * <p> The iterator returned by this method first yields all of the
0N/A * elements of the provider cache, in instantiation order. It then lazily
0N/A * loads and instantiates any remaining providers, adding each one to the
0N/A * cache in turn.
0N/A *
0N/A * <p> To achieve laziness the actual work of parsing the available
0N/A * provider-configuration files and instantiating providers must be done by
0N/A * the iterator itself. Its {@link java.util.Iterator#hasNext hasNext} and
0N/A * {@link java.util.Iterator#next next} methods can therefore throw a
0N/A * {@link ServiceConfigurationError} if a provider-configuration file
0N/A * violates the specified format, or if it names a provider class that
0N/A * cannot be found and instantiated, or if the result of instantiating the
0N/A * class is not assignable to the service type, or if any other kind of
0N/A * exception or error is thrown as the next provider is located and
0N/A * instantiated. To write robust code it is only necessary to catch {@link
0N/A * ServiceConfigurationError} when using a service iterator.
0N/A *
0N/A * <p> If such an error is thrown then subsequent invocations of the
0N/A * iterator will make a best effort to locate and instantiate the next
0N/A * available provider, but in general such recovery cannot be guaranteed.
0N/A *
0N/A * <blockquote style="font-size: smaller; line-height: 1.2"><span
0N/A * style="padding-right: 1em; font-weight: bold">Design Note</span>
0N/A * Throwing an error in these cases may seem extreme. The rationale for
0N/A * this behavior is that a malformed provider-configuration file, like a
0N/A * malformed class file, indicates a serious problem with the way the Java
0N/A * virtual machine is configured or is being used. As such it is
0N/A * preferable to throw an error rather than try to recover or, even worse,
0N/A * fail silently.</blockquote>
0N/A *
0N/A * <p> The iterator returned by this method does not support removal.
0N/A * Invoking its {@link java.util.Iterator#remove() remove} method will
0N/A * cause an {@link UnsupportedOperationException} to be thrown.
0N/A *
0N/A * @return An iterator that lazily loads providers for this loader's
0N/A * service
0N/A */
0N/A public Iterator<S> iterator() {
0N/A return new Iterator<S>() {
0N/A
0N/A Iterator<Map.Entry<String,S>> knownProviders
0N/A = providers.entrySet().iterator();
0N/A
0N/A public boolean hasNext() {
0N/A if (knownProviders.hasNext())
0N/A return true;
0N/A return lookupIterator.hasNext();
0N/A }
0N/A
0N/A public S next() {
0N/A if (knownProviders.hasNext())
0N/A return knownProviders.next().getValue();
0N/A return lookupIterator.next();
0N/A }
0N/A
0N/A public void remove() {
0N/A throw new UnsupportedOperationException();
0N/A }
0N/A
0N/A };
0N/A }
0N/A
0N/A /**
0N/A * Creates a new service loader for the given service type and class
0N/A * loader.
0N/A *
0N/A * @param service
0N/A * The interface or abstract class representing the service
0N/A *
0N/A * @param loader
0N/A * The class loader to be used to load provider-configuration files
0N/A * and provider classes, or <tt>null</tt> if the system class
0N/A * loader (or, failing that, the bootstrap class loader) is to be
0N/A * used
0N/A *
0N/A * @return A new service loader
0N/A */
0N/A public static <S> ServiceLoader<S> load(Class<S> service,
0N/A ClassLoader loader)
0N/A {
3323N/A return new ServiceLoader<>(service, loader);
0N/A }
0N/A
0N/A /**
0N/A * Creates a new service loader for the given service type, using the
0N/A * current thread's {@linkplain java.lang.Thread#getContextClassLoader
0N/A * context class loader}.
0N/A *
0N/A * <p> An invocation of this convenience method of the form
0N/A *
0N/A * <blockquote><pre>
0N/A * ServiceLoader.load(<i>service</i>)</pre></blockquote>
0N/A *
0N/A * is equivalent to
0N/A *
0N/A * <blockquote><pre>
0N/A * ServiceLoader.load(<i>service</i>,
0N/A * Thread.currentThread().getContextClassLoader())</pre></blockquote>
0N/A *
0N/A * @param service
0N/A * The interface or abstract class representing the service
0N/A *
0N/A * @return A new service loader
0N/A */
0N/A public static <S> ServiceLoader<S> load(Class<S> service) {
0N/A ClassLoader cl = Thread.currentThread().getContextClassLoader();
0N/A return ServiceLoader.load(service, cl);
0N/A }
0N/A
0N/A /**
0N/A * Creates a new service loader for the given service type, using the
0N/A * extension class loader.
0N/A *
0N/A * <p> This convenience method simply locates the extension class loader,
0N/A * call it <tt><i>extClassLoader</i></tt>, and then returns
0N/A *
0N/A * <blockquote><pre>
0N/A * ServiceLoader.load(<i>service</i>, <i>extClassLoader</i>)</pre></blockquote>
0N/A *
0N/A * <p> If the extension class loader cannot be found then the system class
0N/A * loader is used; if there is no system class loader then the bootstrap
0N/A * class loader is used.
0N/A *
0N/A * <p> This method is intended for use when only installed providers are
0N/A * desired. The resulting service will only find and load providers that
0N/A * have been installed into the current Java virtual machine; providers on
0N/A * the application's class path will be ignored.
0N/A *
0N/A * @param service
0N/A * The interface or abstract class representing the service
0N/A *
0N/A * @return A new service loader
0N/A */
0N/A public static <S> ServiceLoader<S> loadInstalled(Class<S> service) {
0N/A ClassLoader cl = ClassLoader.getSystemClassLoader();
0N/A ClassLoader prev = null;
0N/A while (cl != null) {
0N/A prev = cl;
0N/A cl = cl.getParent();
0N/A }
0N/A return ServiceLoader.load(service, prev);
0N/A }
0N/A
0N/A /**
0N/A * Returns a string describing this service.
0N/A *
0N/A * @return A descriptive string
0N/A */
0N/A public String toString() {
0N/A return "java.util.ServiceLoader[" + service.getName() + "]";
0N/A }
0N/A
0N/A}