org.glassfish.jersey.internal.ServiceFinder Maven / Gradle / Ivy
Show all versions of ehcache Show documentation
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright (c) 2010-2014 Oracle and/or its affiliates. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common Development
* and Distribution License("CDDL") (collectively, the "License"). You
* may not use this file except in compliance with the License. You can
* obtain a copy of the License at
* http://glassfish.java.net/public/CDDL+GPL_1_1.html
* or packager/legal/LICENSE.txt. See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each
* file and include the License file at packager/legal/LICENSE.txt.
*
* GPL Classpath Exception:
* Oracle designates this particular file as subject to the "Classpath"
* exception as provided by Oracle in the GPL Version 2 section of the License
* file that accompanied this code.
*
* Modifications:
* If applicable, add the following below the License Header, with the fields
* enclosed by brackets [] replaced by your own identifying information:
* "Portions Copyright [year] [name of copyright owner]"
*
* Contributor(s):
* If you wish your version of this file to be governed by only the CDDL or
* only the GPL Version 2, indicate your decision by adding "[Contributor]
* elects to include this software in this distribution under the [CDDL or GPL
* Version 2] license." If you don't indicate a single choice of license, a
* recipient has the option to distribute your version of this file under
* either the CDDL, the GPL Version 2 or to extend the choice of license to
* its licensees as provided above. However, if you add GPL Version 2 code
* and therefore, elected the GPL Version 2 license, then the option applies
* only if the new code is made subject to such option by the copyright
* holder.
*/
package org.glassfish.jersey.internal;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Array;
import java.lang.reflect.ReflectPermission;
import java.net.URL;
import java.net.URLConnection;
import java.security.AccessController;
import java.security.PrivilegedActionException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.TreeSet;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.glassfish.jersey.internal.util.ReflectionHelper;
/**
* A simple service-provider lookup mechanism. A service is a
* well-known set of interfaces and (usually abstract) classes. A service
* provider is a specific implementation of a service. The classes in a
* provider typically implement the interfaces and subclass the classes defined
* in the service itself. Service providers may be installed in an
* implementation of the Java platform in the form of extensions, that is, jar
* files placed into any of the usual extension directories. Providers may
* also be made available by adding them to the applet or application class
* path or by some other platform-specific means.
*
* In this lookup mechanism a service is represented by an interface or an
* abstract class. (A concrete class may be used, but this is not
* recommended.) A provider of a given service contains one or more concrete
* classes that extend this service class with data and code specific to
* the provider. This provider class will typically not be the entire
* provider itself but rather a proxy that contains enough information to
* decide whether the provider is able to satisfy a particular request together
* with code that can create the actual provider on demand. The details of
* provider classes tend to be highly service-specific; no single class or
* interface could possibly unify them, so no such class has been defined. The
* only requirement enforced here is that provider classes must have a
* zero-argument constructor so that they may be instantiated during lookup.
*
* The default service provider registration/lookup mechanism based
* on META-INF/services files is described below.
* For environments, where the basic mechanism is not suitable, clients
* can enforce a different approach by setting their custom ServiceIteratorProvider
* by calling setIteratorProvider. The call must be made prior to any lookup attempts.
*
* A service provider identifies itself by placing a provider-configuration
* file in the resource directory META-INF/services. The file's name
* should consist of the fully-qualified name of the abstract service class.
* The file should contain a list of fully-qualified concrete provider-class
* names, one per line. Space and tab characters surrounding each name, as
* well as blank lines, are ignored. The comment character is '#'
* (0x23); on each line all characters following the first comment
* character are ignored. The file must be encoded in UTF-8.
*
* If a particular concrete provider class is named in more than one
* configuration file, or is named in the same configuration file more than
* once, then the duplicates will be ignored. The configuration file naming a
* particular provider need not be in the same jar file or other distribution
* unit as the provider itself. The provider must be accessible from the same
* class loader that was initially queried to locate the configuration file;
* note that this is not necessarily the class loader that found the file.
*
* Example: Suppose we have a service class named
* java.io.spi.CharCodec. It has two abstract methods:
*
*
* public abstract CharEncoder getEncoder(String encodingName);
* public abstract CharDecoder getDecoder(String encodingName);
*
*
* Each method returns an appropriate object or null if it cannot
* translate the given encoding. Typical CharCodec providers will
* support more than one encoding.
*
* If sun.io.StandardCodec is a provider of the CharCodec
* service then its jar file would contain the file
* META-INF/services/java.io.spi.CharCodec. This file would contain
* the single line:
*
*
* sun.io.StandardCodec # Standard codecs for the platform
*
*
* To locate an codec for a given encoding name, the internal I/O code would
* do something like this:
*
*
* CharEncoder getEncoder(String encodingName) {
* for( CharCodec cc : ServiceFinder.find(CharCodec.class) ) {
* CharEncoder ce = cc.getEncoder(encodingName);
* if (ce != null)
* return ce;
* }
* return null;
* }
*
*
* The provider-lookup mechanism always executes in the security context of the
* caller. Trusted system code should typically invoke the methods in this
* class from within a privileged security context.
*
* @param the type of the service instance.
* @author Mark Reinhold
* @author Jakub Podlesak
* @author Marek Potociar
*/
public final class ServiceFinder implements Iterable {
private static final Logger LOGGER = Logger.getLogger(ServiceFinder.class.getName());
private static final String PREFIX = "META-INF/services/";
private final Class serviceClass;
private final String serviceName;
private final ClassLoader classLoader;
private final boolean ignoreOnClassNotFound;
static {
final OsgiRegistry osgiRegistry = ReflectionHelper.getOsgiRegistryInstance();
if (osgiRegistry != null) {
LOGGER.log(Level.CONFIG, "Running in an OSGi environment");
osgiRegistry.hookUp();
} else {
LOGGER.log(Level.CONFIG, "Running in a non-OSGi environment");
}
}
private static Enumeration getResources(ClassLoader loader, String name) throws IOException {
if (loader == null) {
return getResources(name);
} else {
final Enumeration resources = loader.getResources(name);
if ((resources != null) && resources.hasMoreElements()) {
return resources;
} else {
return getResources(name);
}
}
}
private static Enumeration getResources(String name) throws IOException {
if (ServiceFinder.class.getClassLoader() != null) {
return ServiceFinder.class.getClassLoader().getResources(name);
} else {
return ClassLoader.getSystemResources(name);
}
}
private static ClassLoader _getContextClassLoader() {
return AccessController.doPrivileged(ReflectionHelper.getContextClassLoaderPA());
}
/**
* Locates and incrementally instantiates the available providers of a
* given service using the given class loader.
*
* This method transforms the name of the given service class into a
* provider-configuration filename as described above and then uses the
* getResources method of the given class loader to find all
* available files with that name. These files are then read and parsed to
* produce a list of provider-class names. The iterator that is returned
* uses the given class loader to lookup and then instantiate each element
* of the list.
*
* Because it is possible for extensions to be installed into a running
* Java virtual machine, this method may return different results each time
* it is invoked.
* @param service The service's abstract service class
* @param loader The class loader to be used to load provider-configuration files
* and instantiate provider classes, or null if the system
* class loader (or, failing that the bootstrap class loader) is to
* be used
* @throws ServiceConfigurationError If a provider-configuration file violates the specified format
* or names a provider class that cannot be found and instantiated
* @see #find(Class)
* @param the type of the service instance.
* @return the service finder
*/
public static ServiceFinder find(Class service, ClassLoader loader)
throws ServiceConfigurationError {
return find(service,
loader,
false);
}
/**
* Locates and incrementally instantiates the available providers of a
* given service using the given class loader.
*
* This method transforms the name of the given service class into a
* provider-configuration filename as described above and then uses the
* getResources method of the given class loader to find all
* available files with that name. These files are then read and parsed to
* produce a list of provider-class names. The iterator that is returned
* uses the given class loader to lookup and then instantiate each element
* of the list.
*
* Because it is possible for extensions to be installed into a running
* Java virtual machine, this method may return different results each time
* it is invoked.
* @param service The service's abstract service class
* @param loader The class loader to be used to load provider-configuration files
* and instantiate provider classes, or null if the system
* class loader (or, failing that the bootstrap class loader) is to
* be used
* @param ignoreOnClassNotFound If a provider cannot be loaded by the class loader
* then move on to the next available provider.
* @throws ServiceConfigurationError If a provider-configuration file violates the specified format
* or names a provider class that cannot be found and instantiated
* @see #find(Class)
* @param the type of the service instance.
* @return the service finder
*/
public static ServiceFinder find(Class service,
ClassLoader loader,
boolean ignoreOnClassNotFound) throws ServiceConfigurationError {
return new ServiceFinder(service,
loader,
ignoreOnClassNotFound);
}
/**
* Locates and incrementally instantiates the available providers of a
* given service using the context class loader. This convenience method
* is equivalent to
*
*
* ClassLoader cl = Thread.currentThread().getContextClassLoader();
* return Service.providers(service, cl, false);
*
* @param service The service's abstract service class
* @throws ServiceConfigurationError If a provider-configuration file violates the specified format
* or names a provider class that cannot be found and instantiated
* @see #find(Class, ClassLoader)
* @param the type of the service instance.
* @return the service finder
*/
public static ServiceFinder find(Class service)
throws ServiceConfigurationError {
return find(service,
_getContextClassLoader(),
false);
}
/**
* Locates and incrementally instantiates the available providers of a
* given service using the context class loader. This convenience method
* is equivalent to
*
*
* ClassLoader cl = Thread.currentThread().getContextClassLoader();
* boolean ingore = ...
* return Service.providers(service, cl, ignore);
*
* @param service The service's abstract service class
* @param ignoreOnClassNotFound If a provider cannot be loaded by the class loader
* then move on to the next available provider.
* @throws ServiceConfigurationError If a provider-configuration file violates the specified format
* or names a provider class that cannot be found and instantiated
* @see #find(Class, ClassLoader)
* @param the type of the service instance.
* @return the service finder
*/
public static ServiceFinder find(Class service,
boolean ignoreOnClassNotFound) throws ServiceConfigurationError {
return find(service,
_getContextClassLoader(),
ignoreOnClassNotFound);
}
/**
* Locates and incrementally instantiates the available classes of a given
* service file using the context class loader.
*
* @param serviceName the service name correspond to a file in
* META-INF/services that contains a list of fully qualified class
* names
* @throws ServiceConfigurationError If a service file violates the specified format
* or names a provider class that cannot be found and instantiated
* @return the service finder
*/
public static ServiceFinder> find(String serviceName) throws ServiceConfigurationError {
return new ServiceFinder