Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/share/classes/javax/imageio/spi/ServiceRegistry.java
38830 views
/*1* Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425package javax.imageio.spi;2627import java.io.File;28import java.security.AccessControlContext;29import java.security.AccessController;30import java.security.PrivilegedAction;31import java.util.ArrayList;32import java.util.HashMap;33import java.util.Iterator;34import java.util.List;35import java.util.Map;36import java.util.NoSuchElementException;37import java.util.Set;38import java.util.ServiceLoader;3940/**41* A registry for service provider instances.42*43* <p> A <i>service</i> is a well-known set of interfaces and (usually44* abstract) classes. A <i>service provider</i> is a specific45* implementation of a service. The classes in a provider typically46* implement the interface or subclass the class defined by the47* service itself.48*49* <p> Service providers are stored in one or more <i>categories</i>,50* each of which is defined by a class of interface (described by a51* <code>Class</code> object) that all of its members must implement.52* The set of categories may be changed dynamically.53*54* <p> Only a single instance of a given leaf class (that is, the55* actual class returned by <code>getClass()</code>, as opposed to any56* inherited classes or interfaces) may be registered. That is,57* suppose that the58* <code>com.mycompany.mypkg.GreenServiceProvider</code> class59* implements the <code>com.mycompany.mypkg.MyService</code>60* interface. If a <code>GreenServiceProvider</code> instance is61* registered, it will be stored in the category defined by the62* <code>MyService</code> class. If a new instance of63* <code>GreenServiceProvider</code> is registered, it will replace64* the previous instance. In practice, service provider objects are65* usually singletons so this behavior is appropriate.66*67* <p> To declare a service provider, a <code>services</code>68* subdirectory is placed within the <code>META-INF</code> directory69* that is present in every JAR file. This directory contains a file70* for each service provider interface that has one or more71* implementation classes present in the JAR file. For example, if72* the JAR file contained a class named73* <code>com.mycompany.mypkg.MyServiceImpl</code> which implements the74* <code>javax.someapi.SomeService</code> interface, the JAR file75* would contain a file named: <pre>76* META-INF/services/javax.someapi.SomeService </pre>77*78* containing the line:79*80* <pre>81* com.mycompany.mypkg.MyService82* </pre>83*84* <p> The service provider classes should be to be lightweight and85* quick to load. Implementations of these interfaces should avoid86* complex dependencies on other classes and on native code. The usual87* pattern for more complex services is to register a lightweight88* proxy for the heavyweight service.89*90* <p> An application may customize the contents of a registry as it91* sees fit, so long as it has the appropriate runtime permission.92*93* <p> For more details on declaring service providers, and the JAR94* format in general, see the <a95* href="../../../../technotes/guides/jar/jar.html">96* JAR File Specification</a>.97*98* @see RegisterableService99*100*/101public class ServiceRegistry {102103// Class -> Registry104private Map categoryMap = new HashMap();105106/**107* Constructs a <code>ServiceRegistry</code> instance with a108* set of categories taken from the <code>categories</code>109* argument.110*111* @param categories an <code>Iterator</code> containing112* <code>Class</code> objects to be used to define categories.113*114* @exception IllegalArgumentException if115* <code>categories</code> is <code>null</code>.116*/117public ServiceRegistry(Iterator<Class<?>> categories) {118if (categories == null) {119throw new IllegalArgumentException("categories == null!");120}121while (categories.hasNext()) {122Class category = (Class)categories.next();123SubRegistry reg = new SubRegistry(this, category);124categoryMap.put(category, reg);125}126}127128// The following two methods expose functionality from129// sun.misc.Service. If that class is made public, they may be130// removed.131//132// The sun.misc.ServiceConfigurationError class may also be133// exposed, in which case the references to 'an134// <code>Error</code>' below should be changed to 'a135// <code>ServiceConfigurationError</code>'.136137/**138* Searches for implementations of a particular service class139* using the given class loader.140*141* <p> This method transforms the name of the given service class142* into a provider-configuration filename as described in the143* class comment and then uses the <code>getResources</code>144* method of the given class loader to find all available files145* with that name. These files are then read and parsed to146* produce a list of provider-class names. The iterator that is147* returned uses the given class loader to look up and then148* instantiate each element of the list.149*150* <p> Because it is possible for extensions to be installed into151* a running Java virtual machine, this method may return152* different results each time it is invoked.153*154* @param providerClass a <code>Class</code>object indicating the155* class or interface of the service providers being detected.156*157* @param loader the class loader to be used to load158* provider-configuration files and instantiate provider classes,159* or <code>null</code> if the system class loader (or, failing that160* the bootstrap class loader) is to be used.161*162* @param <T> the type of the providerClass.163*164* @return An <code>Iterator</code> that yields provider objects165* for the given service, in some arbitrary order. The iterator166* will throw an <code>Error</code> if a provider-configuration167* file violates the specified format or if a provider class168* cannot be found and instantiated.169*170* @exception IllegalArgumentException if171* <code>providerClass</code> is <code>null</code>.172*/173public static <T> Iterator<T> lookupProviders(Class<T> providerClass,174ClassLoader loader)175{176if (providerClass == null) {177throw new IllegalArgumentException("providerClass == null!");178}179return ServiceLoader.load(providerClass, loader).iterator();180}181182/**183* Locates and incrementally instantiates the available providers184* of a given service using the context class loader. This185* convenience method is equivalent to:186*187* <pre>188* ClassLoader cl = Thread.currentThread().getContextClassLoader();189* return Service.providers(service, cl);190* </pre>191*192* @param providerClass a <code>Class</code>object indicating the193* class or interface of the service providers being detected.194*195* @param <T> the type of the providerClass.196*197* @return An <code>Iterator</code> that yields provider objects198* for the given service, in some arbitrary order. The iterator199* will throw an <code>Error</code> if a provider-configuration200* file violates the specified format or if a provider class201* cannot be found and instantiated.202*203* @exception IllegalArgumentException if204* <code>providerClass</code> is <code>null</code>.205*/206public static <T> Iterator<T> lookupProviders(Class<T> providerClass) {207if (providerClass == null) {208throw new IllegalArgumentException("providerClass == null!");209}210return ServiceLoader.load(providerClass).iterator();211}212213/**214* Returns an <code>Iterator</code> of <code>Class</code> objects215* indicating the current set of categories. The iterator will be216* empty if no categories exist.217*218* @return an <code>Iterator</code> containing219* <code>Class</code>objects.220*/221public Iterator<Class<?>> getCategories() {222Set keySet = categoryMap.keySet();223return keySet.iterator();224}225226/**227* Returns an Iterator containing the subregistries to which the228* provider belongs.229*/230private Iterator getSubRegistries(Object provider) {231List l = new ArrayList();232Iterator iter = categoryMap.keySet().iterator();233while (iter.hasNext()) {234Class c = (Class)iter.next();235if (c.isAssignableFrom(provider.getClass())) {236l.add((SubRegistry)categoryMap.get(c));237}238}239return l.iterator();240}241242/**243* Adds a service provider object to the registry. The provider244* is associated with the given category.245*246* <p> If <code>provider</code> implements the247* <code>RegisterableService</code> interface, its248* <code>onRegistration</code> method will be called. Its249* <code>onDeregistration</code> method will be called each time250* it is deregistered from a category, for example if a251* category is removed or the registry is garbage collected.252*253* @param provider the service provide object to be registered.254* @param category the category under which to register the255* provider.256* @param <T> the type of the provider.257*258* @return true if no provider of the same class was previously259* registered in the same category category.260*261* @exception IllegalArgumentException if <code>provider</code> is262* <code>null</code>.263* @exception IllegalArgumentException if there is no category264* corresponding to <code>category</code>.265* @exception ClassCastException if provider does not implement266* the <code>Class</code> defined by <code>category</code>.267*/268public <T> boolean registerServiceProvider(T provider,269Class<T> category) {270if (provider == null) {271throw new IllegalArgumentException("provider == null!");272}273SubRegistry reg = (SubRegistry)categoryMap.get(category);274if (reg == null) {275throw new IllegalArgumentException("category unknown!");276}277if (!category.isAssignableFrom(provider.getClass())) {278throw new ClassCastException();279}280281return reg.registerServiceProvider(provider);282}283284/**285* Adds a service provider object to the registry. The provider286* is associated within each category present in the registry287* whose <code>Class</code> it implements.288*289* <p> If <code>provider</code> implements the290* <code>RegisterableService</code> interface, its291* <code>onRegistration</code> method will be called once for each292* category it is registered under. Its293* <code>onDeregistration</code> method will be called each time294* it is deregistered from a category or when the registry is295* finalized.296*297* @param provider the service provider object to be registered.298*299* @exception IllegalArgumentException if300* <code>provider</code> is <code>null</code>.301*/302public void registerServiceProvider(Object provider) {303if (provider == null) {304throw new IllegalArgumentException("provider == null!");305}306Iterator regs = getSubRegistries(provider);307while (regs.hasNext()) {308SubRegistry reg = (SubRegistry)regs.next();309reg.registerServiceProvider(provider);310}311}312313/**314* Adds a set of service provider objects, taken from an315* <code>Iterator</code> to the registry. Each provider is316* associated within each category present in the registry whose317* <code>Class</code> it implements.318*319* <p> For each entry of <code>providers</code> that implements320* the <code>RegisterableService</code> interface, its321* <code>onRegistration</code> method will be called once for each322* category it is registered under. Its323* <code>onDeregistration</code> method will be called each time324* it is deregistered from a category or when the registry is325* finalized.326*327* @param providers an Iterator containing service provider328* objects to be registered.329*330* @exception IllegalArgumentException if <code>providers</code>331* is <code>null</code> or contains a <code>null</code> entry.332*/333public void registerServiceProviders(Iterator<?> providers) {334if (providers == null) {335throw new IllegalArgumentException("provider == null!");336}337while (providers.hasNext()) {338registerServiceProvider(providers.next());339}340}341342/**343* Removes a service provider object from the given category. If344* the provider was not previously registered, nothing happens and345* <code>false</code> is returned. Otherwise, <code>true</code>346* is returned. If an object of the same class as347* <code>provider</code> but not equal (using <code>==</code>) to348* <code>provider</code> is registered, it will not be349* deregistered.350*351* <p> If <code>provider</code> implements the352* <code>RegisterableService</code> interface, its353* <code>onDeregistration</code> method will be called.354*355* @param provider the service provider object to be deregistered.356* @param category the category from which to deregister the357* provider.358* @param <T> the type of the provider.359*360* @return <code>true</code> if the provider was previously361* registered in the same category category,362* <code>false</code> otherwise.363*364* @exception IllegalArgumentException if <code>provider</code> is365* <code>null</code>.366* @exception IllegalArgumentException if there is no category367* corresponding to <code>category</code>.368* @exception ClassCastException if provider does not implement369* the class defined by <code>category</code>.370*/371public <T> boolean deregisterServiceProvider(T provider,372Class<T> category) {373if (provider == null) {374throw new IllegalArgumentException("provider == null!");375}376SubRegistry reg = (SubRegistry)categoryMap.get(category);377if (reg == null) {378throw new IllegalArgumentException("category unknown!");379}380if (!category.isAssignableFrom(provider.getClass())) {381throw new ClassCastException();382}383return reg.deregisterServiceProvider(provider);384}385386/**387* Removes a service provider object from all categories that388* contain it.389*390* @param provider the service provider object to be deregistered.391*392* @exception IllegalArgumentException if <code>provider</code> is393* <code>null</code>.394*/395public void deregisterServiceProvider(Object provider) {396if (provider == null) {397throw new IllegalArgumentException("provider == null!");398}399Iterator regs = getSubRegistries(provider);400while (regs.hasNext()) {401SubRegistry reg = (SubRegistry)regs.next();402reg.deregisterServiceProvider(provider);403}404}405406/**407* Returns <code>true</code> if <code>provider</code> is currently408* registered.409*410* @param provider the service provider object to be queried.411*412* @return <code>true</code> if the given provider has been413* registered.414*415* @exception IllegalArgumentException if <code>provider</code> is416* <code>null</code>.417*/418public boolean contains(Object provider) {419if (provider == null) {420throw new IllegalArgumentException("provider == null!");421}422Iterator regs = getSubRegistries(provider);423while (regs.hasNext()) {424SubRegistry reg = (SubRegistry)regs.next();425if (reg.contains(provider)) {426return true;427}428}429430return false;431}432433/**434* Returns an <code>Iterator</code> containing all registered435* service providers in the given category. If436* <code>useOrdering</code> is <code>false</code>, the iterator437* will return all of the server provider objects in an arbitrary438* order. Otherwise, the ordering will respect any pairwise439* orderings that have been set. If the graph of pairwise440* orderings contains cycles, any providers that belong to a cycle441* will not be returned.442*443* @param category the category to be retrieved from.444* @param useOrdering <code>true</code> if pairwise orderings445* should be taken account in ordering the returned objects.446* @param <T> the type of the category.447*448* @return an <code>Iterator</code> containing service provider449* objects from the given category, possibly in order.450*451* @exception IllegalArgumentException if there is no category452* corresponding to <code>category</code>.453*/454public <T> Iterator<T> getServiceProviders(Class<T> category,455boolean useOrdering) {456SubRegistry reg = (SubRegistry)categoryMap.get(category);457if (reg == null) {458throw new IllegalArgumentException("category unknown!");459}460return reg.getServiceProviders(useOrdering);461}462463/**464* A simple filter interface used by465* <code>ServiceRegistry.getServiceProviders</code> to select466* providers matching an arbitrary criterion. Classes that467* implement this interface should be defined in order to make use468* of the <code>getServiceProviders</code> method of469* <code>ServiceRegistry</code> that takes a <code>Filter</code>.470*471* @see ServiceRegistry#getServiceProviders(Class, ServiceRegistry.Filter, boolean)472*/473public interface Filter {474475/**476* Returns <code>true</code> if the given477* <code>provider</code> object matches the criterion defined478* by this <code>Filter</code>.479*480* @param provider a service provider <code>Object</code>.481*482* @return true if the provider matches the criterion.483*/484boolean filter(Object provider);485}486487/**488* Returns an <code>Iterator</code> containing service provider489* objects within a given category that satisfy a criterion490* imposed by the supplied <code>ServiceRegistry.Filter</code>491* object's <code>filter</code> method.492*493* <p> The <code>useOrdering</code> argument controls the494* ordering of the results using the same rules as495* <code>getServiceProviders(Class, boolean)</code>.496*497* @param category the category to be retrieved from.498* @param filter an instance of <code>ServiceRegistry.Filter</code>499* whose <code>filter</code> method will be invoked.500* @param useOrdering <code>true</code> if pairwise orderings501* should be taken account in ordering the returned objects.502* @param <T> the type of the category.503*504* @return an <code>Iterator</code> containing service provider505* objects from the given category, possibly in order.506*507* @exception IllegalArgumentException if there is no category508* corresponding to <code>category</code>.509*/510public <T> Iterator<T> getServiceProviders(Class<T> category,511Filter filter,512boolean useOrdering) {513SubRegistry reg = (SubRegistry)categoryMap.get(category);514if (reg == null) {515throw new IllegalArgumentException("category unknown!");516}517Iterator iter = getServiceProviders(category, useOrdering);518return new FilterIterator(iter, filter);519}520521/**522* Returns the currently registered service provider object that523* is of the given class type. At most one object of a given524* class is allowed to be registered at any given time. If no525* registered object has the desired class type, <code>null</code>526* is returned.527*528* @param providerClass the <code>Class</code> of the desired529* service provider object.530* @param <T> the type of the provider.531*532* @return a currently registered service provider object with the533* desired <code>Class</code>type, or <code>null</code> is none is534* present.535*536* @exception IllegalArgumentException if <code>providerClass</code> is537* <code>null</code>.538*/539public <T> T getServiceProviderByClass(Class<T> providerClass) {540if (providerClass == null) {541throw new IllegalArgumentException("providerClass == null!");542}543Iterator iter = categoryMap.keySet().iterator();544while (iter.hasNext()) {545Class c = (Class)iter.next();546if (c.isAssignableFrom(providerClass)) {547SubRegistry reg = (SubRegistry)categoryMap.get(c);548T provider = reg.getServiceProviderByClass(providerClass);549if (provider != null) {550return provider;551}552}553}554return null;555}556557/**558* Sets a pairwise ordering between two service provider objects559* within a given category. If one or both objects are not560* currently registered within the given category, or if the561* desired ordering is already set, nothing happens and562* <code>false</code> is returned. If the providers previously563* were ordered in the reverse direction, that ordering is564* removed.565*566* <p> The ordering will be used by the567* <code>getServiceProviders</code> methods when their568* <code>useOrdering</code> argument is <code>true</code>.569*570* @param category a <code>Class</code> object indicating the571* category under which the preference is to be established.572* @param firstProvider the preferred provider.573* @param secondProvider the provider to which574* <code>firstProvider</code> is preferred.575* @param <T> the type of the category.576*577* @return <code>true</code> if a previously unset ordering578* was established.579*580* @exception IllegalArgumentException if either provider is581* <code>null</code> or they are the same object.582* @exception IllegalArgumentException if there is no category583* corresponding to <code>category</code>.584*/585public <T> boolean setOrdering(Class<T> category,586T firstProvider,587T secondProvider) {588if (firstProvider == null || secondProvider == null) {589throw new IllegalArgumentException("provider is null!");590}591if (firstProvider == secondProvider) {592throw new IllegalArgumentException("providers are the same!");593}594SubRegistry reg = (SubRegistry)categoryMap.get(category);595if (reg == null) {596throw new IllegalArgumentException("category unknown!");597}598if (reg.contains(firstProvider) &&599reg.contains(secondProvider)) {600return reg.setOrdering(firstProvider, secondProvider);601}602return false;603}604605/**606* Sets a pairwise ordering between two service provider objects607* within a given category. If one or both objects are not608* currently registered within the given category, or if no609* ordering is currently set between them, nothing happens610* and <code>false</code> is returned.611*612* <p> The ordering will be used by the613* <code>getServiceProviders</code> methods when their614* <code>useOrdering</code> argument is <code>true</code>.615*616* @param category a <code>Class</code> object indicating the617* category under which the preference is to be disestablished.618* @param firstProvider the formerly preferred provider.619* @param secondProvider the provider to which620* <code>firstProvider</code> was formerly preferred.621* @param <T> the type of the category.622*623* @return <code>true</code> if a previously set ordering was624* disestablished.625*626* @exception IllegalArgumentException if either provider is627* <code>null</code> or they are the same object.628* @exception IllegalArgumentException if there is no category629* corresponding to <code>category</code>.630*/631public <T> boolean unsetOrdering(Class<T> category,632T firstProvider,633T secondProvider) {634if (firstProvider == null || secondProvider == null) {635throw new IllegalArgumentException("provider is null!");636}637if (firstProvider == secondProvider) {638throw new IllegalArgumentException("providers are the same!");639}640SubRegistry reg = (SubRegistry)categoryMap.get(category);641if (reg == null) {642throw new IllegalArgumentException("category unknown!");643}644if (reg.contains(firstProvider) &&645reg.contains(secondProvider)) {646return reg.unsetOrdering(firstProvider, secondProvider);647}648return false;649}650651/**652* Deregisters all service provider object currently registered653* under the given category.654*655* @param category the category to be emptied.656*657* @exception IllegalArgumentException if there is no category658* corresponding to <code>category</code>.659*/660public void deregisterAll(Class<?> category) {661SubRegistry reg = (SubRegistry)categoryMap.get(category);662if (reg == null) {663throw new IllegalArgumentException("category unknown!");664}665reg.clear();666}667668/**669* Deregisters all currently registered service providers from all670* categories.671*/672public void deregisterAll() {673Iterator iter = categoryMap.values().iterator();674while (iter.hasNext()) {675SubRegistry reg = (SubRegistry)iter.next();676reg.clear();677}678}679680/**681* Finalizes this object prior to garbage collection. The682* <code>deregisterAll</code> method is called to deregister all683* currently registered service providers. This method should not684* be called from application code.685*686* @exception Throwable if an error occurs during superclass687* finalization.688*/689public void finalize() throws Throwable {690deregisterAll();691super.finalize();692}693}694695696/**697* A portion of a registry dealing with a single superclass or698* interface.699*/700class SubRegistry {701702ServiceRegistry registry;703704Class category;705706// Provider Objects organized by partial ordering707final PartiallyOrderedSet poset = new PartiallyOrderedSet();708709// Class -> Provider Object of that class710final Map<Class<?>,Object> map = new HashMap();711final Map<Class<?>,AccessControlContext> accMap = new HashMap<>();712713public SubRegistry(ServiceRegistry registry, Class category) {714this.registry = registry;715this.category = category;716}717718public boolean registerServiceProvider(Object provider) {719Object oprovider = map.get(provider.getClass());720boolean present = oprovider != null;721722if (present) {723deregisterServiceProvider(oprovider);724}725map.put(provider.getClass(), provider);726accMap.put(provider.getClass(), AccessController.getContext());727poset.add(provider);728if (provider instanceof RegisterableService) {729RegisterableService rs = (RegisterableService)provider;730rs.onRegistration(registry, category);731}732733return !present;734}735736/**737* If the provider was not previously registered, do nothing.738*739* @return true if the provider was previously registered.740*/741public boolean deregisterServiceProvider(Object provider) {742Object oprovider = map.get(provider.getClass());743744if (provider == oprovider) {745map.remove(provider.getClass());746accMap.remove(provider.getClass());747poset.remove(provider);748if (provider instanceof RegisterableService) {749RegisterableService rs = (RegisterableService)provider;750rs.onDeregistration(registry, category);751}752753return true;754}755return false;756}757758public boolean contains(Object provider) {759Object oprovider = map.get(provider.getClass());760return oprovider == provider;761}762763public boolean setOrdering(Object firstProvider,764Object secondProvider) {765return poset.setOrdering(firstProvider, secondProvider);766}767768public boolean unsetOrdering(Object firstProvider,769Object secondProvider) {770return poset.unsetOrdering(firstProvider, secondProvider);771}772773public Iterator getServiceProviders(boolean useOrdering) {774if (useOrdering) {775return poset.iterator();776} else {777return map.values().iterator();778}779}780781public <T> T getServiceProviderByClass(Class<T> providerClass) {782return (T)map.get(providerClass);783}784785public void clear() {786Iterator iter = map.values().iterator();787while (iter.hasNext()) {788Object provider = iter.next();789iter.remove();790791if (provider instanceof RegisterableService) {792RegisterableService rs = (RegisterableService)provider;793AccessControlContext acc = accMap.get(provider.getClass());794if (acc != null || System.getSecurityManager() == null) {795AccessController.doPrivileged((PrivilegedAction<Void>) () -> {796rs.onDeregistration(registry, category);797return null;798}, acc);799}800}801}802poset.clear();803accMap.clear();804}805806public void finalize() {807clear();808}809}810811812/**813* A class for wrapping <code>Iterators</code> with a filter function.814* This provides an iterator for a subset without duplication.815*/816class FilterIterator<T> implements Iterator<T> {817818private Iterator<T> iter;819private ServiceRegistry.Filter filter;820821private T next = null;822823public FilterIterator(Iterator<T> iter,824ServiceRegistry.Filter filter) {825this.iter = iter;826this.filter = filter;827advance();828}829830private void advance() {831while (iter.hasNext()) {832T elt = iter.next();833if (filter.filter(elt)) {834next = elt;835return;836}837}838839next = null;840}841842public boolean hasNext() {843return next != null;844}845846public T next() {847if (next == null) {848throw new NoSuchElementException();849}850T o = next;851advance();852return o;853}854855public void remove() {856throw new UnsupportedOperationException();857}858}859860861