aoqi@0: /* aoqi@0: * Copyright (c) 1997, 2010, Oracle and/or its affiliates. All rights reserved. aoqi@0: * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. aoqi@0: * aoqi@0: * This code is free software; you can redistribute it and/or modify it aoqi@0: * under the terms of the GNU General Public License version 2 only, as aoqi@0: * published by the Free Software Foundation. Oracle designates this aoqi@0: * particular file as subject to the "Classpath" exception as provided aoqi@0: * by Oracle in the LICENSE file that accompanied this code. aoqi@0: * aoqi@0: * This code is distributed in the hope that it will be useful, but WITHOUT aoqi@0: * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or aoqi@0: * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License aoqi@0: * version 2 for more details (a copy is included in the LICENSE file that aoqi@0: * accompanied this code). aoqi@0: * aoqi@0: * You should have received a copy of the GNU General Public License version aoqi@0: * 2 along with this work; if not, write to the Free Software Foundation, aoqi@0: * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. aoqi@0: * aoqi@0: * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA aoqi@0: * or visit www.oracle.com if you need additional information or have any aoqi@0: * questions. aoqi@0: */ aoqi@0: aoqi@0: package com.sun.xml.internal.ws.policy.privateutil; aoqi@0: aoqi@0: import java.io.BufferedReader; aoqi@0: import java.io.IOException; aoqi@0: import java.io.InputStream; aoqi@0: import java.io.InputStreamReader; aoqi@0: import java.lang.reflect.Array; aoqi@0: import java.net.URL; aoqi@0: import java.util.ArrayList; aoqi@0: import java.util.Enumeration; aoqi@0: import java.util.Iterator; aoqi@0: import java.util.List; aoqi@0: import java.util.NoSuchElementException; aoqi@0: import java.util.Set; aoqi@0: import java.util.TreeSet; aoqi@0: aoqi@0: aoqi@0: /** aoqi@0: * aoqi@0: * A simple service-provider lookup mechanism. A service is a aoqi@0: * well-known set of interfaces and (usually abstract) classes. A service aoqi@0: * provider is a specific implementation of a service. The classes in a aoqi@0: * provider typically implement the interfaces and subclass the classes defined aoqi@0: * in the service itself. Service providers may be installed in an aoqi@0: * implementation of the Java platform in the form of extensions, that is, jar aoqi@0: * files placed into any of the usual extension directories. Providers may aoqi@0: * also be made available by adding them to the applet or application class aoqi@0: * path or by some other platform-specific means. aoqi@0: *

aoqi@0: *

In this lookup mechanism a service is represented by an interface or an aoqi@0: * abstract class. (A concrete class may be used, but this is not aoqi@0: * recommended.) A provider of a given service contains one or more concrete aoqi@0: * classes that extend this service class with data and code specific to aoqi@0: * the provider. This provider class will typically not be the entire aoqi@0: * provider itself but rather a proxy that contains enough information to aoqi@0: * decide whether the provider is able to satisfy a particular request together aoqi@0: * with code that can create the actual provider on demand. The details of aoqi@0: * provider classes tend to be highly service-specific; no single class or aoqi@0: * interface could possibly unify them, so no such class has been defined. The aoqi@0: * only requirement enforced here is that provider classes must have a aoqi@0: * zero-argument constructor so that they may be instantiated during lookup. aoqi@0: *

aoqi@0: *

A service provider identifies itself by placing a provider-configuration aoqi@0: * file in the resource directory META-INF/services. The file's name aoqi@0: * should consist of the fully-qualified name of the abstract service class. aoqi@0: * The file should contain a list of fully-qualified concrete provider-class aoqi@0: * names, one per line. Space and tab characters surrounding each name, as aoqi@0: * well as blank lines, are ignored. The comment character is '#' aoqi@0: * (0x23); on each line all characters following the first comment aoqi@0: * character are ignored. The file must be encoded in UTF-8. aoqi@0: *

aoqi@0: *

If a particular concrete provider class is named in more than one aoqi@0: * configuration file, or is named in the same configuration file more than aoqi@0: * once, then the duplicates will be ignored. The configuration file naming a aoqi@0: * particular provider need not be in the same jar file or other distribution aoqi@0: * unit as the provider itself. The provider must be accessible from the same aoqi@0: * class loader that was initially queried to locate the configuration file; aoqi@0: * note that this is not necessarily the class loader that found the file. aoqi@0: *

aoqi@0: *

Example: Suppose we have a service class named aoqi@0: * java.io.spi.CharCodec. It has two abstract methods: aoqi@0: *

aoqi@0: *

aoqi@0:  *   public abstract CharEncoder getEncoder(String encodingName);
aoqi@0:  *   public abstract CharDecoder getDecoder(String encodingName);
aoqi@0:  * 
aoqi@0: *

aoqi@0: * Each method returns an appropriate object or null if it cannot aoqi@0: * translate the given encoding. Typical CharCodec providers will aoqi@0: * support more than one encoding. aoqi@0: *

aoqi@0: *

If sun.io.StandardCodec is a provider of the CharCodec aoqi@0: * service then its jar file would contain the file aoqi@0: * META-INF/services/java.io.spi.CharCodec. This file would contain aoqi@0: * the single line: aoqi@0: *

aoqi@0: *

aoqi@0:  *   sun.io.StandardCodec    # Standard codecs for the platform
aoqi@0:  * 
aoqi@0: *

aoqi@0: * To locate an encoder for a given encoding name, the internal I/O code would aoqi@0: * do something like this: aoqi@0: *

aoqi@0: *

aoqi@0:  *   CharEncoder getEncoder(String encodingName) {
aoqi@0:  *       for( CharCodec cc : ServiceFinder.find(CharCodec.class) ) {
aoqi@0:  *           CharEncoder ce = cc.getEncoder(encodingName);
aoqi@0:  *           if (ce != null)
aoqi@0:  *               return ce;
aoqi@0:  *       }
aoqi@0:  *       return null;
aoqi@0:  *   }
aoqi@0:  * 
aoqi@0: *

aoqi@0: * The provider-lookup mechanism always executes in the security context of the aoqi@0: * caller. Trusted system code should typically invoke the methods in this aoqi@0: * class from within a privileged security context. aoqi@0: * aoqi@0: * @author Mark Reinhold aoqi@0: * @version 1.11, 03/12/19 aoqi@0: * @since 1.3 aoqi@0: */ aoqi@0: final class ServiceFinder implements Iterable { aoqi@0: private static final PolicyLogger LOGGER = PolicyLogger.getLogger(ServiceFinder.class); aoqi@0: aoqi@0: private static final String prefix = "META-INF/services/"; aoqi@0: aoqi@0: private final Class serviceClass; aoqi@0: private final ClassLoader classLoader; aoqi@0: aoqi@0: /** aoqi@0: * Locates and incrementally instantiates the available providers of a aoqi@0: * given service using the given class loader. aoqi@0: *

aoqi@0: *

This method transforms the name of the given service class into a aoqi@0: * provider-configuration filename as described above and then uses the aoqi@0: * getResources method of the given class loader to find all aoqi@0: * available files with that name. These files are then read and parsed to aoqi@0: * produce a list of provider-class names. The iterator that is returned aoqi@0: * uses the given class loader to lookup and then instantiate each element aoqi@0: * of the list. aoqi@0: *

aoqi@0: *

Because it is possible for extensions to be installed into a running aoqi@0: * Java virtual machine, this method may return different results each time aoqi@0: * it is invoked.

aoqi@0: * aoqi@0: * @param service The service's abstract service class aoqi@0: * @param loader The class loader to be used to load provider-configuration files aoqi@0: * and instantiate provider classes, or null if the system aoqi@0: * class loader (or, failing that the bootstrap class loader) is to aoqi@0: * be used aoqi@0: * @throws ServiceConfigurationError If a provider-configuration file violates the specified format aoqi@0: * or names a provider class that cannot be found and instantiated aoqi@0: * @see #find(Class) aoqi@0: */ aoqi@0: static ServiceFinder find(final Class service, final ClassLoader loader) { aoqi@0: if (null==service) { aoqi@0: throw LOGGER.logSevereException(new NullPointerException(LocalizationMessages.WSP_0032_SERVICE_CAN_NOT_BE_NULL())); aoqi@0: } aoqi@0: return new ServiceFinder(service,loader); aoqi@0: } aoqi@0: aoqi@0: /** aoqi@0: * Locates and incrementally instantiates the available providers of a aoqi@0: * given service using the context class loader. This convenience method aoqi@0: * is equivalent to aoqi@0: *

aoqi@0: *

aoqi@0:      *   ClassLoader cl = Thread.currentThread().getContextClassLoader();
aoqi@0:      *   return Service.providers(service, cl);
aoqi@0:      * 
aoqi@0: * aoqi@0: * @param service The service's abstract service class aoqi@0: * aoqi@0: * @throws ServiceConfigurationError If a provider-configuration file violates the specified format aoqi@0: * or names a provider class that cannot be found and instantiated aoqi@0: * @see #find(Class, ClassLoader) aoqi@0: */ aoqi@0: public static ServiceFinder find(final Class service) { aoqi@0: return find(service,Thread.currentThread().getContextClassLoader()); aoqi@0: } aoqi@0: aoqi@0: private ServiceFinder(Class service, ClassLoader loader) { aoqi@0: this.serviceClass = service; aoqi@0: this.classLoader = loader; aoqi@0: } aoqi@0: aoqi@0: /** aoqi@0: * Returns discovered objects incrementally. aoqi@0: * aoqi@0: * @return An Iterator that yields provider objects for the given aoqi@0: * service, in some arbitrary order. The iterator will throw a aoqi@0: * ServiceConfigurationError if a provider-configuration aoqi@0: * file violates the specified format or if a provider class cannot aoqi@0: * be found and instantiated. aoqi@0: */ aoqi@0: public Iterator iterator() { aoqi@0: return new LazyIterator(serviceClass,classLoader); aoqi@0: } aoqi@0: aoqi@0: /** aoqi@0: * Returns discovered objects all at once. aoqi@0: * aoqi@0: * @return aoqi@0: * can be empty but never null. aoqi@0: * aoqi@0: * @throws ServiceConfigurationError aoqi@0: */ aoqi@0: @SuppressWarnings({"unchecked"}) aoqi@0: public T[] toArray() { aoqi@0: List result = new ArrayList(); aoqi@0: for (T t : this) { aoqi@0: result.add(t); aoqi@0: } aoqi@0: return result.toArray((T[])Array.newInstance(serviceClass,result.size())); aoqi@0: } aoqi@0: aoqi@0: private static void fail(final Class service, final String msg, final Throwable cause) aoqi@0: throws ServiceConfigurationError { aoqi@0: final ServiceConfigurationError sce aoqi@0: = new ServiceConfigurationError(LocalizationMessages.WSP_0025_SPI_FAIL_SERVICE_MSG(service.getName(), msg)); aoqi@0: if (null != cause) { aoqi@0: sce.initCause(cause); aoqi@0: } aoqi@0: aoqi@0: throw LOGGER.logSevereException(sce); aoqi@0: } aoqi@0: aoqi@0: /* private static void fail(Class service, String msg) aoqi@0: throws ServiceConfigurationError { aoqi@0: throw new ServiceConfigurationError(LocalizationMessages.WSP_0025_SPI_FAIL_SERVICE_MSG(service.getName(), msg)); aoqi@0: }*/ aoqi@0: aoqi@0: private static void fail(final Class service, final URL u, final int line, final String msg, final Throwable cause) aoqi@0: throws ServiceConfigurationError { aoqi@0: fail(service, LocalizationMessages.WSP_0024_SPI_FAIL_SERVICE_URL_LINE_MSG(u , line, msg), cause); aoqi@0: } aoqi@0: aoqi@0: /** aoqi@0: * Parse a single line from the given configuration file, adding the name aoqi@0: * on the line to both the names list and the returned set iff the name is aoqi@0: * not already a member of the returned set. aoqi@0: */ aoqi@0: private static int parseLine(final Class service, final URL u, final BufferedReader r, final int lc, aoqi@0: final List names, final Set returned) aoqi@0: throws IOException, ServiceConfigurationError { aoqi@0: String ln = r.readLine(); aoqi@0: if (ln == null) { aoqi@0: return -1; aoqi@0: } aoqi@0: final int ci = ln.indexOf('#'); aoqi@0: if (ci >= 0) ln = ln.substring(0, ci); aoqi@0: ln = ln.trim(); aoqi@0: final int n = ln.length(); aoqi@0: if (n != 0) { aoqi@0: if ((ln.indexOf(' ') >= 0) || (ln.indexOf('\t') >= 0)) aoqi@0: fail(service, u, lc, LocalizationMessages.WSP_0067_ILLEGAL_CFG_FILE_SYNTAX(), null); aoqi@0: int cp = ln.codePointAt(0); aoqi@0: if (!Character.isJavaIdentifierStart(cp)) aoqi@0: fail(service, u, lc, LocalizationMessages.WSP_0066_ILLEGAL_PROVIDER_CLASSNAME(ln), null); aoqi@0: for (int i = Character.charCount(cp); i < n; i += Character.charCount(cp)) { aoqi@0: cp = ln.codePointAt(i); aoqi@0: if (!Character.isJavaIdentifierPart(cp) && (cp != '.')) aoqi@0: fail(service, u, lc, LocalizationMessages.WSP_0066_ILLEGAL_PROVIDER_CLASSNAME(ln), null); aoqi@0: } aoqi@0: if (!returned.contains(ln)) { aoqi@0: names.add(ln); aoqi@0: returned.add(ln); aoqi@0: } aoqi@0: } aoqi@0: return lc + 1; aoqi@0: } aoqi@0: aoqi@0: /** aoqi@0: * Parse the content of the given URL as a provider-configuration file. aoqi@0: * aoqi@0: * @param service The service class for which providers are being sought; aoqi@0: * used to construct error detail strings aoqi@0: * @param u The URL naming the configuration file to be parsed aoqi@0: * @param returned A Set containing the names of provider classes that have already aoqi@0: * been returned. This set will be updated to contain the names aoqi@0: * that will be yielded from the returned Iterator. aoqi@0: * @return A (possibly empty) Iterator that will yield the aoqi@0: * provider-class names in the given configuration file that are aoqi@0: * not yet members of the returned set aoqi@0: * @throws ServiceConfigurationError If an I/O error occurs while reading from the given URL, or aoqi@0: * if a configuration-file format error is detected aoqi@0: */ aoqi@0: @SuppressWarnings({"StatementWithEmptyBody"}) aoqi@0: private static Iterator parse(Class service, URL u, Set returned) aoqi@0: throws ServiceConfigurationError { aoqi@0: InputStream in = null; aoqi@0: BufferedReader r = null; aoqi@0: ArrayList names = new ArrayList(); aoqi@0: try { aoqi@0: in = u.openStream(); aoqi@0: r = new BufferedReader(new InputStreamReader(in, "utf-8")); aoqi@0: int lc = 1; aoqi@0: while ((lc = parseLine(service, u, r, lc, names, returned)) >= 0) ; aoqi@0: } catch (IOException x) { aoqi@0: fail(service, ": " + x, x); aoqi@0: } finally { aoqi@0: try { aoqi@0: if (r != null) r.close(); aoqi@0: if (in != null) in.close(); aoqi@0: } catch (IOException y) { aoqi@0: fail(service, ": " + y, y); aoqi@0: } aoqi@0: } aoqi@0: return names.iterator(); aoqi@0: } aoqi@0: aoqi@0: aoqi@0: /** aoqi@0: * Private inner class implementing fully-lazy provider lookup aoqi@0: */ aoqi@0: private static class LazyIterator implements Iterator { aoqi@0: Class service; aoqi@0: ClassLoader loader; aoqi@0: Enumeration configs = null; aoqi@0: Iterator pending = null; aoqi@0: Set returned = new TreeSet(); aoqi@0: String nextName = null; aoqi@0: aoqi@0: private LazyIterator(Class service, ClassLoader loader) { aoqi@0: this.service = service; aoqi@0: this.loader = loader; aoqi@0: } aoqi@0: aoqi@0: public boolean hasNext() throws ServiceConfigurationError { aoqi@0: if (nextName != null) { aoqi@0: return true; aoqi@0: } aoqi@0: if (configs == null) { aoqi@0: try { aoqi@0: final String fullName = prefix + service.getName(); aoqi@0: if (loader == null) aoqi@0: configs = ClassLoader.getSystemResources(fullName); aoqi@0: else aoqi@0: configs = loader.getResources(fullName); aoqi@0: } catch (IOException x) { aoqi@0: fail(service, ": " + x, x); aoqi@0: } aoqi@0: } aoqi@0: while ((pending == null) || !pending.hasNext()) { aoqi@0: if (!configs.hasMoreElements()) { aoqi@0: return false; aoqi@0: } aoqi@0: pending = parse(service, configs.nextElement(), returned); aoqi@0: } aoqi@0: nextName = pending.next(); aoqi@0: return true; aoqi@0: } aoqi@0: aoqi@0: public T next() throws ServiceConfigurationError { aoqi@0: if (!hasNext()) { aoqi@0: throw new NoSuchElementException(); aoqi@0: } aoqi@0: final String cn = nextName; aoqi@0: nextName = null; aoqi@0: try { aoqi@0: return service.cast(Class.forName(cn, true, loader).newInstance()); aoqi@0: } catch (ClassNotFoundException x) { aoqi@0: fail(service, LocalizationMessages.WSP_0027_SERVICE_PROVIDER_NOT_FOUND(cn), x); aoqi@0: } catch (Exception x) { aoqi@0: fail(service, LocalizationMessages.WSP_0028_SERVICE_PROVIDER_COULD_NOT_BE_INSTANTIATED(cn), x); aoqi@0: } aoqi@0: return null; /* This cannot happen */ aoqi@0: } aoqi@0: aoqi@0: public void remove() { aoqi@0: throw new UnsupportedOperationException(); aoqi@0: } aoqi@0: } aoqi@0: }