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