001: /*
002: * $RCSfile: Service.java,v $
003: *
004: * Copyright (c) 2005 Sun Microsystems, Inc. All rights reserved.
005: *
006: * Use is subject to license terms.
007: *
008: * $Revision: 1.1 $
009: * $Date: 2005/02/11 04:57:02 $
010: * $State: Exp $
011: */
012: // This code is copied from the javax.media.imageio.spi
013: //
014: // Original SCCS ID: @(#)Service.java 1.4 00/05/23
015: package com.sun.media.jai.util;
016:
017: import java.io.BufferedReader;
018: import java.io.IOException;
019: import java.io.InputStream;
020: import java.io.InputStreamReader;
021: import java.net.URL;
022: import java.util.ArrayList;
023: import java.util.Enumeration;
024: import java.util.Iterator;
025: import java.util.List;
026: import java.util.NoSuchElementException;
027: import java.util.Set;
028: import java.util.TreeSet;
029:
030: /**
031: * A simple service-provider lookup mechanism. A <i>service</i> is a
032: * well-known set of interfaces and (usually abstract) classes. A <i>service
033: * provider</i> is a specific implementation of a service. The classes in a
034: * provider typically implement the interfaces and subclass the classes defined
035: * in the service itself. Service providers may be installed in an
036: * implementation of the Java platform in the form of extensions, that is, jar
037: * files placed into any of the usual extension directories. Providers may
038: * also be made available by adding them to the applet or application class
039: * path or by some other platform-specific means.
040: *
041: * <p> In this lookup mechanism a service is represented by an interface or an
042: * abstract class. (A concrete class may be used, but this is not
043: * recommended.) A provider of a given service contains one or more concrete
044: * classes that extend this <i>service class</i> with data and code specific to
045: * the provider. This <i>provider class</i> will typically not be the entire
046: * provider itself but rather a proxy that contains enough information to
047: * decide whether the provider is able to satisfy a particular request together
048: * with code that can create the actual provider on demand. The details of
049: * provider classes tend to be highly service-specific; no single class or
050: * interface could possibly unify them, so no such class has been defined. The
051: * only requirement enforced here is that provider classes must have a
052: * zero-argument constructor so that they may be instantiated during lookup.
053: *
054: * <p> A service provider identifies itself by placing a provider-configuration
055: * file in the resource directory <tt>META-INF/services</tt>. The file's name
056: * should consist of the fully-qualified name of the abstract service class.
057: * The file should contain a list of fully-qualified concrete provider-class
058: * names, one per line. Space and tab characters surrounding each name, as
059: * well as blank lines, are ignored. The comment character is <tt>'#'</tt>
060: * (<tt>0x23</tt>); on each line all characters following the first comment
061: * character are ignored. The file must be encoded in UTF-8.
062: *
063: * <p> If a particular concrete provider class is named in more than one
064: * configuration file, or is named in the same configuration file more than
065: * once, then the duplicates will be ignored. The configuration file naming a
066: * particular provider need not be in the same jar file or other distribution
067: * unit as the provider itself. The provider must be accessible from the same
068: * class loader that was initially queried to locate the configuration file;
069: * note that this is not necessarily the class loader that found the file.
070: *
071: * <p> <b>Example:</b> Suppose we have a service class named
072: * <tt>java.io.spi.CharCodec</tt>. It has two abstract methods:
073: *
074: * <pre>
075: * public abstract CharEncoder getEncoder(String encodingName);
076: * public abstract CharDecoder getDecoder(String encodingName);
077: * </pre>
078: *
079: * Each method returns an appropriate object or <tt>null</tt> if it cannot
080: * translate the given encoding. Typical <tt>CharCodec</tt> providers will
081: * support more than one encoding.
082: *
083: * <p> If <tt>sun.io.StandardCodec</tt> is a provider of the <tt>CharCodec</tt>
084: * service then its jar file would contain the file
085: * <tt>META-INF/services/java.io.spi.CharCodec</tt>. This file would contain
086: * the single line:
087: *
088: * <pre>
089: * sun.io.StandardCodec # Standard codecs for the platform
090: * </pre>
091: *
092: * To locate an encoder for a given encoding name, the internal I/O code would
093: * do something like this:
094: *
095: * <pre>
096: * CharEncoder getEncoder(String encodingName) {
097: * Iterator ps = Service.providers(CharCodec.class);
098: * while (ps.hasNext()) {
099: * CharCodec cc = (CharCodec)ps.next();
100: * CharEncoder ce = cc.getEncoder(encodingName);
101: * if (ce != null)
102: * return ce;
103: * }
104: * return null;
105: * }
106: * </pre>
107: *
108: * The provider-lookup mechanism always executes in the security context of the
109: * caller. Trusted system code should typically invoke the methods in this
110: * class from within a privileged security context.
111: *
112: * @since 1.3
113: */
114:
115: public final class Service {
116:
117: private static final String prefix = "META-INF/services/";
118:
119: private Service() {
120: }
121:
122: private static void fail(Class service, String msg)
123: throws ServiceConfigurationError {
124: throw new ServiceConfigurationError(service.getName() + ": "
125: + msg);
126: }
127:
128: private static void fail(Class service, URL u, int line, String msg)
129: throws ServiceConfigurationError {
130: fail(service, u + ":" + line + ": " + msg);
131: }
132:
133: /**
134: * Parse a single line from the given configuration file, adding the name
135: * on the line to both the names list and the returned set iff the name is
136: * not already a member of the returned set.
137: */
138: private static int parseLine(Class service, URL u,
139: BufferedReader r, int lc, List names, Set returned)
140: throws IOException, ServiceConfigurationError {
141: String ln = r.readLine();
142: if (ln == null) {
143: return -1;
144: }
145: int ci = ln.indexOf('#');
146: if (ci >= 0)
147: ln = ln.substring(0, ci);
148: ln = ln.trim();
149: int n = ln.length();
150: if (n != 0) {
151: if ((ln.indexOf(' ') >= 0) || (ln.indexOf('\t') >= 0))
152: fail(service, u, lc,
153: "Illegal configuration-file syntax");
154: if (!Character.isJavaIdentifierStart(ln.charAt(0)))
155: fail(service, u, lc, "Illegal provider-class name: "
156: + ln);
157: for (int i = 1; i < n; i++) {
158: char c = ln.charAt(i);
159: if (!Character.isJavaIdentifierPart(c) && (c != '.'))
160: fail(service, u, lc,
161: "Illegal provider-class name: " + ln);
162: }
163: if (!returned.contains(ln)) {
164: names.add(ln);
165: returned.add(ln);
166: }
167: }
168: return lc + 1;
169: }
170:
171: /**
172: * Parse the content of the given URL as a provider-configuration file.
173: *
174: * @param service
175: * The service class for which providers are being sought;
176: * used to construct error detail strings
177: *
178: * @param url
179: * The URL naming the configuration file to be parsed
180: *
181: * @param returned
182: * A Set containing the names of provider classes that have already
183: * been returned. This set will be updated to contain the names
184: * that will be yielded from the returned <tt>Iterator</tt>.
185: *
186: * @return A (possibly empty) <tt>Iterator</tt> that will yield the
187: * provider-class names in the given configuration file that are
188: * not yet members of the returned set
189: *
190: * @throws ServiceConfigurationError
191: * If an I/O error occurs while reading from the given URL, or
192: * if a configuration-file format error is detected
193: */
194: private static Iterator parse(Class service, URL u, Set returned)
195: throws ServiceConfigurationError {
196: InputStream in = null;
197: BufferedReader r = null;
198: ArrayList names = new ArrayList();
199: try {
200: in = u.openStream();
201: r = new BufferedReader(new InputStreamReader(in, "utf-8"));
202: int lc = 1;
203: while ((lc = parseLine(service, u, r, lc, names, returned)) >= 0)
204: ;
205: } catch (IOException x) {
206: fail(service, ": " + x);
207: } finally {
208: try {
209: if (r != null)
210: r.close();
211: if (in != null)
212: in.close();
213: } catch (IOException y) {
214: fail(service, ": " + y);
215: }
216: }
217: return names.iterator();
218: }
219:
220: /**
221: * Private inner class implementing fully-lazy provider lookup
222: */
223: private static class LazyIterator implements Iterator {
224:
225: Class service;
226: ClassLoader loader;
227: Enumeration configs = null;
228: Iterator pending = null;
229: Set returned = new TreeSet();
230: String nextName = null;
231:
232: private LazyIterator(Class service, ClassLoader loader) {
233: this .service = service;
234: this .loader = loader;
235: }
236:
237: public boolean hasNext() throws ServiceConfigurationError {
238: if (nextName != null) {
239: return true;
240: }
241: if (configs == null) {
242: try {
243: String fullName = prefix + service.getName();
244: if (loader == null)
245: configs = ClassLoader
246: .getSystemResources(fullName);
247: else
248: configs = loader.getResources(fullName);
249: } catch (IOException x) {
250: fail(service, ": " + x);
251: }
252: }
253: while ((pending == null) || !pending.hasNext()) {
254: if (!configs.hasMoreElements()) {
255: return false;
256: }
257: pending = parse(service, (URL) configs.nextElement(),
258: returned);
259: }
260: nextName = (String) pending.next();
261: return true;
262: }
263:
264: public Object next() throws ServiceConfigurationError {
265: if (!hasNext()) {
266: throw new NoSuchElementException();
267: }
268: String cn = nextName;
269: nextName = null;
270: try {
271: return Class.forName(cn, true, loader).newInstance();
272: } catch (ClassNotFoundException x) {
273: fail(service, "Provider " + cn + " not found");
274: } catch (Exception x) {
275: fail(service, "Provider " + cn
276: + " could not be instantiated: " + x);
277: }
278: return null; /* This cannot happen */
279: }
280:
281: public void remove() {
282: throw new UnsupportedOperationException();
283: }
284:
285: }
286:
287: /**
288: * Locates and incrementally instantiates the available providers of a
289: * given service using the given class loader.
290: *
291: * <p> This method transforms the name of the given service class into a
292: * provider-configuration filename as described above and then uses the
293: * <tt>getResources</tt> method of the given class loader to find all
294: * available files with that name. These files are then read and parsed to
295: * produce a list of provider-class names. The iterator that is returned
296: * uses the given class loader to lookup and then instantiate each element
297: * of the list.
298: *
299: * <p> Because it is possible for extensions to be installed into a running
300: * Java virtual machine, this method may return different results each time
301: * it is invoked. <p>
302: *
303: * @param service
304: * The service's abstract service class
305: *
306: * @param loader
307: * The class loader to be used to load provider-configuration files
308: * and instantiate provider classes, or <tt>null</tt> if the system
309: * class loader (or, failing that the bootstrap class loader) is to
310: * be used
311: *
312: * @return An <tt>Iterator</tt> that yields provider objects for the given
313: * service, in some arbitrary order. The iterator will throw a
314: * <tt>ServiceConfigurationError</tt> if a provider-configuration
315: * file violates the specified format or if a provider class cannot
316: * be found and instantiated.
317: *
318: * @throws ServiceConfigurationError
319: * If a provider-configuration file violates the specified format
320: * or names a provider class that cannot be found and instantiated
321: *
322: * @see #providers(java.lang.Class)
323: * @see #installedProviders(java.lang.Class)
324: */
325: public static Iterator providers(Class service, ClassLoader loader)
326: throws ServiceConfigurationError {
327: return new LazyIterator(service, loader);
328: }
329:
330: /**
331: * Locates and incrementally instantiates the available providers of a
332: * given service using the context class loader. This convenience method
333: * is equivalent to
334: *
335: * <pre>
336: * ClassLoader cl = Thread.currentThread().getContextClassLoader();
337: * return Service.providers(service, cl);
338: * </pre>
339: *
340: * @param service
341: * The service's abstract service class
342: *
343: * @return An <tt>Iterator</tt> that yields provider objects for the given
344: * service, in some arbitrary order. The iterator will throw a
345: * <tt>ServiceConfigurationError</tt> if a provider-configuration
346: * file violates the specified format or if a provider class cannot
347: * be found and instantiated.
348: *
349: * @throws ServiceConfigurationError
350: * If a provider-configuration file violates the specified format
351: * or names a provider class that cannot be found and instantiated
352: *
353: * @see #providers(java.lang.Class, java.lang.ClassLoader)
354: */
355: public static Iterator providers(Class service)
356: throws ServiceConfigurationError {
357: ClassLoader cl = Thread.currentThread().getContextClassLoader();
358: return Service.providers(service, cl);
359: }
360:
361: /**
362: * Locates and incrementally instantiates the available providers of a
363: * given service using the extension class loader. This convenience method
364: * simply locates the extension class loader, call it
365: * <tt>extClassLoader</tt>, and then does
366: *
367: * <pre>
368: * return Service.providers(service, extClassLoader);
369: * </pre>
370: *
371: * If the extension class loader cannot be found then the system class
372: * loader is used; if there is no system class loader then the bootstrap
373: * class loader is used.
374: *
375: * @param service
376: * The service's abstract service class
377: *
378: * @return An <tt>Iterator</tt> that yields provider objects for the given
379: * service, in some arbitrary order. The iterator will throw a
380: * <tt>ServiceConfigurationError</tt> if a provider-configuration
381: * file violates the specified format or if a provider class cannot
382: * be found and instantiated.
383: *
384: * @throws ServiceConfigurationError
385: * If a provider-configuration file violates the specified format
386: * or names a provider class that cannot be found and instantiated
387: *
388: * @see #providers(java.lang.Class, java.lang.ClassLoader)
389: */
390: public static Iterator installedProviders(Class service)
391: throws ServiceConfigurationError {
392: ClassLoader cl = ClassLoader.getSystemClassLoader();
393: if (cl != null)
394: cl = cl.getParent();
395: return Service.providers(service, cl);
396: }
397:
398: }
|