Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
   *
   * Copyright (c) 2010-2012 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 com.sun.jersey.spi.service;
 
 import java.net.URL;
 import java.util.List;
 import java.util.Set;
 
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.

Parameters:
<T> the type of the service instance.
Author(s):
Mark Reinhold (mark.reinhold at oracle.com)
Jakub Podlesak (jakub.podlesak at oracle.com)
Michal Gajdos (michal.gajdos at oracle.com)
public final class ServiceFinder<T> implements Iterable<T> {
    private static final Logger LOGGER = Logger.getLogger(ServiceFinder.class.getName());
    private static final String MODULE_VERSION = "META-INF/jersey-module-version";
    private static final String PREFIX = "META-INF/services/";
    private static final String MODULE_VERSION_VALUE = getModuleVersion();
    private static final Set<StringMODULES_BLACKLIST;
    private final Class<T> serviceClass;
    private final String serviceName;
    private final ClassLoader classLoader;
    private final boolean ignoreOnClassNotFound;
    static {
         = new HashSet<String>() {{
            // Jersey
            add("jersey-client");
            add("jersey-core");
            add("jersey-gf-server");
            add("jersey-gf-servlet");
            add("jersey-gf-statsproviders");
            add("jersey-grizzly");
            add("jersey-json");
            add("jersey-moxy");
            add("jersey-multipart");
            add("jersey-server");
            add("jersey-servlet");
            add("jersey-statsproviders");
            // GF
            add("glassfish-embedded");
        }};
        final OsgiRegistry osgiRegistry = ReflectionHelper.getOsgiRegistryInstance();
        if (osgiRegistry != null) {
            .log(."Running in an OSGi environment");
        } else {
            .log(."Running in a non-OSGi environment");
        }
    }
    private static String getModuleVersion() {
        try {
            String resource = ServiceFinder.class.getName().replace(".""/") + ".class";
            URL url = getResource(ServiceFinder.class.getClassLoader(), resource);
            if (url == null) {
                .log(."Error getting " + ServiceFinder.class.getName() + " class as a resource");
                return null;
            }
            return getJerseyModuleVersion(ServiceFinder.class.getName(), url);
        } catch(IOException ioe) {
            .log(."Error loading META-INF/jersey-module-version associated with " + ServiceFinder.class.getName(), ioe);
            return null;
        }
    }
    private static Enumeration<URLfilterServiceURLsWithVersion(String serviceNameEnumeration<URLserviceUrls) {
        if ( == null || !serviceUrls.hasMoreElements()) {
            return serviceUrls;
        }
        final List<URLurls = Collections.list(serviceUrls);
        final ListIterator<URLli = urls.listIterator();
        while (li.hasNext()) {
            final URL url = li.next();
            if (isServiceInBlacklistedModule(url)) {
                String jerseyModuleVersion = getJerseyModuleVersion(serviceNameurl);
                if (jerseyModuleVersion != null) {
                    if (!.equals(jerseyModuleVersion)) {
                        li.remove();
                    }
                }
            }
        }
        return Collections.enumeration(urls);
    }
    private static boolean isServiceInBlacklistedModule(final URL serviceUrl) {
        final String service = serviceUrl.toString();
        for (final String module : ) {
            if (service.contains(module)) {
                return true;
            }
        }
        return false;
    }
    private static String getJerseyModuleVersion(final String serviceNamefinal URL serviceUrl) {
        try {
            final String url = serviceUrl.toString();
            final String resource = url.endsWith("class") ? serviceName.replace(".""/") + ".class" : serviceName;
            final URL moduleVersionURL = new URL(url.replace(resource));
            return new BufferedReader(new InputStreamReader(moduleVersionURL.openStream())).readLine();
        } catch (IOException ioe) {
            .log(."Error loading META-INF/jersey-module-version associated with " + ServiceFinder.class.getName());
            return null;
        }
    }
    private static URL getResource(ClassLoader loaderString namethrows IOException {
        if (loader == null)
            return getResource(name);
        else {
            final URL resource = loader.getResource(name);
            if (resource != null) {
                return resource;
            } else {
                return getResource(name);
            }
        }
    }
    private static URL getResource(String namethrows IOException {
        if (ServiceFinder.class.getClassLoader() != null)
            return ServiceFinder.class.getClassLoader().getResource(name);
        else
            return ClassLoader.getSystemResource(name);
    }
    private static Enumeration<URLgetResources(ClassLoader loaderString namethrows IOException {
        if (loader == null) {
            return getResources(name);
        } else {
            final Enumeration<URLresources = loader.getResources(name);
            if ((resources != null) && resources.hasMoreElements()) {
                return resources;
            } else {
                return getResources(name);
            }
        }
    }
    private static Enumeration<URLgetResources(String namethrows IOException {
        if (ServiceFinder.class.getClassLoader() != null)
            return ServiceFinder.class.getClassLoader().getResources(name);
        else
            return ClassLoader.getSystemResources(name);
    }

    
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.

Parameters:
service The service's abstract service class
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
<T> the type of the service instance.
Returns:
the service finder
Throws:
ServiceConfigurationError If a provider-configuration file violates the specified format or names a provider class that cannot be found and instantiated
See also:
find(java.lang.Class)
    public static <T> ServiceFinder<T> find(Class<T> serviceClassLoader 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.

Parameters:
service The service's abstract service class
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
ignoreOnClassNotFound If a provider cannot be loaded by the class loader then move on to the next available provider.
<T> the type of the service instance.
Returns:
the service finder
Throws:
ServiceConfigurationError If a provider-configuration file violates the specified format or names a provider class that cannot be found and instantiated
See also:
find(java.lang.Class)
    public static <T> ServiceFinder<T> find(Class<T> service,
                                            ClassLoader loader,
                                            boolean ignoreOnClassNotFoundthrows ServiceConfigurationError {
        return new ServiceFinder<T>(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);
 

Parameters:
service The service's abstract service class
<T> the type of the service instance.
Returns:
the service finder
Throws:
ServiceConfigurationError If a provider-configuration file violates the specified format or names a provider class that cannot be found and instantiated
See also:
find(java.lang.Class,java.lang.ClassLoader)
    public static <T> ServiceFinder<T> find(Class<T> service)
            throws ServiceConfigurationError {
        return find(service,
                Thread.currentThread().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);
 

Parameters:
service The service's abstract service class
ignoreOnClassNotFound If a provider cannot be loaded by the class loader then move on to the next available provider.
<T> the type of the service instance.
Returns:
the service finder
Throws:
ServiceConfigurationError If a provider-configuration file violates the specified format or names a provider class that cannot be found and instantiated
See also:
find(java.lang.Class,java.lang.ClassLoader)
    public static <T> ServiceFinder<T> find(Class<T> service,
                                            boolean ignoreOnClassNotFoundthrows ServiceConfigurationError {
        return find(service,
                Thread.currentThread().getContextClassLoader(),
                ignoreOnClassNotFound);
    }

    
Locates and incrementally instantiates the available classes of a given service file using the context class loader.

Parameters:
serviceName the service name correspond to a file in META-INF/services that contains a list of fully qualified class names
Returns:
the service finder
Throws:
ServiceConfigurationError If a service file violates the specified format or names a provider class that cannot be found and instantiated
    public static ServiceFinder<?> find(String serviceNamethrows ServiceConfigurationError {
        return new ServiceFinder(Object.classserviceName, Thread.currentThread().getContextClassLoader(), false);
    }

    
Register the service iterator provider to iterate on provider instances or classes.

The default implementation registered, ServiceFinder.DefaultServiceIteratorProvider, looks up provider classes in META-INF/service files.

This method must be called prior to any attempts to obtain provider instances or classes.

Parameters:
sip the service iterator provider.
Throws:
java.lang.SecurityException if the provider cannot be registered.
    public static void setIteratorProvider(ServiceIteratorProvider sipthrows SecurityException {
        ServiceIteratorProvider.setInstance(sip);
    }
    private ServiceFinder(
            Class<T> service,
            ClassLoader loader,
            boolean ignoreOnClassNotFound) {
        this(serviceservice.getName(), loaderignoreOnClassNotFound);
    }
    private ServiceFinder(
            Class<T> service,
            String serviceName,
            ClassLoader loader,
            boolean ignoreOnClassNotFound) {
        this. = service;
        this. = serviceName;
        this. = loader;
        this. = ignoreOnClassNotFound;
    }

    
Returns discovered objects incrementally.

Returns:
An Iterator that yields provider objects for the given service, in some arbitrary order. The iterator will throw a ServiceConfigurationError if a provider-configuration file violates the specified format or if a provider class cannot be found and instantiated.
    public Iterator<T> iterator() {
        return ServiceIteratorProvider.getInstance().createIterator();
    }

    
Returns discovered classes incrementally.

Returns:
An Iterator that yields provider classes for the given service, in some arbitrary order. The iterator will throw a ServiceConfigurationError if a provider-configuration file violates the specified format or if a provider class cannot be found.
    private Iterator<Class<T>> classIterator() {
        return ServiceIteratorProvider.getInstance().createClassIterator();
    }

    
Returns discovered objects all at once.

Returns:
can be empty but never null.
Throws:
ServiceConfigurationError If a provider-configuration file violates the specified format or names a provider class that cannot be found and instantiated
    @SuppressWarnings("unchecked")
    public T[] toArray() throws ServiceConfigurationError {
        List<T> result = new ArrayList<T>();
        for (T t : this) {
            result.add(t);
        }
        return result.toArray((T[])Array.newInstance(,result.size()));
    }

    
Returns discovered classes all at once.

Returns:
can be empty but never null.
Throws:
ServiceConfigurationError If a provider-configuration file violates the specified format or names a provider class that cannot be found
    @SuppressWarnings("unchecked")
    public Class<T>[] toClassArray() throws ServiceConfigurationError {
        List<Class<T>> result = new ArrayList<Class<T>>();
        Iterator<Class<T>> i = classIterator();
        while (i.hasNext())
            result.add(i.next());
        return result.toArray((Class<T>[])Array.newInstance(Class.class,result.size()));
    }
    private static void fail(String serviceNameString msgThrowable cause)
            throws ServiceConfigurationError {
        ServiceConfigurationError sce
                = new ServiceConfigurationError(serviceName + ": " + msg);
        sce.initCause(cause);
        throw sce;
    }
    private static void fail(String serviceNameString msg)
            throws ServiceConfigurationError {
        throw new ServiceConfigurationError(serviceName + ": " + msg);
    }
    private static void fail(String serviceNameURL uint lineString msg)
            throws ServiceConfigurationError {
        fail(serviceNameu + ":" + line + ": " + msg);
    }

    
Parse a single line from the given configuration file, adding the name on the line to both the names list and the returned set iff the name is not already a member of the returned set.
    private static int parseLine(String serviceNameURL uBufferedReader rint lc,
                                 List<StringnamesSet<Stringreturned)
            throws IOExceptionServiceConfigurationError {
        String ln = r.readLine();
        if (ln == null) {
            return -1;
        }
        int ci = ln.indexOf('#');
        if (ci >= 0) ln = ln.substring(0, ci);
        ln = ln.trim();
        int n = ln.length();
        if (n != 0) {
            if ((ln.indexOf(' ') >= 0) || (ln.indexOf('\t') >= 0))
                fail(serviceNameulc, SpiMessages.ILLEGAL_CONFIG_SYNTAX());
            int cp = ln.codePointAt(0);
            if (!Character.isJavaIdentifierStart(cp))
                fail(serviceNameulc, SpiMessages.ILLEGAL_PROVIDER_CLASS_NAME(ln));
            for (int i = Character.charCount(cp); i < ni += Character.charCount(cp)) {
                cp = ln.codePointAt(i);
                if (!Character.isJavaIdentifierPart(cp) && (cp != '.'))
                    fail(serviceNameulc, SpiMessages.ILLEGAL_PROVIDER_CLASS_NAME(ln));
            }
            if (!returned.contains(ln)) {
                names.add(ln);
                returned.add(ln);
            }
        }
        return lc + 1;
    }

    
Parse the content of the given URL as a provider-configuration file.

Parameters:
serviceName The service class for which providers are being sought; used to construct error detail strings
u The URL naming the configuration file to be parsed
returned A Set containing the names of provider classes that have already been returned. This set will be updated to contain the names that will be yielded from the returned Iterator.
Returns:
A (possibly empty) Iterator that will yield the provider-class names in the given configuration file that are not yet members of the returned set
Throws:
ServiceConfigurationError If an I/O error occurs while reading from the given URL, or if a configuration-file format error is detected
    @SuppressWarnings({"StatementWithEmptyBody"})
    private static Iterator<Stringparse(String serviceNameURL uSet<Stringreturned)
            throws ServiceConfigurationError {
        InputStream in = null;
        BufferedReader r = null;
        ArrayList<Stringnames = new ArrayList<String>();
        try {
            URLConnection uConn = u.openConnection();
            uConn.setUseCaches(false);
            in = uConn.getInputStream();
            r = new BufferedReader(new InputStreamReader(in"utf-8"));
            int lc = 1;
            while ((lc = parseLine(serviceNameurlcnamesreturned)) >= 0) ;
        } catch (IOException x) {
            fail(serviceName": " + x);
        } finally {
            try {
                if (r != nullr.close();
                if (in != nullin.close();
            } catch (IOException y) {
                fail(serviceName": " + y);
            }
        }
        return names.iterator();
    }
    private static class AbstractLazyIterator<T> {
        final Class<T> service;
        final String serviceName;
        final ClassLoader loader;
        final boolean ignoreOnClassNotFound;
        Enumeration<URLconfigs = null;
        Iterator<Stringpending = null;
        Set<Stringreturned = new TreeSet<String>();
        String nextName = null;
        private AbstractLazyIterator(
                Class<T> service,
                String serviceName,
                ClassLoader loader,
                boolean ignoreOnClassNotFound) {
            this. = service;
            this. = serviceName;
            this. = loader;
            this. = ignoreOnClassNotFound;
        }
        protected final void setConfigs() {
            if ( == null) {
                try {
                    final String fullName =  + ;
                     = filterServiceURLsWithVersion(fullNamegetResources(fullName));
                } catch (IOException x) {
                    fail(": " + x);
                }
            }
        }
        public boolean hasNext() throws ServiceConfigurationError {
            if ( != null) {
                return true;
            }
            setConfigs();
            while ( == null) {
                while (( == null) || !.hasNext()) {
                    if (!.hasMoreElements()) {
                        return false;
                    }
                     = parse(.nextElement(), );
                }
                 = .next();
                if () {
                    try {
                        ReflectionHelper.classForNameWithException();
                    } catch (ClassNotFoundException ex) {
                        // Provider implementation not found
                        if(.isLoggable(.)) {
                            .log(.,
                                    SpiMessages.PROVIDER_NOT_FOUND());
                        }
                         = null;
                    } catch (NoClassDefFoundError ex) {
                        // Dependent class of provider not found
                        if(.isLoggable(.)) {
                            // This assumes that ex.getLocalizedMessage() returns
                            // the name of a dependent class that is not found
                            .log(. ,
                                    SpiMessages.DEPENDENT_CLASS_OF_PROVIDER_NOT_FOUND(
                                            ex.getLocalizedMessage(), ));
                        }
                         = null;
                    } catch(ClassFormatError ex) {
                        // Dependent class of provider not found
                        if(.isLoggable(.)) {
                            .log(. ,
                                    SpiMessages.DEPENDENT_CLASS_OF_PROVIDER_FORMAT_ERROR(
                                            ex.getLocalizedMessage(), ));
                        }
                         = null;
                    }
                }
            }
            return true;
        }
        public void remove() {
            throw new UnsupportedOperationException();
        }
    }
    private static final class LazyClassIterator<T> extends AbstractLazyIterator<T>
            implements Iterator<Class<T>> {
        private LazyClassIterator(
                Class<T> service,
                String serviceName,
                ClassLoader loader,
                boolean ignoreOnClassNotFound) {
            super(serviceserviceNameloaderignoreOnClassNotFound);
        }
        @SuppressWarnings("unchecked")
        public Class<T> next() {
            if (!hasNext()) {
                throw new NoSuchElementException();
            }
            String cn = ;
             = null;
            try {
                return (Class<T>)ReflectionHelper.classForNameWithException(cn);
            } catch (ClassNotFoundException ex) {
                fail(,
                        SpiMessages.PROVIDER_NOT_FOUND(cn));
            } catch (NoClassDefFoundError ex) {
                fail(,
                        SpiMessages.DEPENDENT_CLASS_OF_PROVIDER_NOT_FOUND(
                                ex.getLocalizedMessage(), cn));
            } catch (ClassFormatError ex) {
                fail(,
                        SpiMessages.DEPENDENT_CLASS_OF_PROVIDER_FORMAT_ERROR(
                                ex.getLocalizedMessage(), cn));
            } catch (Exception x) {
                fail(,
                        SpiMessages.PROVIDER_CLASS_COULD_NOT_BE_LOADED(cnx.getLocalizedMessage()),
                        x);
            }
            return null;    /* This cannot happen */
        }
    }
    private static final class LazyObjectIterator<T> extends AbstractLazyIterator<T>
            implements Iterator<T> {
        private T t;
        private LazyObjectIterator(
                Class<T> service,
                String serviceName,
                ClassLoader loader,
                boolean ignoreOnClassNotFound) {
            super(serviceserviceNameloaderignoreOnClassNotFound);
        }
        @Override
        public boolean hasNext() throws ServiceConfigurationError {
            if ( != null) {
                return true;
            }
            setConfigs();
            while ( == null) {
                while (( == null) || !.hasNext()) {
                    if (!.hasMoreElements()) {
                        return false;
                    }
                     = parse(.nextElement(), );
                }
                 = .next();
                try {
                     = .cast(ReflectionHelper.classForNameWithException().newInstance());
                } catch (ClassNotFoundException ex) {
                    if () {
                        // Provider implementation not found
                        if(.isLoggable(.)) {
                            .log(.,
                                    SpiMessages.PROVIDER_NOT_FOUND());
                        }
                         = null;
                    } else
                        fail(,
                                SpiMessages.PROVIDER_NOT_FOUND());
                } catch (NoClassDefFoundError ex) {
                    // Dependent class of provider not found
                    if () {
                        if(.isLoggable(.)) {
                            // This assumes that ex.getLocalizedMessage() returns
                            // the name of a dependent class that is not found
                            .log(. ,
                                    SpiMessages.DEPENDENT_CLASS_OF_PROVIDER_NOT_FOUND(
                                            ex.getLocalizedMessage(), ));
                        }
                         = null;
                    } else
                        fail(,
                                SpiMessages.DEPENDENT_CLASS_OF_PROVIDER_NOT_FOUND(ex.getLocalizedMessage(), ),
                                ex);
                } catch (ClassFormatError ex) {
                    // Dependent class of provider not found
                    if () {
                        if(.isLoggable(.)) {
                            .log(. ,
                                    SpiMessages.DEPENDENT_CLASS_OF_PROVIDER_FORMAT_ERROR(
                                            ex.getLocalizedMessage(), ));
                        }
                         = null;
                    } else
                        fail(,
                                SpiMessages.DEPENDENT_CLASS_OF_PROVIDER_FORMAT_ERROR(ex.getLocalizedMessage(), ),
                                ex);
                } catch(Exception ex) {
                    fail(,
                            SpiMessages.PROVIDER_COULD_NOT_BE_CREATED(ex.getLocalizedMessage()),
                            ex);
                }
            }
            return true;
        }
        public T next() {
            if (!hasNext()) {
                throw new NoSuchElementException();
            }
            String cn = ;
             = null;
            return ;
        }
    }

    
Supports iteration of provider instances or classes.

The default implementation looks up provider classes from META-INF/services files, see ServiceFinder.DefaultServiceIteratorProvider. This implementation may be overridden by invoking ServiceFinder.setIteratorProvider(com.sun.jersey.spi.service.ServiceFinder.ServiceIteratorProvider).

Parameters:
<T> the type of service.
    public static abstract class ServiceIteratorProvider<T> {
        private static volatile ServiceIteratorProvider sip;
        private static ServiceIteratorProvider getInstance() {
            // Double-check idiom for lazy initialization of fields.
            ServiceIteratorProvider result = ;
            if (result == null) { // First check (no locking)
                synchronized (ServiceIteratorProvider.class) {
                    result = ;
                    if (result == null) { // Second check (with locking)
                         = result = new DefaultServiceIteratorProvider();
                    }
                }
            }
            return result;
        }
        private static void setInstance(ServiceIteratorProvider sipthrows SecurityException {
            SecurityManager security = System.getSecurityManager();
            if (security != null) {
                ReflectPermission rp = new ReflectPermission("suppressAccessChecks");
                security.checkPermission(rp);
            }
            synchronized (ServiceIteratorProvider.class) {
                . = sip;
            }
        }

        
Iterate over provider instances of a service.

Parameters:
service the service class.
serviceName the service name.
loader the class loader to utilize when loading provider classes.
ignoreOnClassNotFound, if true ignore an instance if the corresponding provider class if cannot be found, otherwise throw a java.lang.ClassNotFoundException.
Returns:
the provider instance iterator.
        public abstract Iterator<T> createIterator(Class<T> service,
                                                   String serviceNameClassLoader loaderboolean ignoreOnClassNotFound);

        
Iterate over provider classes of a service.

Parameters:
service the service class.
serviceName the service name.
loader the class loader to utilize when loading provider classes.
ignoreOnClassNotFound, if true ignore the provider class if cannot be found, otherwise throw a java.lang.ClassNotFoundException.
Returns:
the provider class iterator.
        public abstract Iterator<Class<T>> createClassIterator(Class<T> service,
                                                               String serviceNameClassLoader loaderboolean ignoreOnClassNotFound);
    }


    
The default service iterator provider that looks up provider classes in META-INF/services files.

This class may utilized if a ServiceFinder.ServiceIteratorProvider needs to reuse the default implementation.

Parameters:
<T> the type of service.
    public static final class DefaultServiceIteratorProvider<T> extends ServiceIteratorProvider<T> {
        @Override
        public Iterator<T> createIterator(Class<T> serviceString serviceName,
                                          ClassLoader loaderboolean ignoreOnClassNotFound) {
            return new LazyObjectIterator(serviceserviceNameloaderignoreOnClassNotFound);
        }
        @Override
        public Iterator<Class<T>> createClassIterator(Class<T> serviceString serviceName,
                                                      ClassLoader loaderboolean ignoreOnClassNotFound) {
            return new LazyClassIterator(serviceserviceNameloaderignoreOnClassNotFound);
        }
    }
New to GrepCode? Check out our FAQ X