rt/emul/compact/src/main/java/java/util/ServiceLoader.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Tue, 26 Feb 2013 16:54:16 +0100
changeset 772 d382dacfd73f
parent 565 emul/compact/src/main/java/java/util/ServiceLoader.java@4d76e93fd886
permissions -rw-r--r--
Moving modules around so the runtime is under one master pom and can be built without building other modules that are in the repository
jaroslav@557
     1
/*
jaroslav@557
     2
 * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
jaroslav@557
     3
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
jaroslav@557
     4
 *
jaroslav@557
     5
 * This code is free software; you can redistribute it and/or modify it
jaroslav@557
     6
 * under the terms of the GNU General Public License version 2 only, as
jaroslav@557
     7
 * published by the Free Software Foundation.  Oracle designates this
jaroslav@557
     8
 * particular file as subject to the "Classpath" exception as provided
jaroslav@557
     9
 * by Oracle in the LICENSE file that accompanied this code.
jaroslav@557
    10
 *
jaroslav@557
    11
 * This code is distributed in the hope that it will be useful, but WITHOUT
jaroslav@557
    12
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
jaroslav@557
    13
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
jaroslav@557
    14
 * version 2 for more details (a copy is included in the LICENSE file that
jaroslav@557
    15
 * accompanied this code).
jaroslav@557
    16
 *
jaroslav@557
    17
 * You should have received a copy of the GNU General Public License version
jaroslav@557
    18
 * 2 along with this work; if not, write to the Free Software Foundation,
jaroslav@557
    19
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
jaroslav@557
    20
 *
jaroslav@557
    21
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
jaroslav@557
    22
 * or visit www.oracle.com if you need additional information or have any
jaroslav@557
    23
 * questions.
jaroslav@557
    24
 */
jaroslav@557
    25
jaroslav@557
    26
package java.util;
jaroslav@557
    27
jaroslav@557
    28
import java.io.BufferedReader;
jaroslav@557
    29
import java.io.IOException;
jaroslav@557
    30
import java.io.InputStream;
jaroslav@557
    31
import java.io.InputStreamReader;
jaroslav@557
    32
import java.net.URL;
jaroslav@557
    33
import java.util.ArrayList;
jaroslav@557
    34
import java.util.Enumeration;
jaroslav@557
    35
import java.util.Iterator;
jaroslav@557
    36
import java.util.List;
jaroslav@557
    37
import java.util.NoSuchElementException;
jaroslav@557
    38
jaroslav@557
    39
jaroslav@557
    40
/**
jaroslav@557
    41
 * A simple service-provider loading facility.
jaroslav@557
    42
 *
jaroslav@557
    43
 * <p> A <i>service</i> is a well-known set of interfaces and (usually
jaroslav@557
    44
 * abstract) classes.  A <i>service provider</i> is a specific implementation
jaroslav@557
    45
 * of a service.  The classes in a provider typically implement the interfaces
jaroslav@557
    46
 * and subclass the classes defined in the service itself.  Service providers
jaroslav@557
    47
 * can be installed in an implementation of the Java platform in the form of
jaroslav@557
    48
 * extensions, that is, jar files placed into any of the usual extension
jaroslav@557
    49
 * directories.  Providers can also be made available by adding them to the
jaroslav@557
    50
 * application's class path or by some other platform-specific means.
jaroslav@557
    51
 *
jaroslav@557
    52
 * <p> For the purpose of loading, a service is represented by a single type,
jaroslav@557
    53
 * that is, a single interface or abstract class.  (A concrete class can be
jaroslav@557
    54
 * used, but this is not recommended.)  A provider of a given service contains
jaroslav@557
    55
 * one or more concrete classes that extend this <i>service type</i> with data
jaroslav@557
    56
 * and code specific to the provider.  The <i>provider class</i> is typically
jaroslav@557
    57
 * not the entire provider itself but rather a proxy which contains enough
jaroslav@557
    58
 * information to decide whether the provider is able to satisfy a particular
jaroslav@557
    59
 * request together with code that can create the actual provider on demand.
jaroslav@557
    60
 * The details of provider classes tend to be highly service-specific; no
jaroslav@557
    61
 * single class or interface could possibly unify them, so no such type is
jaroslav@557
    62
 * defined here.  The only requirement enforced by this facility is that
jaroslav@557
    63
 * provider classes must have a zero-argument constructor so that they can be
jaroslav@557
    64
 * instantiated during loading.
jaroslav@557
    65
 *
jaroslav@557
    66
 * <p><a name="format"> A service provider is identified by placing a
jaroslav@557
    67
 * <i>provider-configuration file</i> in the resource directory
jaroslav@557
    68
 * <tt>META-INF/services</tt>.  The file's name is the fully-qualified <a
jaroslav@557
    69
 * href="../lang/ClassLoader.html#name">binary name</a> of the service's type.
jaroslav@557
    70
 * The file contains a list of fully-qualified binary names of concrete
jaroslav@557
    71
 * provider classes, one per line.  Space and tab characters surrounding each
jaroslav@557
    72
 * name, as well as blank lines, are ignored.  The comment character is
jaroslav@557
    73
 * <tt>'#'</tt> (<tt>'&#92;u0023'</tt>, <font size="-1">NUMBER SIGN</font>); on
jaroslav@557
    74
 * each line all characters following the first comment character are ignored.
jaroslav@557
    75
 * The file must be encoded in UTF-8.
jaroslav@557
    76
 *
jaroslav@557
    77
 * <p> If a particular concrete provider class is named in more than one
jaroslav@557
    78
 * configuration file, or is named in the same configuration file more than
jaroslav@557
    79
 * once, then the duplicates are ignored.  The configuration file naming a
jaroslav@557
    80
 * particular provider need not be in the same jar file or other distribution
jaroslav@557
    81
 * unit as the provider itself.  The provider must be accessible from the same
jaroslav@557
    82
 * class loader that was initially queried to locate the configuration file;
jaroslav@557
    83
 * note that this is not necessarily the class loader from which the file was
jaroslav@557
    84
 * actually loaded.
jaroslav@557
    85
 *
jaroslav@557
    86
 * <p> Providers are located and instantiated lazily, that is, on demand.  A
jaroslav@557
    87
 * service loader maintains a cache of the providers that have been loaded so
jaroslav@557
    88
 * far.  Each invocation of the {@link #iterator iterator} method returns an
jaroslav@557
    89
 * iterator that first yields all of the elements of the cache, in
jaroslav@557
    90
 * instantiation order, and then lazily locates and instantiates any remaining
jaroslav@557
    91
 * providers, adding each one to the cache in turn.  The cache can be cleared
jaroslav@557
    92
 * via the {@link #reload reload} method.
jaroslav@557
    93
 *
jaroslav@557
    94
 * <p> Service loaders always execute in the security context of the caller.
jaroslav@557
    95
 * Trusted system code should typically invoke the methods in this class, and
jaroslav@557
    96
 * the methods of the iterators which they return, from within a privileged
jaroslav@557
    97
 * security context.
jaroslav@557
    98
 *
jaroslav@557
    99
 * <p> Instances of this class are not safe for use by multiple concurrent
jaroslav@557
   100
 * threads.
jaroslav@557
   101
 *
jaroslav@557
   102
 * <p> Unless otherwise specified, passing a <tt>null</tt> argument to any
jaroslav@557
   103
 * method in this class will cause a {@link NullPointerException} to be thrown.
jaroslav@557
   104
 *
jaroslav@557
   105
 *
jaroslav@557
   106
 * <p><span style="font-weight: bold; padding-right: 1em">Example</span>
jaroslav@557
   107
 * Suppose we have a service type <tt>com.example.CodecSet</tt> which is
jaroslav@557
   108
 * intended to represent sets of encoder/decoder pairs for some protocol.  In
jaroslav@557
   109
 * this case it is an abstract class with two abstract methods:
jaroslav@557
   110
 *
jaroslav@557
   111
 * <blockquote><pre>
jaroslav@557
   112
 * public abstract Encoder getEncoder(String encodingName);
jaroslav@557
   113
 * public abstract Decoder getDecoder(String encodingName);</pre></blockquote>
jaroslav@557
   114
 *
jaroslav@557
   115
 * Each method returns an appropriate object or <tt>null</tt> if the provider
jaroslav@557
   116
 * does not support the given encoding.  Typical providers support more than
jaroslav@557
   117
 * one encoding.
jaroslav@557
   118
 *
jaroslav@557
   119
 * <p> If <tt>com.example.impl.StandardCodecs</tt> is an implementation of the
jaroslav@557
   120
 * <tt>CodecSet</tt> service then its jar file also contains a file named
jaroslav@557
   121
 *
jaroslav@557
   122
 * <blockquote><pre>
jaroslav@557
   123
 * META-INF/services/com.example.CodecSet</pre></blockquote>
jaroslav@557
   124
 *
jaroslav@557
   125
 * <p> This file contains the single line:
jaroslav@557
   126
 *
jaroslav@557
   127
 * <blockquote><pre>
jaroslav@557
   128
 * com.example.impl.StandardCodecs    # Standard codecs</pre></blockquote>
jaroslav@557
   129
 *
jaroslav@557
   130
 * <p> The <tt>CodecSet</tt> class creates and saves a single service instance
jaroslav@557
   131
 * at initialization:
jaroslav@557
   132
 *
jaroslav@557
   133
 * <blockquote><pre>
jaroslav@557
   134
 * private static ServiceLoader&lt;CodecSet&gt; codecSetLoader
jaroslav@557
   135
 *     = ServiceLoader.load(CodecSet.class);</pre></blockquote>
jaroslav@557
   136
 *
jaroslav@557
   137
 * <p> To locate an encoder for a given encoding name it defines a static
jaroslav@557
   138
 * factory method which iterates through the known and available providers,
jaroslav@557
   139
 * returning only when it has located a suitable encoder or has run out of
jaroslav@557
   140
 * providers.
jaroslav@557
   141
 *
jaroslav@557
   142
 * <blockquote><pre>
jaroslav@557
   143
 * public static Encoder getEncoder(String encodingName) {
jaroslav@557
   144
 *     for (CodecSet cp : codecSetLoader) {
jaroslav@557
   145
 *         Encoder enc = cp.getEncoder(encodingName);
jaroslav@557
   146
 *         if (enc != null)
jaroslav@557
   147
 *             return enc;
jaroslav@557
   148
 *     }
jaroslav@557
   149
 *     return null;
jaroslav@557
   150
 * }</pre></blockquote>
jaroslav@557
   151
 *
jaroslav@557
   152
 * <p> A <tt>getDecoder</tt> method is defined similarly.
jaroslav@557
   153
 *
jaroslav@557
   154
 *
jaroslav@557
   155
 * <p><span style="font-weight: bold; padding-right: 1em">Usage Note</span> If
jaroslav@557
   156
 * the class path of a class loader that is used for provider loading includes
jaroslav@557
   157
 * remote network URLs then those URLs will be dereferenced in the process of
jaroslav@557
   158
 * searching for provider-configuration files.
jaroslav@557
   159
 *
jaroslav@557
   160
 * <p> This activity is normal, although it may cause puzzling entries to be
jaroslav@557
   161
 * created in web-server logs.  If a web server is not configured correctly,
jaroslav@557
   162
 * however, then this activity may cause the provider-loading algorithm to fail
jaroslav@557
   163
 * spuriously.
jaroslav@557
   164
 *
jaroslav@557
   165
 * <p> A web server should return an HTTP 404 (Not Found) response when a
jaroslav@557
   166
 * requested resource does not exist.  Sometimes, however, web servers are
jaroslav@557
   167
 * erroneously configured to return an HTTP 200 (OK) response along with a
jaroslav@557
   168
 * helpful HTML error page in such cases.  This will cause a {@link
jaroslav@557
   169
 * ServiceConfigurationError} to be thrown when this class attempts to parse
jaroslav@557
   170
 * the HTML page as a provider-configuration file.  The best solution to this
jaroslav@557
   171
 * problem is to fix the misconfigured web server to return the correct
jaroslav@557
   172
 * response code (HTTP 404) along with the HTML error page.
jaroslav@557
   173
 *
jaroslav@557
   174
 * @param  <S>
jaroslav@557
   175
 *         The type of the service to be loaded by this loader
jaroslav@557
   176
 *
jaroslav@557
   177
 * @author Mark Reinhold
jaroslav@557
   178
 * @since 1.6
jaroslav@557
   179
 */
jaroslav@557
   180
jaroslav@557
   181
public final class ServiceLoader<S>
jaroslav@557
   182
    implements Iterable<S>
jaroslav@557
   183
{
jaroslav@557
   184
jaroslav@557
   185
    private static final String PREFIX = "META-INF/services/";
jaroslav@557
   186
jaroslav@557
   187
    // The class or interface representing the service being loaded
jaroslav@557
   188
    private Class<S> service;
jaroslav@557
   189
jaroslav@557
   190
    // The class loader used to locate, load, and instantiate providers
jaroslav@557
   191
    private ClassLoader loader;
jaroslav@557
   192
jaroslav@557
   193
    // Cached providers, in instantiation order
jaroslav@557
   194
    private LinkedHashMap<String,S> providers = new LinkedHashMap<>();
jaroslav@557
   195
jaroslav@557
   196
    // The current lazy-lookup iterator
jaroslav@557
   197
    private LazyIterator lookupIterator;
jaroslav@557
   198
jaroslav@557
   199
    /**
jaroslav@557
   200
     * Clear this loader's provider cache so that all providers will be
jaroslav@557
   201
     * reloaded.
jaroslav@557
   202
     *
jaroslav@557
   203
     * <p> After invoking this method, subsequent invocations of the {@link
jaroslav@557
   204
     * #iterator() iterator} method will lazily look up and instantiate
jaroslav@557
   205
     * providers from scratch, just as is done by a newly-created loader.
jaroslav@557
   206
     *
jaroslav@557
   207
     * <p> This method is intended for use in situations in which new providers
jaroslav@557
   208
     * can be installed into a running Java virtual machine.
jaroslav@557
   209
     */
jaroslav@557
   210
    public void reload() {
jaroslav@557
   211
        providers.clear();
jaroslav@557
   212
        lookupIterator = new LazyIterator(service, loader);
jaroslav@557
   213
    }
jaroslav@557
   214
jaroslav@557
   215
    private ServiceLoader(Class<S> svc, ClassLoader cl) {
jaroslav@557
   216
        service = svc;
jaroslav@557
   217
        loader = cl;
jaroslav@557
   218
        reload();
jaroslav@557
   219
    }
jaroslav@557
   220
jaroslav@557
   221
    private static void fail(Class service, String msg, Throwable cause)
jaroslav@557
   222
        throws ServiceConfigurationError
jaroslav@557
   223
    {
jaroslav@557
   224
        throw new ServiceConfigurationError(service.getName() + ": " + msg,
jaroslav@557
   225
                                            cause);
jaroslav@557
   226
    }
jaroslav@557
   227
jaroslav@557
   228
    private static void fail(Class service, String msg)
jaroslav@557
   229
        throws ServiceConfigurationError
jaroslav@557
   230
    {
jaroslav@557
   231
        throw new ServiceConfigurationError(service.getName() + ": " + msg);
jaroslav@557
   232
    }
jaroslav@557
   233
jaroslav@557
   234
    private static void fail(Class service, URL u, int line, String msg)
jaroslav@557
   235
        throws ServiceConfigurationError
jaroslav@557
   236
    {
jaroslav@557
   237
        fail(service, u + ":" + line + ": " + msg);
jaroslav@557
   238
    }
jaroslav@557
   239
jaroslav@557
   240
    // Parse a single line from the given configuration file, adding the name
jaroslav@557
   241
    // on the line to the names list.
jaroslav@557
   242
    //
jaroslav@557
   243
    private int parseLine(Class service, URL u, BufferedReader r, int lc,
jaroslav@557
   244
                          List<String> names)
jaroslav@557
   245
        throws IOException, ServiceConfigurationError
jaroslav@557
   246
    {
jaroslav@557
   247
        String ln = r.readLine();
jaroslav@557
   248
        if (ln == null) {
jaroslav@557
   249
            return -1;
jaroslav@557
   250
        }
jaroslav@557
   251
        int ci = ln.indexOf('#');
jaroslav@557
   252
        if (ci >= 0) ln = ln.substring(0, ci);
jaroslav@557
   253
        ln = ln.trim();
jaroslav@557
   254
        int n = ln.length();
jaroslav@557
   255
        if (n != 0) {
jaroslav@557
   256
            if ((ln.indexOf(' ') >= 0) || (ln.indexOf('\t') >= 0))
jaroslav@557
   257
                fail(service, u, lc, "Illegal configuration-file syntax");
jaroslav@557
   258
            int cp = ln.codePointAt(0);
jaroslav@557
   259
            if (!Character.isJavaIdentifierStart(cp))
jaroslav@557
   260
                fail(service, u, lc, "Illegal provider-class name: " + ln);
jaroslav@557
   261
            for (int i = Character.charCount(cp); i < n; i += Character.charCount(cp)) {
jaroslav@557
   262
                cp = ln.codePointAt(i);
jaroslav@557
   263
                if (!Character.isJavaIdentifierPart(cp) && (cp != '.'))
jaroslav@557
   264
                    fail(service, u, lc, "Illegal provider-class name: " + ln);
jaroslav@557
   265
            }
jaroslav@557
   266
            if (!providers.containsKey(ln) && !names.contains(ln))
jaroslav@557
   267
                names.add(ln);
jaroslav@557
   268
        }
jaroslav@557
   269
        return lc + 1;
jaroslav@557
   270
    }
jaroslav@557
   271
jaroslav@557
   272
    // Parse the content of the given URL as a provider-configuration file.
jaroslav@557
   273
    //
jaroslav@557
   274
    // @param  service
jaroslav@557
   275
    //         The service type for which providers are being sought;
jaroslav@557
   276
    //         used to construct error detail strings
jaroslav@557
   277
    //
jaroslav@557
   278
    // @param  u
jaroslav@557
   279
    //         The URL naming the configuration file to be parsed
jaroslav@557
   280
    //
jaroslav@557
   281
    // @return A (possibly empty) iterator that will yield the provider-class
jaroslav@557
   282
    //         names in the given configuration file that are not yet members
jaroslav@557
   283
    //         of the returned set
jaroslav@557
   284
    //
jaroslav@557
   285
    // @throws ServiceConfigurationError
jaroslav@557
   286
    //         If an I/O error occurs while reading from the given URL, or
jaroslav@557
   287
    //         if a configuration-file format error is detected
jaroslav@557
   288
    //
jaroslav@557
   289
    private Iterator<String> parse(Class service, URL u)
jaroslav@557
   290
        throws ServiceConfigurationError
jaroslav@557
   291
    {
jaroslav@557
   292
        InputStream in = null;
jaroslav@557
   293
        BufferedReader r = null;
jaroslav@557
   294
        ArrayList<String> names = new ArrayList<>();
jaroslav@557
   295
        try {
jaroslav@557
   296
            in = u.openStream();
jaroslav@557
   297
            r = new BufferedReader(new InputStreamReader(in, "utf-8"));
jaroslav@557
   298
            int lc = 1;
jaroslav@557
   299
            while ((lc = parseLine(service, u, r, lc, names)) >= 0);
jaroslav@557
   300
        } catch (IOException x) {
jaroslav@557
   301
            fail(service, "Error reading configuration file", x);
jaroslav@557
   302
        } finally {
jaroslav@557
   303
            try {
jaroslav@557
   304
                if (r != null) r.close();
jaroslav@557
   305
                if (in != null) in.close();
jaroslav@557
   306
            } catch (IOException y) {
jaroslav@557
   307
                fail(service, "Error closing configuration file", y);
jaroslav@557
   308
            }
jaroslav@557
   309
        }
jaroslav@557
   310
        return names.iterator();
jaroslav@557
   311
    }
jaroslav@557
   312
jaroslav@557
   313
    // Private inner class implementing fully-lazy provider lookup
jaroslav@557
   314
    //
jaroslav@557
   315
    private class LazyIterator
jaroslav@557
   316
        implements Iterator<S>
jaroslav@557
   317
    {
jaroslav@557
   318
jaroslav@557
   319
        Class<S> service;
jaroslav@557
   320
        ClassLoader loader;
jaroslav@557
   321
        Enumeration<URL> configs = null;
jaroslav@557
   322
        Iterator<String> pending = null;
jaroslav@557
   323
        String nextName = null;
jaroslav@557
   324
jaroslav@557
   325
        private LazyIterator(Class<S> service, ClassLoader loader) {
jaroslav@557
   326
            this.service = service;
jaroslav@557
   327
            this.loader = loader;
jaroslav@557
   328
        }
jaroslav@557
   329
jaroslav@557
   330
        public boolean hasNext() {
jaroslav@557
   331
            if (nextName != null) {
jaroslav@557
   332
                return true;
jaroslav@557
   333
            }
jaroslav@557
   334
            if (configs == null) {
jaroslav@557
   335
                try {
jaroslav@557
   336
                    String fullName = PREFIX + service.getName();
jaroslav@557
   337
                    if (loader == null)
jaroslav@557
   338
                        configs = ClassLoader.getSystemResources(fullName);
jaroslav@557
   339
                    else
jaroslav@557
   340
                        configs = loader.getResources(fullName);
jaroslav@557
   341
                } catch (IOException x) {
jaroslav@557
   342
                    fail(service, "Error locating configuration files", x);
jaroslav@557
   343
                }
jaroslav@557
   344
            }
jaroslav@557
   345
            while ((pending == null) || !pending.hasNext()) {
jaroslav@557
   346
                if (!configs.hasMoreElements()) {
jaroslav@557
   347
                    return false;
jaroslav@557
   348
                }
jaroslav@557
   349
                pending = parse(service, configs.nextElement());
jaroslav@557
   350
            }
jaroslav@557
   351
            nextName = pending.next();
jaroslav@557
   352
            return true;
jaroslav@557
   353
        }
jaroslav@557
   354
jaroslav@557
   355
        public S next() {
jaroslav@557
   356
            if (!hasNext()) {
jaroslav@557
   357
                throw new NoSuchElementException();
jaroslav@557
   358
            }
jaroslav@557
   359
            String cn = nextName;
jaroslav@557
   360
            nextName = null;
jaroslav@557
   361
            try {
jaroslav@557
   362
                S p = service.cast(Class.forName(cn, true, loader)
jaroslav@557
   363
                                   .newInstance());
jaroslav@557
   364
                providers.put(cn, p);
jaroslav@557
   365
                return p;
jaroslav@557
   366
            } catch (ClassNotFoundException x) {
jaroslav@557
   367
                fail(service,
jaroslav@557
   368
                     "Provider " + cn + " not found");
jaroslav@557
   369
            } catch (Throwable x) {
jaroslav@557
   370
                fail(service,
jaroslav@557
   371
                     "Provider " + cn + " could not be instantiated: " + x,
jaroslav@557
   372
                     x);
jaroslav@557
   373
            }
jaroslav@557
   374
            throw new Error();          // This cannot happen
jaroslav@557
   375
        }
jaroslav@557
   376
jaroslav@557
   377
        public void remove() {
jaroslav@557
   378
            throw new UnsupportedOperationException();
jaroslav@557
   379
        }
jaroslav@557
   380
jaroslav@557
   381
    }
jaroslav@557
   382
jaroslav@557
   383
    /**
jaroslav@557
   384
     * Lazily loads the available providers of this loader's service.
jaroslav@557
   385
     *
jaroslav@557
   386
     * <p> The iterator returned by this method first yields all of the
jaroslav@557
   387
     * elements of the provider cache, in instantiation order.  It then lazily
jaroslav@557
   388
     * loads and instantiates any remaining providers, adding each one to the
jaroslav@557
   389
     * cache in turn.
jaroslav@557
   390
     *
jaroslav@557
   391
     * <p> To achieve laziness the actual work of parsing the available
jaroslav@557
   392
     * provider-configuration files and instantiating providers must be done by
jaroslav@557
   393
     * the iterator itself.  Its {@link java.util.Iterator#hasNext hasNext} and
jaroslav@557
   394
     * {@link java.util.Iterator#next next} methods can therefore throw a
jaroslav@557
   395
     * {@link ServiceConfigurationError} if a provider-configuration file
jaroslav@557
   396
     * violates the specified format, or if it names a provider class that
jaroslav@557
   397
     * cannot be found and instantiated, or if the result of instantiating the
jaroslav@557
   398
     * class is not assignable to the service type, or if any other kind of
jaroslav@557
   399
     * exception or error is thrown as the next provider is located and
jaroslav@557
   400
     * instantiated.  To write robust code it is only necessary to catch {@link
jaroslav@557
   401
     * ServiceConfigurationError} when using a service iterator.
jaroslav@557
   402
     *
jaroslav@557
   403
     * <p> If such an error is thrown then subsequent invocations of the
jaroslav@557
   404
     * iterator will make a best effort to locate and instantiate the next
jaroslav@557
   405
     * available provider, but in general such recovery cannot be guaranteed.
jaroslav@557
   406
     *
jaroslav@557
   407
     * <blockquote style="font-size: smaller; line-height: 1.2"><span
jaroslav@557
   408
     * style="padding-right: 1em; font-weight: bold">Design Note</span>
jaroslav@557
   409
     * Throwing an error in these cases may seem extreme.  The rationale for
jaroslav@557
   410
     * this behavior is that a malformed provider-configuration file, like a
jaroslav@557
   411
     * malformed class file, indicates a serious problem with the way the Java
jaroslav@557
   412
     * virtual machine is configured or is being used.  As such it is
jaroslav@557
   413
     * preferable to throw an error rather than try to recover or, even worse,
jaroslav@557
   414
     * fail silently.</blockquote>
jaroslav@557
   415
     *
jaroslav@557
   416
     * <p> The iterator returned by this method does not support removal.
jaroslav@557
   417
     * Invoking its {@link java.util.Iterator#remove() remove} method will
jaroslav@557
   418
     * cause an {@link UnsupportedOperationException} to be thrown.
jaroslav@557
   419
     *
jaroslav@557
   420
     * @return  An iterator that lazily loads providers for this loader's
jaroslav@557
   421
     *          service
jaroslav@557
   422
     */
jaroslav@557
   423
    public Iterator<S> iterator() {
jaroslav@557
   424
        return new Iterator<S>() {
jaroslav@557
   425
jaroslav@557
   426
            Iterator<Map.Entry<String,S>> knownProviders
jaroslav@557
   427
                = providers.entrySet().iterator();
jaroslav@557
   428
jaroslav@557
   429
            public boolean hasNext() {
jaroslav@557
   430
                if (knownProviders.hasNext())
jaroslav@557
   431
                    return true;
jaroslav@557
   432
                return lookupIterator.hasNext();
jaroslav@557
   433
            }
jaroslav@557
   434
jaroslav@557
   435
            public S next() {
jaroslav@557
   436
                if (knownProviders.hasNext())
jaroslav@557
   437
                    return knownProviders.next().getValue();
jaroslav@557
   438
                return lookupIterator.next();
jaroslav@557
   439
            }
jaroslav@557
   440
jaroslav@557
   441
            public void remove() {
jaroslav@557
   442
                throw new UnsupportedOperationException();
jaroslav@557
   443
            }
jaroslav@557
   444
jaroslav@557
   445
        };
jaroslav@557
   446
    }
jaroslav@557
   447
jaroslav@557
   448
    /**
jaroslav@557
   449
     * Creates a new service loader for the given service type and class
jaroslav@557
   450
     * loader.
jaroslav@557
   451
     *
jaroslav@557
   452
     * @param  service
jaroslav@557
   453
     *         The interface or abstract class representing the service
jaroslav@557
   454
     *
jaroslav@557
   455
     * @param  loader
jaroslav@557
   456
     *         The class loader to be used to load provider-configuration files
jaroslav@557
   457
     *         and provider classes, or <tt>null</tt> if the system class
jaroslav@557
   458
     *         loader (or, failing that, the bootstrap class loader) is to be
jaroslav@557
   459
     *         used
jaroslav@557
   460
     *
jaroslav@557
   461
     * @return A new service loader
jaroslav@557
   462
     */
jaroslav@557
   463
    public static <S> ServiceLoader<S> load(Class<S> service,
jaroslav@557
   464
                                            ClassLoader loader)
jaroslav@557
   465
    {
jaroslav@557
   466
        return new ServiceLoader<>(service, loader);
jaroslav@557
   467
    }
jaroslav@557
   468
jaroslav@557
   469
    /**
jaroslav@557
   470
     * Creates a new service loader for the given service type, using the
jaroslav@557
   471
     * current thread's {@linkplain java.lang.Thread#getContextClassLoader
jaroslav@557
   472
     * context class loader}.
jaroslav@557
   473
     *
jaroslav@557
   474
     * <p> An invocation of this convenience method of the form
jaroslav@557
   475
     *
jaroslav@557
   476
     * <blockquote><pre>
jaroslav@557
   477
     * ServiceLoader.load(<i>service</i>)</pre></blockquote>
jaroslav@557
   478
     *
jaroslav@557
   479
     * is equivalent to
jaroslav@557
   480
     *
jaroslav@557
   481
     * <blockquote><pre>
jaroslav@557
   482
     * ServiceLoader.load(<i>service</i>,
jaroslav@557
   483
     *                    Thread.currentThread().getContextClassLoader())</pre></blockquote>
jaroslav@557
   484
     *
jaroslav@557
   485
     * @param  service
jaroslav@557
   486
     *         The interface or abstract class representing the service
jaroslav@557
   487
     *
jaroslav@557
   488
     * @return A new service loader
jaroslav@557
   489
     */
jaroslav@557
   490
    public static <S> ServiceLoader<S> load(Class<S> service) {
jaroslav@565
   491
        ClassLoader cl = null; // XXX: Thread.currentThread().getContextClassLoader();
jaroslav@557
   492
        return ServiceLoader.load(service, cl);
jaroslav@557
   493
    }
jaroslav@557
   494
jaroslav@557
   495
    /**
jaroslav@557
   496
     * Creates a new service loader for the given service type, using the
jaroslav@557
   497
     * extension class loader.
jaroslav@557
   498
     *
jaroslav@557
   499
     * <p> This convenience method simply locates the extension class loader,
jaroslav@557
   500
     * call it <tt><i>extClassLoader</i></tt>, and then returns
jaroslav@557
   501
     *
jaroslav@557
   502
     * <blockquote><pre>
jaroslav@557
   503
     * ServiceLoader.load(<i>service</i>, <i>extClassLoader</i>)</pre></blockquote>
jaroslav@557
   504
     *
jaroslav@557
   505
     * <p> If the extension class loader cannot be found then the system class
jaroslav@557
   506
     * loader is used; if there is no system class loader then the bootstrap
jaroslav@557
   507
     * class loader is used.
jaroslav@557
   508
     *
jaroslav@557
   509
     * <p> This method is intended for use when only installed providers are
jaroslav@557
   510
     * desired.  The resulting service will only find and load providers that
jaroslav@557
   511
     * have been installed into the current Java virtual machine; providers on
jaroslav@557
   512
     * the application's class path will be ignored.
jaroslav@557
   513
     *
jaroslav@557
   514
     * @param  service
jaroslav@557
   515
     *         The interface or abstract class representing the service
jaroslav@557
   516
     *
jaroslav@557
   517
     * @return A new service loader
jaroslav@557
   518
     */
jaroslav@557
   519
    public static <S> ServiceLoader<S> loadInstalled(Class<S> service) {
jaroslav@557
   520
        ClassLoader cl = ClassLoader.getSystemClassLoader();
jaroslav@557
   521
        ClassLoader prev = null;
jaroslav@557
   522
        while (cl != null) {
jaroslav@557
   523
            prev = cl;
jaroslav@557
   524
            cl = cl.getParent();
jaroslav@557
   525
        }
jaroslav@557
   526
        return ServiceLoader.load(service, prev);
jaroslav@557
   527
    }
jaroslav@557
   528
jaroslav@557
   529
    /**
jaroslav@557
   530
     * Returns a string describing this service.
jaroslav@557
   531
     *
jaroslav@557
   532
     * @return  A descriptive string
jaroslav@557
   533
     */
jaroslav@557
   534
    public String toString() {
jaroslav@557
   535
        return "java.util.ServiceLoader[" + service.getName() + "]";
jaroslav@557
   536
    }
jaroslav@557
   537
jaroslav@557
   538
}