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

ohair@286: *

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

ohair@286: *

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

ohair@286: *

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

ohair@286: *

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

ohair@286: *

ohair@286:  *   public abstract CharEncoder getEncoder(String encodingName);
ohair@286:  *   public abstract CharDecoder getDecoder(String encodingName);
ohair@286:  * 
ohair@286: *

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

ohair@286: *

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

ohair@286: *

ohair@286:  *   sun.io.StandardCodec    # Standard codecs for the platform
ohair@286:  * 
ohair@286: *

ohair@286: * To locate an codec for a given encoding name, the internal I/O code would ohair@286: * do something like this: ohair@286: *

ohair@286: *

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

ohair@286: * The provider-lookup mechanism always executes in the security context of the ohair@286: * caller. Trusted system code should typically invoke the methods in this ohair@286: * class from within a privileged security context. ohair@286: * ohair@286: * @author Mark Reinhold ohair@286: * @version 1.11, 03/12/19 ohair@286: * @since 1.3 ohair@286: */ ohair@286: public final class ServiceFinder implements Iterable { ohair@286: ohair@286: private static final String prefix = "META-INF/services/"; ohair@286: alanb@368: private static WeakHashMap> serviceNameCache alanb@368: = new WeakHashMap>(); alanb@368: ohair@286: private final Class serviceClass; ohair@286: private final @Nullable ClassLoader classLoader; ohair@286: private final @Nullable ComponentEx component; ohair@286: alanb@368: private static class ServiceName { alanb@368: final String className; alanb@368: final URL config; alanb@368: public ServiceName(String className, URL config) { alanb@368: this.className = className; alanb@368: this.config = config; alanb@368: } alanb@368: } alanb@368: ohair@286: public static ServiceFinder find(@NotNull Class service, @Nullable ClassLoader loader, Component component) { alanb@368: return new ServiceFinder(service, loader, component); ohair@286: } ohair@286: ohair@286: public static ServiceFinder find(@NotNull Class service, Component component) { ohair@286: return find(service,Thread.currentThread().getContextClassLoader(),component); ohair@286: } ohair@286: ohair@286: /** ohair@286: * Locates and incrementally instantiates the available providers of a ohair@286: * given service using the given class loader. ohair@286: *

ohair@286: *

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

ohair@286: *

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

ohair@286: * ohair@286: * @param service The service's abstract service class ohair@286: * @param loader The class loader to be used to load provider-configuration files ohair@286: * and instantiate provider classes, or null if the system ohair@286: * class loader (or, failing that the bootstrap class loader) is to ohair@286: * be used ohair@286: * @throws ServiceConfigurationError If a provider-configuration file violates the specified format ohair@286: * or names a provider class that cannot be found and instantiated ohair@286: * @see #find(Class) ohair@286: */ ohair@286: public static ServiceFinder find(@NotNull Class service, @Nullable ClassLoader loader) { ohair@286: return find(service, loader, ContainerResolver.getInstance().getContainer()); ohair@286: } ohair@286: ohair@286: /** ohair@286: * Locates and incrementally instantiates the available providers of a ohair@286: * given service using the context class loader. This convenience method ohair@286: * is equivalent to ohair@286: *

ohair@286: *

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