KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > java > util > ServiceLoader


1 /*
2  * @(#)ServiceLoader.java 1.10 06/04/10
3  *
4  * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
5  * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
6  */

7
8 package java.util;
9
10 import java.io.BufferedReader JavaDoc;
11 import java.io.IOException JavaDoc;
12 import java.io.InputStream JavaDoc;
13 import java.io.InputStreamReader JavaDoc;
14 import java.net.URL JavaDoc;
15 import java.util.ArrayList JavaDoc;
16 import java.util.Enumeration JavaDoc;
17 import java.util.Iterator JavaDoc;
18 import java.util.List JavaDoc;
19 import java.util.NoSuchElementException JavaDoc;
20
21
22 /**
23  * A simple service-provider loading facility.
24  *
25  * <p> A <i>service</i> is a well-known set of interfaces and (usually
26  * abstract) classes. A <i>service provider</i> is a specific implementation
27  * of a service. The classes in a provider typically implement the interfaces
28  * and subclass the classes defined in the service itself. Service providers
29  * can be installed in an implementation of the Java platform in the form of
30  * extensions, that is, jar files placed into any of the usual extension
31  * directories. Providers can also be made available by adding them to the
32  * application's class path or by some other platform-specific means.
33  *
34  * <p> For the purpose of loading, a service is represented by a single type,
35  * that is, a single interface or abstract class. (A concrete class can be
36  * used, but this is not recommended.) A provider of a given service contains
37  * one or more concrete classes that extend this <i>service type</i> with data
38  * and code specific to the provider. The <i>provider class</i> is typically
39  * not the entire provider itself but rather a proxy which contains enough
40  * information to decide whether the provider is able to satisfy a particular
41  * request together with code that can create the actual provider on demand.
42  * The details of provider classes tend to be highly service-specific; no
43  * single class or interface could possibly unify them, so no such type is
44  * defined here. The only requirement enforced by this facility is that
45  * provider classes must have a zero-argument constructor so that they can be
46  * instantiated during loading.
47  *
48  * <p><a name="format"> A service provider is identified by placing a
49  * <i>provider-configuration file</i> in the resource directory
50  * <tt>META-INF/services</tt>. The file's name is the fully-qualified <a
51  * HREF="../lang/ClassLoader.html#name">binary name</a> of the service's type.
52  * The file contains a list of fully-qualified binary names of concrete
53  * provider classes, one per line. Space and tab characters surrounding each
54  * name, as well as blank lines, are ignored. The comment character is
55  * <tt>'#'</tt> (<tt>'&#92;u0023'</tt>, <font size="-1">NUMBER SIGN</font>); on
56  * each line all characters following the first comment character are ignored.
57  * The file must be encoded in UTF-8.
58  *
59  * <p> If a particular concrete provider class is named in more than one
60  * configuration file, or is named in the same configuration file more than
61  * once, then the duplicates are ignored. The configuration file naming a
62  * particular provider need not be in the same jar file or other distribution
63  * unit as the provider itself. The provider must be accessible from the same
64  * class loader that was initially queried to locate the configuration file;
65  * note that this is not necessarily the class loader from which the file was
66  * actually loaded.
67  *
68  * <p> Providers are located and instantiated lazily, that is, on demand. A
69  * service loader maintains a cache of the providers that have been loaded so
70  * far. Each invocation of the {@link #iterator iterator} method returns an
71  * iterator that first yields all of the elements of the cache, in
72  * instantiation order, and then lazily locates and instantiates any remaining
73  * providers, adding each one to the cache in turn. The cache can be cleared
74  * via the {@link #reload reload} method.
75  *
76  * <p> Service loaders always execute in the security context of the caller.
77  * Trusted system code should typically invoke the methods in this class, and
78  * the methods of the iterators which they return, from within a privileged
79  * security context.
80  *
81  * <p> Instances of this class are not safe for use by multiple concurrent
82  * threads.
83  *
84  * <p> Unless otherwise specified, passing a <tt>null</tt> argument to any
85  * method in this class will cause a {@link NullPointerException} to be thrown.
86  *
87  *
88  * <p><span style="font-weight: bold; padding-right: 1em">Example</span>
89  * Suppose we have a service type <tt>com.example.CodecSet</tt> which is
90  * intended to represent sets of encoder/decoder pairs for some protocol. In
91  * this case it is an abstract class with two abstract methods:
92  *
93  * <blockquote><pre>
94  * public abstract Encoder getEncoder(String encodingName);
95  * public abstract Decoder getDecoder(String encodingName);</pre></blockquote>
96  *
97  * Each method returns an appropriate object or <tt>null</tt> if the provider
98  * does not support the given encoding. Typical providers support more than
99  * one encoding.
100  *
101  * <p> If <tt>com.example.impl.StandardCodecs</tt> is an implementation of the
102  * <tt>CodecSet</tt> service then its jar file also contains a file named
103  *
104  * <blockquote><pre>
105  * META-INF/services/com.example.CodecSet</pre></blockquote>
106  *
107  * <p> This file contains the single line:
108  *
109  * <blockquote><pre>
110  * com.example.impl.StandardCodecs # Standard codecs</pre></blockquote>
111  *
112  * <p> The <tt>CodecSet</tt> class creates and saves a single service instance
113  * at initialization:
114  *
115  * <blockquote><pre>
116  * private static ServiceLoader&lt;CodecSet&gt; codecSetLoader
117  * = ServiceLoader.load(CodecSet.class);</pre></blockquote>
118  *
119  * <p> To locate an encoder for a given encoding name it defines a static
120  * factory method which iterates through the known and available providers,
121  * returning only when it has located a suitable encoder or has run out of
122  * providers.
123  *
124  * <blockquote><pre>
125  * public static Encoder getEncoder(String encodingName) {
126  * for (CodecSet cp : codecSetLoader) {
127  * Encoder enc = cp.getEncoder(encodingName);
128  * if (enc != null)
129  * return enc;
130  * }
131  * return null;
132  * }</pre></blockquote>
133  *
134  * <p> A <tt>getDecoder</tt> method is defined similarly.
135  *
136  *
137  * <p><span style="font-weight: bold; padding-right: 1em">Usage Note</span> If
138  * the class path of a class loader that is used for provider loading includes
139  * remote network URLs then those URLs will be dereferenced in the process of
140  * searching for provider-configuration files.
141  *
142  * <p> This activity is normal, although it may cause puzzling entries to be
143  * created in web-server logs. If a web server is not configured correctly,
144  * however, then this activity may cause the provider-loading algorithm to fail
145  * spuriously.
146  *
147  * <p> A web server should return an HTTP 404 (Not Found) response when a
148  * requested resource does not exist. Sometimes, however, web servers are
149  * erroneously configured to return an HTTP 200 (OK) response along with a
150  * helpful HTML error page in such cases. This will cause a {@link
151  * ServiceConfigurationError} to be thrown when this class attempts to parse
152  * the HTML page as a provider-configuration file. The best solution to this
153  * problem is to fix the misconfigured web server to return the correct
154  * response code (HTTP 404) along with the HTML error page.
155  *
156  * @param <S>
157  * The type of the service to be loaded by this loader
158  *
159  * @author Mark Reinhold
160  * @version 1.10, 06/04/10
161  * @since 1.6
162  */

163
164 public final class ServiceLoader<S>
165     implements Iterable JavaDoc<S>
166 {
167
168     private static final String JavaDoc PREFIX = "META-INF/services/";
169
170     // The class or interface representing the service being loaded
171
private Class JavaDoc<S> service;
172
173     // The class loader used to locate, load, and instantiate providers
174
private ClassLoader JavaDoc loader;
175
176     // Cached providers, in instantiation order
177
private LinkedHashMap JavaDoc<String JavaDoc,S> providers = new LinkedHashMap JavaDoc<String JavaDoc,S>();
178
179     // The current lazy-lookup iterator
180
private LazyIterator lookupIterator;
181
182     /**
183      * Clear this loader's provider cache so that all providers will be
184      * reloaded.
185      *
186      * <p> After invoking this method, subsequent invocations of the {@link
187      * #iterator() iterator} method will lazily look up and instantiate
188      * providers from scratch, just as is done by a newly-created loader.
189      *
190      * <p> This method is intended for use in situations in which new providers
191      * can be installed into a running Java virtual machine.
192      */

193     public void reload() {
194     providers.clear();
195     lookupIterator = new LazyIterator(service, loader);
196     }
197
198     private ServiceLoader(Class JavaDoc<S> svc, ClassLoader JavaDoc cl) {
199     service = svc;
200     loader = cl;
201     reload();
202     }
203
204     private static void fail(Class JavaDoc service, String JavaDoc msg, Throwable JavaDoc cause)
205     throws ServiceConfigurationError JavaDoc
206     {
207     throw new ServiceConfigurationError JavaDoc(service.getName() + ": " + msg,
208                         cause);
209     }
210
211     private static void fail(Class JavaDoc service, String JavaDoc msg)
212     throws ServiceConfigurationError JavaDoc
213     {
214     throw new ServiceConfigurationError JavaDoc(service.getName() + ": " + msg);
215     }
216
217     private static void fail(Class JavaDoc service, URL JavaDoc u, int line, String JavaDoc msg)
218     throws ServiceConfigurationError JavaDoc
219     {
220     fail(service, u + ":" + line + ": " + msg);
221     }
222
223     // Parse a single line from the given configuration file, adding the name
224
// on the line to the names list.
225
//
226
private int parseLine(Class JavaDoc service, URL JavaDoc u, BufferedReader JavaDoc r, int lc,
227               List JavaDoc<String JavaDoc> names)
228     throws IOException JavaDoc, ServiceConfigurationError JavaDoc
229     {
230     String JavaDoc ln = r.readLine();
231     if (ln == null) {
232         return -1;
233     }
234     int ci = ln.indexOf('#');
235     if (ci >= 0) ln = ln.substring(0, ci);
236     ln = ln.trim();
237     int n = ln.length();
238     if (n != 0) {
239         if ((ln.indexOf(' ') >= 0) || (ln.indexOf('\t') >= 0))
240         fail(service, u, lc, "Illegal configuration-file syntax");
241         int cp = ln.codePointAt(0);
242         if (!Character.isJavaIdentifierStart(cp))
243         fail(service, u, lc, "Illegal provider-class name: " + ln);
244         for (int i = Character.charCount(cp); i < n; i += Character.charCount(cp)) {
245         cp = ln.codePointAt(i);
246         if (!Character.isJavaIdentifierPart(cp) && (cp != '.'))
247             fail(service, u, lc, "Illegal provider-class name: " + ln);
248         }
249         if (!providers.containsKey(ln) && !names.contains(ln))
250         names.add(ln);
251     }
252     return lc + 1;
253     }
254
255     // Parse the content of the given URL as a provider-configuration file.
256
//
257
// @param service
258
// The service type for which providers are being sought;
259
// used to construct error detail strings
260
//
261
// @param u
262
// The URL naming the configuration file to be parsed
263
//
264
// @return A (possibly empty) iterator that will yield the provider-class
265
// names in the given configuration file that are not yet members
266
// of the returned set
267
//
268
// @throws ServiceConfigurationError
269
// If an I/O error occurs while reading from the given URL, or
270
// if a configuration-file format error is detected
271
//
272
private Iterator JavaDoc<String JavaDoc> parse(Class JavaDoc service, URL JavaDoc u)
273     throws ServiceConfigurationError JavaDoc
274     {
275     InputStream JavaDoc in = null;
276     BufferedReader JavaDoc r = null;
277     ArrayList JavaDoc<String JavaDoc> names = new ArrayList JavaDoc<String JavaDoc>();
278     try {
279         in = u.openStream();
280         r = new BufferedReader JavaDoc(new InputStreamReader JavaDoc(in, "utf-8"));
281         int lc = 1;
282         while ((lc = parseLine(service, u, r, lc, names)) >= 0);
283     } catch (IOException JavaDoc x) {
284         fail(service, "Error reading configuration file", x);
285     } finally {
286         try {
287         if (r != null) r.close();
288         if (in != null) in.close();
289         } catch (IOException JavaDoc y) {
290         fail(service, "Error closing configuration file", y);
291         }
292     }
293     return names.iterator();
294     }
295
296     // Private inner class implementing fully-lazy provider lookup
297
//
298
private class LazyIterator
299     implements Iterator JavaDoc<S>
300     {
301
302     Class JavaDoc<S> service;
303     ClassLoader JavaDoc loader;
304     Enumeration JavaDoc<URL JavaDoc> configs = null;
305     Iterator JavaDoc<String JavaDoc> pending = null;
306     String JavaDoc nextName = null;
307
308     private LazyIterator(Class JavaDoc<S> service, ClassLoader JavaDoc loader) {
309         this.service = service;
310         this.loader = loader;
311     }
312
313     public boolean hasNext() {
314         if (nextName != null) {
315         return true;
316         }
317         if (configs == null) {
318         try {
319             String JavaDoc fullName = PREFIX + service.getName();
320             if (loader == null)
321             configs = ClassLoader.getSystemResources(fullName);
322             else
323             configs = loader.getResources(fullName);
324         } catch (IOException JavaDoc x) {
325             fail(service, "Error locating configuration files", x);
326         }
327         }
328         while ((pending == null) || !pending.hasNext()) {
329         if (!configs.hasMoreElements()) {
330             return false;
331         }
332         pending = parse(service, configs.nextElement());
333         }
334         nextName = pending.next();
335         return true;
336     }
337
338     public S next() {
339         if (!hasNext()) {
340         throw new NoSuchElementException JavaDoc();
341         }
342         String JavaDoc cn = nextName;
343         nextName = null;
344         try {
345         S p = service.cast(Class.forName(cn, true, loader)
346                    .newInstance());
347         providers.put(cn, p);
348         return p;
349         } catch (ClassNotFoundException JavaDoc x) {
350         fail(service,
351              "Provider " + cn + " not found");
352         } catch (Throwable JavaDoc x) {
353         fail(service,
354              "Provider " + cn + " could not be instantiated: " + x,
355              x);
356         }
357         throw new Error JavaDoc(); // This cannot happen
358
}
359
360     public void remove() {
361         throw new UnsupportedOperationException JavaDoc();
362     }
363
364     }
365
366     /**
367      * Lazily loads the available providers of this loader's service.
368      *
369      * <p> The iterator returned by this method first yields all of the
370      * elements of the provider cache, in instantiation order. It then lazily
371      * loads and instantiates any remaining providers, adding each one to the
372      * cache in turn.
373      *
374      * <p> To achieve laziness the actual work of parsing the available
375      * provider-configuration files and instantiating providers must be done by
376      * the iterator itself. Its {@link java.util.Iterator#hasNext hasNext} and
377      * {@link java.util.Iterator#next next} methods can therefore throw a
378      * {@link ServiceConfigurationError} if a provider-configuration file
379      * violates the specified format, or if it names a provider class that
380      * cannot be found and instantiated, or if the result of instantiating the
381      * class is not assignable to the service type, or if any other kind of
382      * exception or error is thrown as the next provider is located and
383      * instantiated. To write robust code it is only necessary to catch {@link
384      * ServiceConfigurationError} when using a service iterator.
385      *
386      * <p> If such an error is thrown then subsequent invocations of the
387      * iterator will make a best effort to locate and instantiate the next
388      * available provider, but in general such recovery cannot be guaranteed.
389      *
390      * <blockquote style="font-size: smaller; line-height: 1.2"><span
391      * style="padding-right: 1em; font-weight: bold">Design Note</span>
392      * Throwing an error in these cases may seem extreme. The rationale for
393      * this behavior is that a malformed provider-configuration file, like a
394      * malformed class file, indicates a serious problem with the way the Java
395      * virtual machine is configured or is being used. As such it is
396      * preferable to throw an error rather than try to recover or, even worse,
397      * fail silently.</blockquote>
398      *
399      * <p> The iterator returned by this method does not support removal.
400      * Invoking its {@link java.util.Iterator#remove() remove} method will
401      * cause an {@link UnsupportedOperationException} to be thrown.
402      *
403      * @return An iterator that lazily loads providers for this loader's
404      * service
405      */

406     public Iterator JavaDoc<S> iterator() {
407     return new Iterator JavaDoc<S>() {
408
409         Iterator JavaDoc<Map.Entry JavaDoc<String JavaDoc,S>> knownProviders
410         = providers.entrySet().iterator();
411
412         public boolean hasNext() {
413         if (knownProviders.hasNext())
414             return true;
415         return lookupIterator.hasNext();
416         }
417
418         public S next() {
419         if (knownProviders.hasNext())
420             return knownProviders.next().getValue();
421         return lookupIterator.next();
422         }
423
424         public void remove() {
425         throw new UnsupportedOperationException JavaDoc();
426         }
427
428     };
429     }
430
431     /**
432      * Creates a new service loader for the given service type and class
433      * loader.
434      *
435      * @param service
436      * The interface or abstract class representing the service
437      *
438      * @param loader
439      * The class loader to be used to load provider-configuration files
440      * and provider classes, or <tt>null</tt> if the system class
441      * loader (or, failing that, the bootstrap class loader) is to be
442      * used
443      *
444      * @return A new service loader
445      */

446     public static <S> ServiceLoader JavaDoc<S> load(Class JavaDoc<S> service,
447                         ClassLoader JavaDoc loader)
448     {
449     return new ServiceLoader JavaDoc<S>(service, loader);
450     }
451
452     /**
453      * Creates a new service loader for the given service type, using the
454      * current thread's {@linkplain java.lang.Thread#getContextClassLoader
455      * context class loader}.
456      *
457      * <p> An invocation of this convenience method of the form
458      *
459      * <blockquote><pre>
460      * ServiceLoader.load(<i>service</i>)</pre></blockquote>
461      *
462      * is equivalent to
463      *
464      * <blockquote><pre>
465      * ServiceLoader.load(<i>service</i>,
466      * Thread.currentThread().getContextClassLoader())</pre></blockquote>
467      *
468      * @param service
469      * The interface or abstract class representing the service
470      *
471      * @return A new service loader
472      */

473     public static <S> ServiceLoader JavaDoc<S> load(Class JavaDoc<S> service) {
474     ClassLoader JavaDoc cl = Thread.currentThread().getContextClassLoader();
475     return ServiceLoader.load(service, cl);
476     }
477
478     /**
479      * Creates a new service loader for the given service type, using the
480      * extension class loader.
481      *
482      * <p> This convenience method simply locates the extension class loader,
483      * call it <tt><i>extClassLoader</i></tt>, and then returns
484      *
485      * <blockquote><pre>
486      * ServiceLoader.load(<i>service</i>, <i>extClassLoader</i>)</pre></blockquote>
487      *
488      * <p> If the extension class loader cannot be found then the system class
489      * loader is used; if there is no system class loader then the bootstrap
490      * class loader is used.
491      *
492      * <p> This method is intended for use when only installed providers are
493      * desired. The resulting service will only find and load providers that
494      * have been installed into the current Java virtual machine; providers on
495      * the application's class path will be ignored.
496      *
497      * @param service
498      * The interface or abstract class representing the service
499      *
500      * @return A new service loader
501      */

502     public static <S> ServiceLoader JavaDoc<S> loadInstalled(Class JavaDoc<S> service) {
503     ClassLoader JavaDoc cl = ClassLoader.getSystemClassLoader();
504     ClassLoader JavaDoc prev = null;
505     while (cl != null) {
506         prev = cl;
507         cl = cl.getParent();
508     }
509     return ServiceLoader.load(service, prev);
510     }
511
512     /**
513      * Returns a string describing this service.
514      *
515      * @return A descriptive string
516      */

517     public String JavaDoc toString() {
518     return "java.util.ServiceLoader[" + service.getName() + "]";
519     }
520
521 }
522
Popular Tags