1 /* 2 * Copyright (C) 2014 The Android Open Source Project 3 * Copyright (c) 2005, 2021, Oracle and/or its affiliates. All rights reserved. 4 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 5 * 6 * This code is free software; you can redistribute it and/or modify it 7 * under the terms of the GNU General Public License version 2 only, as 8 * published by the Free Software Foundation. Oracle designates this 9 * particular file as subject to the "Classpath" exception as provided 10 * by Oracle in the LICENSE file that accompanied this code. 11 * 12 * This code is distributed in the hope that it will be useful, but WITHOUT 13 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 14 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 15 * version 2 for more details (a copy is included in the LICENSE file that 16 * accompanied this code). 17 * 18 * You should have received a copy of the GNU General Public License version 19 * 2 along with this work; if not, write to the Free Software Foundation, 20 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 21 * 22 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 23 * or visit www.oracle.com if you need additional information or have any 24 * questions. 25 */ 26 27 package java.util; 28 29 import java.io.BufferedReader; 30 import java.io.IOException; 31 import java.io.InputStream; 32 import java.io.InputStreamReader; 33 import java.lang.reflect.Constructor; 34 import java.lang.reflect.InvocationTargetException; 35 import java.lang.reflect.Method; 36 import java.lang.reflect.Modifier; 37 import java.net.URL; 38 import java.nio.charset.StandardCharsets; 39 import java.util.ArrayList; 40 import java.util.Enumeration; 41 import java.util.Iterator; 42 import java.util.List; 43 import java.util.NoSuchElementException; 44 import java.net.URLConnection; 45 import java.security.AccessControlContext; 46 import java.security.AccessController; 47 import java.security.PrivilegedAction; 48 import java.security.PrivilegedActionException; 49 import java.security.PrivilegedExceptionAction; 50 import java.util.function.Consumer; 51 import java.util.function.Supplier; 52 import java.util.stream.Stream; 53 import java.util.stream.StreamSupport; 54 55 import jdk.internal.misc.VM; 56 import jdk.internal.reflect.CallerSensitive; 57 import jdk.internal.reflect.Reflection; 58 59 // Android-changed: JPMS and Security related sections are commented out. 60 /** 61 * A facility to load implementations of a service. 62 * 63 * <p> A <i>service</i> is a well-known interface or class for which zero, one, 64 * or many service providers exist. A <i>service provider</i> (or just 65 * <i>provider</i>) is a class that implements or subclasses the well-known 66 * interface or class. A {@code ServiceLoader} is an object that locates and 67 * loads service providers deployed in the run time environment at a time of an 68 * application's choosing. Application code refers only to the service, not to 69 * service providers, and is assumed to be capable of choosing between multiple 70 * service providers (based on the functionality they expose through the service), 71 * and handling the possibility that no service providers are located. 72 * 73 * <h2> Obtaining a service loader </h2> 74 * 75 * <p> An application obtains a service loader for a given service by invoking 76 * one of the static {@code load} methods of {@code ServiceLoader}. <!--If the 77 * application is a module, then its module declaration must have a <i>uses</i> 78 * directive that specifies the service; this helps to locate providers and ensure 79 * they will execute reliably. In addition, if the application module does not 80 * contain the service, then its module declaration must have a <i>requires</i> 81 * directive that specifies the module which exports the service. It is strongly 82 * recommended that the application module does <b>not</b> require modules which 83 * contain providers of the service.--/> 84 * 85 * <p> A service loader can be used to locate and instantiate providers of the 86 * service by means of the {@link #iterator() iterator} method. {@code ServiceLoader} 87 * also defines the {@link #stream() stream} method to obtain a stream of providers 88 * that can be inspected and filtered without instantiating them. 89 * 90 * <p> As an example, suppose the service is {@code com.example.CodecFactory}, an 91 * interface that defines methods for producing encoders and decoders: 92 * 93 * <pre>{@code 94 * package com.example; 95 * public interface CodecFactory { 96 * Encoder getEncoder(String encodingName); 97 * Decoder getDecoder(String encodingName); 98 * } 99 * }</pre> 100 * 101 * <p> The following code obtains a service loader for the {@code CodecFactory} 102 * service, then uses its iterator (created automatically by the enhanced-for 103 * loop) to yield instances of the service providers that are located: 104 * 105 * <pre>{@code 106 * ServiceLoader<CodecFactory> loader = ServiceLoader.load(CodecFactory.class); 107 * for (CodecFactory factory : loader) { 108 * Encoder enc = factory.getEncoder("PNG"); 109 * if (enc != null) 110 * ... use enc to encode a PNG file 111 * break; 112 * } 113 * }</pre> 114 * 115 * <p> Sometimes an application may wish to inspect a service provider before 116 * instantiating it, in order to determine if an instance of that service 117 * provider would be useful. For example, a service provider for {@code 118 * CodecFactory} that is capable of producing a "PNG" encoder may be annotated 119 * with {@code @PNG}. The following code uses service loader's {@code stream} 120 * method to yield instances of {@code Provider<CodecFactory>} in contrast to 121 * how the iterator yields instances of {@code CodecFactory}: 122 * <pre>{@code 123 * ServiceLoader<CodecFactory> loader = ServiceLoader.load(CodecFactory.class); 124 * Set<CodecFactory> pngFactories = loader 125 * .stream() // Note a below 126 * .filter(p -> p.type().isAnnotationPresent(PNG.class)) // Note b 127 * .map(Provider::get) // Note c 128 * .collect(Collectors.toSet()); 129 * }</pre> 130 * <ol type="a"> 131 * <li> A stream of {@code Provider<CodecFactory>} objects </li> 132 * <li> {@code p.type()} yields a {@code Class<CodecFactory>} </li> 133 * <li> {@code get()} yields an instance of {@code CodecFactory} </li> 134 * </ol> 135 * 136 * <h2> Designing services </h2> 137 * 138 * <p> A service is a single type, usually an interface or abstract class. A 139 * concrete class can be used, but this is not recommended. The type may have 140 * any accessibility. The methods of a service are highly domain-specific, so 141 * this API specification cannot give concrete advice about their form or 142 * function. However, there are two general guidelines: 143 * <ol> 144 * <li><p> A service should declare as many methods as needed to allow service 145 * providers to communicate their domain-specific properties and other 146 * quality-of-implementation factors. An application which obtains a service 147 * loader for the service may then invoke these methods on each instance of 148 * a service provider, in order to choose the best provider for the 149 * application. </p></li> 150 * <li><p> A service should express whether its service providers are intended 151 * to be direct implementations of the service or to be an indirection 152 * mechanism such as a "proxy" or a "factory". Service providers tend to be 153 * indirection mechanisms when domain-specific objects are relatively 154 * expensive to instantiate; in this case, the service should be designed 155 * so that service providers are abstractions which create the "real" 156 * implementation on demand. For example, the {@code CodecFactory} service 157 * expresses through its name that its service providers are factories 158 * for codecs, rather than codecs themselves, because it may be expensive 159 * or complicated to produce certain codecs. </p></li> 160 * </ol> 161 * 162 * <h2> <a id="developing-service-providers">Developing service providers</a> </h2> 163 * 164 * <p> A service provider is a single type, usually a concrete class. An 165 * interface or abstract class is permitted because it may declare a static 166 * provider method, discussed later. The type must be public and must not be 167 * an inner class. 168 * 169 * <p> A service provider and its supporting code may be developed in a module, 170 * which is then deployed on the application module path or in a modular 171 * image. Alternatively, a service provider and its supporting code may be 172 * packaged as a JAR file and deployed on the application class path. The 173 * advantage of developing a service provider in a module is that the provider 174 * can be fully encapsulated to hide all details of its implementation. 175 * 176 * <p> An application that obtains a service loader for a given service is 177 * indifferent to whether providers of the service are deployed in modules or 178 * packaged as JAR files. The application instantiates service providers via 179 * the service loader's iterator, or via {@link Provider Provider} objects in 180 * the service loader's stream, without knowledge of the service providers' 181 * locations. 182 * 183 * <h2> Deploying service providers on the class path </h2> 184 * 185 * A service provider that is packaged as a JAR file for the class path is 186 * identified by placing a <i>provider-configuration file</i> in the resource 187 * directory {@code META-INF/services}. The name of the provider-configuration 188 * file is the fully qualified binary name of the service. The provider-configuration 189 * file contains a list of fully qualified binary names of service providers, one 190 * per line. 191 * 192 * <p> For example, suppose the service provider 193 * {@code com.example.impl.StandardCodecs} is packaged in a JAR file for the 194 * class path. The JAR file will contain a provider-configuration file named: 195 * 196 * <blockquote>{@code 197 * META-INF/services/com.example.CodecFactory 198 * }</blockquote> 199 * 200 * that contains the line: 201 * 202 * <blockquote>{@code 203 * com.example.impl.StandardCodecs # Standard codecs 204 * }</blockquote> 205 * 206 * <p><a id="format">The provider-configuration file must be encoded in UTF-8. </a> 207 * Space and tab characters surrounding each service provider's name, as well as 208 * blank lines, are ignored. The comment character is {@code '#'} 209 * ({@code U+0023} <span style="font-size:smaller;">NUMBER SIGN</span>); 210 * on each line all characters following the first comment character are ignored. 211 * If a service provider class name is listed more than once in a 212 * provider-configuration file then the duplicate is ignored. If a service 213 * provider class is named in more than one configuration file then the duplicate 214 * is ignored. 215 * 216 * <p> A service provider that is mentioned in a provider-configuration file may 217 * be located in the same JAR file as the provider-configuration file or in a 218 * different JAR file. The service provider must be visible from the class loader 219 * that is initially queried to locate the provider-configuration file; this is 220 * not necessarily the class loader which ultimately locates the 221 * provider-configuration file. 222 * 223 * <h2> Timing of provider discovery </h2> 224 * 225 * <p> Service providers are loaded and instantiated lazily, that is, on demand. 226 * A service loader maintains a cache of the providers that have been loaded so 227 * far. Each invocation of the {@code iterator} method returns an {@code Iterator} 228 * that first yields all of the elements cached from previous iteration, in 229 * instantiation order, and then lazily locates and instantiates any remaining 230 * providers, adding each one to the cache in turn. Similarly, each invocation 231 * of the stream method returns a {@code Stream} that first processes all 232 * providers loaded by previous stream operations, in load order, and then lazily 233 * locates any remaining providers. Caches are cleared via the {@link #reload 234 * reload} method. 235 * 236 * <h2> <a id="errors">Errors</a> </h2> 237 * 238 * <p> When using the service loader's {@code iterator}, the {@link 239 * Iterator#hasNext() hasNext} and {@link Iterator#next() next} methods will 240 * fail with {@link ServiceConfigurationError} if an error occurs locating, 241 * loading or instantiating a service provider. When processing the service 242 * loader's stream then {@code ServiceConfigurationError} may be thrown by any 243 * method that causes a service provider to be located or loaded. 244 * 245 * <p> When loading or instantiating a service provider in a module, {@code 246 * ServiceConfigurationError} can be thrown for the following reasons: 247 * 248 * <p> When reading a provider-configuration file, or loading or instantiating 249 * a provider class named in a provider-configuration file, then {@code 250 * ServiceConfigurationError} can be thrown for the following reasons: 251 * 252 * <ul> 253 * 254 * <li> The format of the provider-configuration file violates the <a 255 * href="ServiceLoader.html#format">format</a> specified above; </li> 256 * 257 * <li> An {@link IOException IOException} occurs while reading the 258 * provider-configuration file; </li> 259 * 260 * <li> A service provider cannot be loaded; </li> 261 * 262 * <li> A service provider is not assignable to the service's interface or 263 * class, or does not define a provider constructor, or cannot be 264 * instantiated. </li> 265 * 266 * </ul> 267 * 268 * <h2> Concurrency </h2> 269 * 270 * <p> Instances of this class are not safe for use by multiple concurrent 271 * threads. 272 * 273 * <h3> Null handling </h3> 274 * 275 * <p> Unless otherwise specified, passing a {@code null} argument to any 276 * method in this class will cause a {@link NullPointerException} to be thrown. 277 * 278 * @param <S> 279 * The type of the service to be loaded by this loader 280 * 281 * @author Mark Reinhold 282 * @since 1.6 283 * @revised 9 284 */ 285 286 public final class ServiceLoader<S> 287 implements Iterable<S> 288 { 289 // The class or interface representing the service being loaded 290 private final Class<S> service; 291 292 // The class of the service type 293 // Android-removed: used in JPMS paths only. 294 // private final String serviceName; 295 296 // Android-removed: JPMS is not supported. 297 // The module layer used to locate providers; null when locating 298 // providers using a class loader 299 // private final ModuleLayer layer; 300 301 // The class loader used to locate, load, and instantiate providers; 302 // null when locating provider using a module layer 303 private final ClassLoader loader; 304 305 // The access control context taken when the ServiceLoader is created 306 // Android-changed: do not use legacy security code. 307 // @SuppressWarnings("removal") 308 // private final AccessControlContext acc; 309 310 // The lazy-lookup iterator for iterator operations 311 private Iterator<Provider<S>> lookupIterator1; 312 private final List<S> instantiatedProviders = new ArrayList<>(); 313 314 // The lazy-lookup iterator for stream operations 315 private Iterator<Provider<S>> lookupIterator2; 316 private final List<Provider<S>> loadedProviders = new ArrayList<>(); 317 private boolean loadedAllProviders; // true when all providers loaded 318 319 // Incremented when reload is called 320 private int reloadCount; 321 322 // Android-removed: JavaLangAccess is not yet imported. 323 /* 324 private static JavaLangAccess LANG_ACCESS; 325 static { 326 LANG_ACCESS = SharedSecrets.getJavaLangAccess(); 327 } 328 */ 329 330 /** 331 * Represents a service provider located by {@code ServiceLoader}. 332 * 333 * <p> When using a loader's {@link ServiceLoader#stream() stream()} method 334 * then the elements are of type {@code Provider}. This allows processing 335 * to select or filter on the provider class without instantiating the 336 * provider. </p> 337 * 338 * @param <S> The service type 339 * @since 9 340 */ 341 public static interface Provider<S> extends Supplier<S> { 342 /** 343 * Returns the provider type. There is no guarantee that this type is 344 * accessible or that it has a public no-args constructor. The {@link 345 * #get() get()} method should be used to obtain the provider instance. 346 * 347 * <p> When a module declares that the provider class is created by a 348 * provider factory then this method returns the return type of its 349 * public static "{@code provider()}" method. 350 * 351 * @return The provider type 352 */ type()353 Class<? extends S> type(); 354 355 /** 356 * Returns an instance of the provider. 357 * 358 * @return An instance of the provider. 359 * 360 * @throws ServiceConfigurationError 361 * If the service provider cannot be instantiated, or in the 362 * case of a provider factory, the public static 363 * "{@code provider()}" method returns {@code null} or throws 364 * an error or exception. The {@code ServiceConfigurationError} 365 * will carry an appropriate cause where possible. 366 */ get()367 @Override S get(); 368 } 369 370 // Android-removed: JPMS is not supported. 371 /* 372 * Initializes a new instance of this class for locating service providers 373 * in a module layer. 374 * 375 * @throws ServiceConfigurationError 376 * If {@code svc} is not accessible to {@code caller} or the caller 377 * module does not use the service type. 378 * 379 @SuppressWarnings("removal") 380 private ServiceLoader(Class<?> caller, ModuleLayer layer, Class<S> svc) { 381 Objects.requireNonNull(caller); 382 Objects.requireNonNull(layer); 383 Objects.requireNonNull(svc); 384 checkCaller(caller, svc); 385 386 this.service = svc; 387 this.serviceName = svc.getName(); 388 this.layer = layer; 389 this.loader = null; 390 this.acc = (System.getSecurityManager() != null) 391 ? AccessController.getContext() 392 : null; 393 } 394 */ 395 396 /** 397 * Initializes a new instance of this class for locating service providers 398 * via a class loader. 399 * 400 * @throws ServiceConfigurationError 401 * If {@code svc} is not accessible to {@code caller} or the caller 402 * module does not use the service type. 403 */ 404 @SuppressWarnings("removal") ServiceLoader(Class<?> caller, Class<S> svc, ClassLoader cl)405 private ServiceLoader(Class<?> caller, Class<S> svc, ClassLoader cl) { 406 Objects.requireNonNull(svc); 407 408 if (VM.isBooted()) { 409 checkCaller(caller, svc); 410 if (cl == null) { 411 cl = ClassLoader.getSystemClassLoader(); 412 } 413 } else { 414 415 // if we get here then it means that ServiceLoader is being used 416 // before the VM initialization has completed. At this point then 417 // only code in the java.base should be executing. 418 // Android-removed: JPMS is not supported. 419 /* 420 Module callerModule = caller.getModule(); 421 Module base = Object.class.getModule(); 422 Module svcModule = svc.getModule(); 423 if (callerModule != base || svcModule != base) { 424 fail(svc, "not accessible to " + callerModule + " during VM init"); 425 } 426 */ 427 428 // restricted to boot loader during startup 429 cl = null; 430 } 431 432 this.service = svc; 433 // Android-removed: used in JPMS paths only. 434 // this.serviceName = svc.getName(); 435 // this.layer = null; 436 this.loader = cl; 437 // Android-removed: do not use legacy security code. 438 /* 439 this.acc = (System.getSecurityManager() != null) 440 ? AccessController.getContext() 441 : null; 442 */ 443 } 444 445 // Android-removed: JPMS is not supported. 446 /* 447 * Initializes a new instance of this class for locating service providers 448 * via a class loader. 449 * 450 * @apiNote For use by ResourceBundle 451 * 452 * @throws ServiceConfigurationError 453 * If the caller module does not use the service type. 454 * 455 @SuppressWarnings("removal") 456 private ServiceLoader(Module callerModule, Class<S> svc, ClassLoader cl) { 457 if (!callerModule.canUse(svc)) { 458 fail(svc, callerModule + " does not declare `uses`"); 459 } 460 461 this.service = Objects.requireNonNull(svc); 462 this.serviceName = svc.getName(); 463 this.layer = null; 464 this.loader = cl; 465 this.acc = (System.getSecurityManager() != null) 466 ? AccessController.getContext() 467 : null; 468 } 469 */ 470 471 /** 472 * Checks that the given service type is accessible to types in the given 473 * module, and check that the module declares that it uses the service type. 474 */ checkCaller(Class<?> caller, Class<?> svc)475 private static void checkCaller(Class<?> caller, Class<?> svc) { 476 if (caller == null) { 477 fail(svc, "no caller to check if it declares `uses`"); 478 } 479 480 // Check access to the service type 481 // Module callerModule = caller.getModule(); 482 int mods = svc.getModifiers(); 483 if (!Reflection.verifyMemberAccess(caller, svc, null, mods)) { 484 // Android-removed: JPMS is not supported. 485 // fail(svc, "service type not accessible to " + callerModule); 486 fail(svc, "service type not accessible to " + caller); 487 } 488 489 // If the caller is in a named module then it should "uses" the 490 // service type 491 // Android-removed: JPMS is not supported. 492 /* 493 if (!callerModule.canUse(svc)) { 494 fail(svc, callerModule + " does not declare `uses`"); 495 } 496 */ 497 } 498 fail(Class<?> service, String msg, Throwable cause)499 private static void fail(Class<?> service, String msg, Throwable cause) 500 throws ServiceConfigurationError 501 { 502 throw new ServiceConfigurationError(service.getName() + ": " + msg, 503 cause); 504 } 505 fail(Class<?> service, String msg)506 private static void fail(Class<?> service, String msg) 507 throws ServiceConfigurationError 508 { 509 throw new ServiceConfigurationError(service.getName() + ": " + msg); 510 } 511 fail(Class<?> service, URL u, int line, String msg)512 private static void fail(Class<?> service, URL u, int line, String msg) 513 throws ServiceConfigurationError 514 { 515 fail(service, u + ":" + line + ": " + msg); 516 } 517 518 // Android-removed: JPMS is not supported. 519 /* 520 * Returns {@code true} if the provider is in an explicit module 521 * 522 private boolean inExplicitModule(Class<?> clazz) { 523 Module module = clazz.getModule(); 524 return module.isNamed() && !module.getDescriptor().isAutomatic(); 525 } 526 */ 527 528 // Android-removed: used in JPMS paths only. 529 /* 530 * Returns the public static "provider" method if found. 531 * 532 * @throws ServiceConfigurationError if there is an error finding the 533 * provider method or there is more than one public static 534 * provider method 535 * 536 @SuppressWarnings("removal") 537 private Method findStaticProviderMethod(Class<?> clazz) { 538 List<Method> methods = null; 539 try { 540 methods = LANG_ACCESS.getDeclaredPublicMethods(clazz, "provider"); 541 } catch (Throwable x) { 542 fail(service, "Unable to get public provider() method", x); 543 } 544 if (methods.isEmpty()) { 545 // does not declare a public provider method 546 return null; 547 } 548 549 // locate the static methods, can be at most one 550 Method result = null; 551 for (Method method : methods) { 552 int mods = method.getModifiers(); 553 assert Modifier.isPublic(mods); 554 if (Modifier.isStatic(mods)) { 555 if (result != null) { 556 fail(service, clazz + " declares more than one" 557 + " public static provider() method"); 558 } 559 result = method; 560 } 561 } 562 if (result != null) { 563 Method m = result; 564 PrivilegedAction<Void> pa = () -> { 565 m.setAccessible(true); 566 return null; 567 }; 568 AccessController.doPrivileged(pa); 569 } 570 return result; 571 } 572 */ 573 574 /** 575 * Returns the public no-arg constructor of a class. 576 * 577 * @throws ServiceConfigurationError if the class does not have 578 * public no-arg constructor 579 */ 580 @SuppressWarnings("removal") getConstructor(Class<?> clazz)581 private Constructor<?> getConstructor(Class<?> clazz) { 582 PrivilegedExceptionAction<Constructor<?>> pa 583 = new PrivilegedExceptionAction<>() { 584 @Override 585 public Constructor<?> run() throws Exception { 586 Constructor<?> ctor = clazz.getConstructor(); 587 // Android-removed: JPMS is not supported. 588 // if (inExplicitModule(clazz)) 589 ctor.setAccessible(true); 590 return ctor; 591 } 592 }; 593 Constructor<?> ctor = null; 594 try { 595 ctor = AccessController.doPrivileged(pa); 596 } catch (Throwable x) { 597 if (x instanceof PrivilegedActionException) 598 x = x.getCause(); 599 String cn = clazz.getName(); 600 fail(service, cn + " Unable to get public no-arg constructor", x); 601 } 602 return ctor; 603 } 604 605 /** 606 * A Provider implementation that supports invoking, with reduced 607 * permissions, the static factory to obtain the provider or the 608 * provider's no-arg constructor. 609 */ 610 private static class ProviderImpl<S> implements Provider<S> { 611 final Class<S> service; 612 final Class<? extends S> type; 613 final Method factoryMethod; // factory method or null 614 final Constructor<? extends S> ctor; // public no-args constructor or null 615 // BEGIN Android-changed: removed AccessControlContext from args list. 616 // ProviderImpl(Class, Class, Method) is not used, hence removed. 617 // @SuppressWarnings("removal") 618 // final AccessControlContext acc; 619 620 /* 621 ProviderImpl(Class<S> service, 622 Class<? extends S> type, 623 Method factoryMethod, 624 @SuppressWarnings("removal") AccessControlContext acc) { 625 this.service = service; 626 this.type = type; 627 this.factoryMethod = factoryMethod; 628 this.ctor = null; 629 this.acc = acc; 630 } 631 632 ProviderImpl(Class<S> service, 633 Class<? extends S> type, 634 Constructor<? extends S> ctor, 635 @SuppressWarnings("removal") AccessControlContext acc) { 636 this.service = service; 637 this.type = type; 638 this.factoryMethod = null; 639 this.ctor = ctor; 640 this.acc = acc; 641 } 642 */ 643 ProviderImpl(Class<S> service, Class<? extends S> type, Constructor<? extends S> ctor)644 ProviderImpl(Class<S> service, 645 Class<? extends S> type, 646 Constructor<? extends S> ctor) { 647 this.service = service; 648 this.type = type; 649 this.factoryMethod = null; 650 this.ctor = ctor; 651 } 652 // END Android-changed: removed AccessControlContext from args list. 653 654 @Override type()655 public Class<? extends S> type() { 656 return type; 657 } 658 659 @Override get()660 public S get() { 661 if (factoryMethod != null) { 662 return invokeFactoryMethod(); 663 } else { 664 return newInstance(); 665 } 666 } 667 668 /** 669 * Invokes the provider's "provider" method to instantiate a provider. 670 * When running with a security manager then the method runs with 671 * permissions that are restricted by the security context of whatever 672 * created this loader. 673 */ 674 @SuppressWarnings("removal") invokeFactoryMethod()675 private S invokeFactoryMethod() { 676 Object result = null; 677 Throwable exc = null; 678 // BEGIN Android-changed: do not use legacy security code. 679 // if (acc == null) { 680 try { 681 result = factoryMethod.invoke(null); 682 } catch (Throwable x) { 683 exc = x; 684 } 685 /* 686 } else { 687 PrivilegedExceptionAction<?> pa = new PrivilegedExceptionAction<>() { 688 @Override 689 public Object run() throws Exception { 690 return factoryMethod.invoke(null); 691 } 692 }; 693 // invoke factory method with permissions restricted by acc 694 try { 695 result = AccessController.doPrivileged(pa, acc); 696 } catch (Throwable x) { 697 if (x instanceof PrivilegedActionException) 698 x = x.getCause(); 699 exc = x; 700 } 701 } 702 */ 703 // END Android-changed: do not use legacy security code. 704 if (exc != null) { 705 if (exc instanceof InvocationTargetException) 706 exc = exc.getCause(); 707 fail(service, factoryMethod + " failed", exc); 708 } 709 if (result == null) { 710 fail(service, factoryMethod + " returned null"); 711 } 712 @SuppressWarnings("unchecked") 713 S p = (S) result; 714 return p; 715 } 716 717 /** 718 * Invokes Constructor::newInstance to instantiate a provider. When running 719 * with a security manager then the constructor runs with permissions that 720 * are restricted by the security context of whatever created this loader. 721 */ 722 @SuppressWarnings("removal") newInstance()723 private S newInstance() { 724 S p = null; 725 Throwable exc = null; 726 // BEGIN Androic-changed: do not use legacy security code. 727 // if (acc == null) { 728 try { 729 p = ctor.newInstance(); 730 } catch (Throwable x) { 731 exc = x; 732 } 733 /* 734 } else { 735 PrivilegedExceptionAction<S> pa = new PrivilegedExceptionAction<>() { 736 @Override 737 public S run() throws Exception { 738 return ctor.newInstance(); 739 } 740 }; 741 // invoke constructor with permissions restricted by acc 742 try { 743 p = AccessController.doPrivileged(pa, acc); 744 } catch (Throwable x) { 745 if (x instanceof PrivilegedActionException) 746 x = x.getCause(); 747 exc = x; 748 } 749 } 750 */ 751 // END Android-changed: do not use legacy security code. 752 if (exc != null) { 753 if (exc instanceof InvocationTargetException) 754 exc = exc.getCause(); 755 String cn = ctor.getDeclaringClass().getName(); 756 fail(service, 757 "Provider " + cn + " could not be instantiated", exc); 758 } 759 return p; 760 } 761 762 // For now, equals/hashCode uses the access control context to ensure 763 // that two Providers created with different contexts are not equal 764 // when running with a security manager. 765 766 @Override hashCode()767 public int hashCode() { 768 // Android-changed: do not use legacy security code. 769 // return Objects.hash(service, type, acc); 770 return Objects.hash(service, type); 771 } 772 773 @Override equals(Object ob)774 public boolean equals(Object ob) { 775 return ob instanceof @SuppressWarnings("unchecked")ProviderImpl<?> that 776 && this.service == that.service 777 && this.type == that.type; 778 // Android-changed: do not use legacy security code. 779 // && Objects.equals(this.acc, that.acc); 780 } 781 } 782 783 // BEGIN Android-removed: JPMS is not supported. 784 /* 785 * Loads a service provider in a module. 786 * 787 * Returns {@code null} if the service provider's module doesn't read 788 * the module with the service type. 789 * 790 * @throws ServiceConfigurationError if the class cannot be loaded or 791 * isn't the expected sub-type (or doesn't define a provider 792 * factory method that returns the expected type) 793 * 794 @SuppressWarnings("removal") 795 private Provider<S> loadProvider(ServiceProvider provider) { 796 Module module = provider.module(); 797 if (!module.canRead(service.getModule())) { 798 // module does not read the module with the service type 799 return null; 800 } 801 802 String cn = provider.providerName(); 803 Class<?> clazz = null; 804 if (acc == null) { 805 try { 806 clazz = Class.forName(module, cn); 807 } catch (LinkageError e) { 808 fail(service, "Unable to load " + cn, e); 809 } 810 } else { 811 PrivilegedExceptionAction<Class<?>> pa = () -> Class.forName(module, cn); 812 try { 813 clazz = AccessController.doPrivileged(pa); 814 } catch (Throwable x) { 815 if (x instanceof PrivilegedActionException) 816 x = x.getCause(); 817 fail(service, "Unable to load " + cn, x); 818 return null; 819 } 820 } 821 if (clazz == null) { 822 fail(service, "Provider " + cn + " not found"); 823 } 824 825 int mods = clazz.getModifiers(); 826 if (!Modifier.isPublic(mods)) { 827 fail(service, clazz + " is not public"); 828 } 829 830 // if provider in explicit module then check for static factory method 831 if (inExplicitModule(clazz)) { 832 Method factoryMethod = findStaticProviderMethod(clazz); 833 if (factoryMethod != null) { 834 Class<?> returnType = factoryMethod.getReturnType(); 835 if (!service.isAssignableFrom(returnType)) { 836 fail(service, factoryMethod + " return type not a subtype"); 837 } 838 839 @SuppressWarnings("unchecked") 840 Class<? extends S> type = (Class<? extends S>) returnType; 841 return new ProviderImpl<S>(service, type, factoryMethod, acc); 842 } 843 } 844 845 // no factory method so must be a subtype 846 if (!service.isAssignableFrom(clazz)) { 847 fail(service, clazz.getName() + " not a subtype"); 848 } 849 850 @SuppressWarnings("unchecked") 851 Class<? extends S> type = (Class<? extends S>) clazz; 852 @SuppressWarnings("unchecked") 853 Constructor<? extends S> ctor = (Constructor<? extends S> ) getConstructor(clazz); 854 return new ProviderImpl<S>(service, type, ctor, acc); 855 } 856 857 /* 858 * Implements lazy service provider lookup of service providers that 859 * are provided by modules in a module layer (or parent layers) 860 * 861 private final class LayerLookupIterator<T> 862 implements Iterator<Provider<T>> 863 { 864 Deque<ModuleLayer> stack = new ArrayDeque<>(); 865 Set<ModuleLayer> visited = new HashSet<>(); 866 Iterator<ServiceProvider> iterator; 867 868 Provider<T> nextProvider; 869 ServiceConfigurationError nextError; 870 871 LayerLookupIterator() { 872 visited.add(layer); 873 stack.push(layer); 874 } 875 876 private Iterator<ServiceProvider> providers(ModuleLayer layer) { 877 ServicesCatalog catalog = LANG_ACCESS.getServicesCatalog(layer); 878 return catalog.findServices(serviceName).iterator(); 879 } 880 881 @Override 882 public boolean hasNext() { 883 while (nextProvider == null && nextError == null) { 884 // get next provider to load 885 while (iterator == null || !iterator.hasNext()) { 886 // next layer (DFS order) 887 if (stack.isEmpty()) 888 return false; 889 890 ModuleLayer layer = stack.pop(); 891 List<ModuleLayer> parents = layer.parents(); 892 for (int i = parents.size() - 1; i >= 0; i--) { 893 ModuleLayer parent = parents.get(i); 894 if (visited.add(parent)) { 895 stack.push(parent); 896 } 897 } 898 iterator = providers(layer); 899 } 900 901 // attempt to load provider 902 ServiceProvider provider = iterator.next(); 903 try { 904 @SuppressWarnings("unchecked") 905 Provider<T> next = (Provider<T>) loadProvider(provider); 906 nextProvider = next; 907 } catch (ServiceConfigurationError e) { 908 nextError = e; 909 } 910 } 911 return true; 912 } 913 914 @Override 915 public Provider<T> next() { 916 if (!hasNext()) 917 throw new NoSuchElementException(); 918 919 Provider<T> provider = nextProvider; 920 if (provider != null) { 921 nextProvider = null; 922 return provider; 923 } else { 924 ServiceConfigurationError e = nextError; 925 assert e != null; 926 nextError = null; 927 throw e; 928 } 929 } 930 } 931 932 /* 933 * Implements lazy service provider lookup of service providers that 934 * are provided by modules defined to a class loader or to modules in 935 * layers with a module defined to the class loader. 936 * 937 private final class ModuleServicesLookupIterator<T> 938 implements Iterator<Provider<T>> 939 { 940 ClassLoader currentLoader; 941 Iterator<ServiceProvider> iterator; 942 943 Provider<T> nextProvider; 944 ServiceConfigurationError nextError; 945 946 ModuleServicesLookupIterator() { 947 this.currentLoader = loader; 948 this.iterator = iteratorFor(loader); 949 } 950 951 /** 952 * Returns iterator to iterate over the implementations of {@code 953 * service} in the given layer. 954 * 955 private List<ServiceProvider> providers(ModuleLayer layer) { 956 ServicesCatalog catalog = LANG_ACCESS.getServicesCatalog(layer); 957 return catalog.findServices(serviceName); 958 } 959 960 /** 961 * Returns the class loader that a module is defined to 962 * 963 @SuppressWarnings("removal") 964 private ClassLoader loaderFor(Module module) { 965 SecurityManager sm = System.getSecurityManager(); 966 if (sm == null) { 967 return module.getClassLoader(); 968 } else { 969 PrivilegedAction<ClassLoader> pa = module::getClassLoader; 970 return AccessController.doPrivileged(pa); 971 } 972 } 973 974 /** 975 * Returns an iterator to iterate over the implementations of {@code 976 * service} in modules defined to the given class loader or in custom 977 * layers with a module defined to this class loader. 978 * 979 private Iterator<ServiceProvider> iteratorFor(ClassLoader loader) { 980 // modules defined to the class loader 981 ServicesCatalog catalog; 982 if (loader == null) { 983 catalog = BootLoader.getServicesCatalog(); 984 } else { 985 catalog = ServicesCatalog.getServicesCatalogOrNull(loader); 986 } 987 List<ServiceProvider> providers; 988 if (catalog == null) { 989 providers = List.of(); 990 } else { 991 providers = catalog.findServices(serviceName); 992 } 993 994 // modules in layers that define modules to the class loader 995 ClassLoader platformClassLoader = ClassLoaders.platformClassLoader(); 996 if (loader == null || loader == platformClassLoader) { 997 return providers.iterator(); 998 } else { 999 List<ServiceProvider> allProviders = new ArrayList<>(providers); 1000 Iterator<ModuleLayer> iterator = LANG_ACCESS.layers(loader).iterator(); 1001 while (iterator.hasNext()) { 1002 ModuleLayer layer = iterator.next(); 1003 for (ServiceProvider sp : providers(layer)) { 1004 ClassLoader l = loaderFor(sp.module()); 1005 if (l != null && l != platformClassLoader) { 1006 allProviders.add(sp); 1007 } 1008 } 1009 } 1010 return allProviders.iterator(); 1011 } 1012 } 1013 1014 @Override 1015 public boolean hasNext() { 1016 while (nextProvider == null && nextError == null) { 1017 // get next provider to load 1018 while (!iterator.hasNext()) { 1019 if (currentLoader == null) { 1020 return false; 1021 } else { 1022 currentLoader = currentLoader.getParent(); 1023 iterator = iteratorFor(currentLoader); 1024 } 1025 } 1026 1027 // attempt to load provider 1028 ServiceProvider provider = iterator.next(); 1029 try { 1030 @SuppressWarnings("unchecked") 1031 Provider<T> next = (Provider<T>) loadProvider(provider); 1032 nextProvider = next; 1033 } catch (ServiceConfigurationError e) { 1034 nextError = e; 1035 } 1036 } 1037 return true; 1038 } 1039 1040 @Override 1041 public Provider<T> next() { 1042 if (!hasNext()) 1043 throw new NoSuchElementException(); 1044 1045 Provider<T> provider = nextProvider; 1046 if (provider != null) { 1047 nextProvider = null; 1048 return provider; 1049 } else { 1050 ServiceConfigurationError e = nextError; 1051 assert e != null; 1052 nextError = null; 1053 throw e; 1054 } 1055 } 1056 } 1057 */ 1058 // END Android-removed: JPMS is not supported. 1059 1060 /** 1061 * Implements lazy service provider lookup where the service providers are 1062 * configured via service configuration files. Service providers in named 1063 * modules are silently ignored by this lookup iterator. 1064 */ 1065 private final class LazyClassPathLookupIterator<T> 1066 implements Iterator<Provider<T>> 1067 { 1068 static final String PREFIX = "META-INF/services/"; 1069 1070 Set<String> providerNames = new HashSet<>(); // to avoid duplicates 1071 Enumeration<URL> configs; 1072 Iterator<String> pending; 1073 1074 Provider<T> nextProvider; 1075 ServiceConfigurationError nextError; 1076 LazyClassPathLookupIterator()1077 LazyClassPathLookupIterator() { } 1078 1079 /** 1080 * Parse a single line from the given configuration file, adding the 1081 * name on the line to set of names if not already seen. 1082 */ parseLine(URL u, BufferedReader r, int lc, Set<String> names)1083 private int parseLine(URL u, BufferedReader r, int lc, Set<String> names) 1084 throws IOException 1085 { 1086 String ln = r.readLine(); 1087 if (ln == null) { 1088 return -1; 1089 } 1090 int ci = ln.indexOf('#'); 1091 if (ci >= 0) ln = ln.substring(0, ci); 1092 ln = ln.trim(); 1093 int n = ln.length(); 1094 if (n != 0) { 1095 if ((ln.indexOf(' ') >= 0) || (ln.indexOf('\t') >= 0)) 1096 fail(service, u, lc, "Illegal configuration-file syntax"); 1097 int cp = ln.codePointAt(0); 1098 if (!Character.isJavaIdentifierStart(cp)) 1099 fail(service, u, lc, "Illegal provider-class name: " + ln); 1100 int start = Character.charCount(cp); 1101 for (int i = start; i < n; i += Character.charCount(cp)) { 1102 cp = ln.codePointAt(i); 1103 if (!Character.isJavaIdentifierPart(cp) && (cp != '.')) 1104 fail(service, u, lc, "Illegal provider-class name: " + ln); 1105 } 1106 if (providerNames.add(ln)) { 1107 names.add(ln); 1108 } 1109 } 1110 return lc + 1; 1111 } 1112 1113 /** 1114 * Parse the content of the given URL as a provider-configuration file. 1115 */ parse(URL u)1116 private Iterator<String> parse(URL u) { 1117 Set<String> names = new LinkedHashSet<>(); // preserve insertion order 1118 try { 1119 URLConnection uc = u.openConnection(); 1120 uc.setUseCaches(false); 1121 try (InputStream in = uc.getInputStream(); 1122 BufferedReader r 1123 // = new BufferedReader(new InputStreamReader(in, UTF_8.INSTANCE))) 1124 = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8))) 1125 { 1126 int lc = 1; 1127 while ((lc = parseLine(u, r, lc, names)) >= 0); 1128 } 1129 } catch (IOException x) { 1130 fail(service, "Error accessing configuration file", x); 1131 } 1132 return names.iterator(); 1133 } 1134 1135 /** 1136 * Loads and returns the next provider class. 1137 */ nextProviderClass()1138 private Class<?> nextProviderClass() { 1139 if (configs == null) { 1140 try { 1141 String fullName = PREFIX + service.getName(); 1142 if (loader == null) { 1143 configs = ClassLoader.getSystemResources(fullName); 1144 // Android-removed: platformClassLoader not available on Android. 1145 // There were no changes in ClassLoaders, keeping old behaviour. 1146 /* 1147 } else if (loader == ClassLoaders.platformClassLoader()) { 1148 // The platform classloader doesn't have a class path, 1149 // but the boot loader might. 1150 if (BootLoader.hasClassPath()) { 1151 configs = BootLoader.findResources(fullName); 1152 } else { 1153 configs = Collections.emptyEnumeration(); 1154 } 1155 */ 1156 } else { 1157 configs = loader.getResources(fullName); 1158 } 1159 } catch (IOException x) { 1160 fail(service, "Error locating configuration files", x); 1161 } 1162 } 1163 while ((pending == null) || !pending.hasNext()) { 1164 if (!configs.hasMoreElements()) { 1165 return null; 1166 } 1167 pending = parse(configs.nextElement()); 1168 } 1169 String cn = pending.next(); 1170 try { 1171 return Class.forName(cn, false, loader); 1172 } catch (ClassNotFoundException x) { 1173 // Android-changed: let the ServiceConfigurationError have a cause. 1174 // fail(service, "Provider " + cn + " not found"); 1175 fail(service, "Provider " + cn + " not found", x); 1176 return null; 1177 } 1178 } 1179 1180 @SuppressWarnings("unchecked") hasNextService()1181 private boolean hasNextService() { 1182 while (nextProvider == null && nextError == null) { 1183 try { 1184 Class<?> clazz = nextProviderClass(); 1185 if (clazz == null) 1186 return false; 1187 1188 // Android-removed: JPMS is not available on Android. 1189 /* 1190 if (clazz.getModule().isNamed()) { 1191 // ignore class if in named module 1192 continue; 1193 } 1194 */ 1195 1196 if (service.isAssignableFrom(clazz)) { 1197 Class<? extends S> type = (Class<? extends S>) clazz; 1198 Constructor<? extends S> ctor 1199 = (Constructor<? extends S>)getConstructor(clazz); 1200 // Android-changed: do not use legacy security code. 1201 // ProviderImpl<S> p = new ProviderImpl<S>(service, type, ctor, acc); 1202 ProviderImpl<S> p = new ProviderImpl<S>(service, type, ctor); 1203 nextProvider = (ProviderImpl<T>) p; 1204 } else { 1205 // Android-changed: Let the ServiceConfigurationError have a cause. 1206 // fail(service, clazz.getName() + " not a subtype"); 1207 ClassCastException cce = new ClassCastException( 1208 service.getCanonicalName() + " is not assignable from " + clazz.getCanonicalName()); 1209 fail(service, clazz.getName() + " not a subtype", cce); 1210 } 1211 } catch (ServiceConfigurationError e) { 1212 nextError = e; 1213 } 1214 } 1215 return true; 1216 } 1217 nextService()1218 private Provider<T> nextService() { 1219 if (!hasNextService()) 1220 throw new NoSuchElementException(); 1221 Provider<T> provider = nextProvider; 1222 if (provider != null) { 1223 nextProvider = null; 1224 return provider; 1225 } else { 1226 ServiceConfigurationError e = nextError; 1227 assert e != null; 1228 nextError = null; 1229 throw e; 1230 } 1231 } 1232 1233 @SuppressWarnings("removal") 1234 @Override hasNext()1235 public boolean hasNext() { 1236 // Android-changed: do not use legacy security code 1237 /* if (acc == null) { */ 1238 return hasNextService(); 1239 /* 1240 } else { 1241 PrivilegedAction<Boolean> action = new PrivilegedAction<>() { 1242 public Boolean run() { return hasNextService(); } 1243 }; 1244 return AccessController.doPrivileged(action, acc); 1245 } 1246 */ 1247 } 1248 1249 @SuppressWarnings("removal") 1250 @Override next()1251 public Provider<T> next() { 1252 // Android-changed: do not use legacy security code 1253 // if (acc == null) { 1254 return nextService(); 1255 /* 1256 } else { 1257 PrivilegedAction<Provider<T>> action = new PrivilegedAction<>() { 1258 public Provider<T> run() { return nextService(); } 1259 }; 1260 return AccessController.doPrivileged(action, acc); 1261 } 1262 */ 1263 } 1264 } 1265 1266 /** 1267 * Returns a new lookup iterator. 1268 */ newLookupIterator()1269 private Iterator<Provider<S>> newLookupIterator() { 1270 // Android-changed: JPMS is not supported, so there are no service defined in modules. 1271 /* 1272 assert layer == null || loader == null; 1273 if (layer != null) { 1274 return new LayerLookupIterator<>(); 1275 } else { 1276 Iterator<Provider<S>> first = new ModuleServicesLookupIterator<>(); 1277 Iterator<Provider<S>> second = new LazyClassPathLookupIterator<>(); 1278 return new Iterator<Provider<S>>() { 1279 @Override 1280 public boolean hasNext() { 1281 return (first.hasNext() || second.hasNext()); 1282 } 1283 @Override 1284 public Provider<S> next() { 1285 if (first.hasNext()) { 1286 return first.next(); 1287 } else if (second.hasNext()) { 1288 return second.next(); 1289 } else { 1290 throw new NoSuchElementException(); 1291 } 1292 } 1293 }; 1294 } 1295 */ 1296 return new LazyClassPathLookupIterator<>(); 1297 } 1298 1299 /** 1300 * Returns an iterator to lazily load and instantiate the available 1301 * providers of this loader's service. 1302 * 1303 * <p> To achieve laziness the actual work of locating and instantiating 1304 * providers is done by the iterator itself. Its {@link Iterator#hasNext 1305 * hasNext} and {@link Iterator#next next} methods can therefore throw a 1306 * {@link ServiceConfigurationError} for any of the reasons specified in 1307 * the <a href="#errors">Errors</a> section above. To write robust code it 1308 * is only necessary to catch {@code ServiceConfigurationError} when using 1309 * the iterator. If an error is thrown then subsequent invocations of the 1310 * iterator will make a best effort to locate and instantiate the next 1311 * available provider, but in general such recovery cannot be guaranteed. 1312 * 1313 * <p> Caching: The iterator returned by this method first yields all of 1314 * the elements of the provider cache, in the order that they were loaded. 1315 * It then lazily loads and instantiates any remaining service providers, 1316 * adding each one to the cache in turn. If this loader's provider caches are 1317 * cleared by invoking the {@link #reload() reload} method then existing 1318 * iterators for this service loader should be discarded. 1319 * The {@code hasNext} and {@code next} methods of the iterator throw {@link 1320 * java.util.ConcurrentModificationException ConcurrentModificationException} 1321 * if used after the provider cache has been cleared. 1322 * 1323 * <p> The iterator returned by this method does not support removal. 1324 * Invoking its {@link java.util.Iterator#remove() remove} method will 1325 * cause an {@link UnsupportedOperationException} to be thrown. 1326 * 1327 * @apiNote Throwing an error in these cases may seem extreme. The rationale 1328 * for this behavior is that a malformed provider-configuration file, like a 1329 * malformed class file, indicates a serious problem with the way the Java 1330 * virtual machine is configured or is being used. As such it is preferable 1331 * to throw an error rather than try to recover or, even worse, fail silently. 1332 * 1333 * @return An iterator that lazily loads providers for this loader's 1334 * service 1335 * 1336 * @revised 9 1337 */ iterator()1338 public Iterator<S> iterator() { 1339 1340 // create lookup iterator if needed 1341 if (lookupIterator1 == null) { 1342 lookupIterator1 = newLookupIterator(); 1343 } 1344 1345 return new Iterator<S>() { 1346 1347 // record reload count 1348 final int expectedReloadCount = ServiceLoader.this.reloadCount; 1349 1350 // index into the cached providers list 1351 int index; 1352 1353 /** 1354 * Throws ConcurrentModificationException if the list of cached 1355 * providers has been cleared by reload. 1356 */ 1357 private void checkReloadCount() { 1358 if (ServiceLoader.this.reloadCount != expectedReloadCount) 1359 throw new ConcurrentModificationException(); 1360 } 1361 1362 @Override 1363 public boolean hasNext() { 1364 checkReloadCount(); 1365 if (index < instantiatedProviders.size()) 1366 return true; 1367 return lookupIterator1.hasNext(); 1368 } 1369 1370 @Override 1371 public S next() { 1372 checkReloadCount(); 1373 S next; 1374 if (index < instantiatedProviders.size()) { 1375 next = instantiatedProviders.get(index); 1376 } else { 1377 next = lookupIterator1.next().get(); 1378 instantiatedProviders.add(next); 1379 } 1380 index++; 1381 return next; 1382 } 1383 1384 }; 1385 } 1386 1387 /** 1388 * Returns a stream to lazily load available providers of this loader's 1389 * service. The stream elements are of type {@link Provider Provider}, the 1390 * {@code Provider}'s {@link Provider#get() get} method must be invoked to 1391 * get or instantiate the provider. 1392 * 1393 * <p> To achieve laziness the actual work of locating providers is done 1394 * when processing the stream. If a service provider cannot be loaded for any 1395 * of the reasons specified in the <a href="#errors">Errors</a> section 1396 * above then {@link ServiceConfigurationError} is thrown by whatever method 1397 * caused the service provider to be loaded. </p> 1398 * 1399 * <p> Caching: When processing the stream then providers that were previously 1400 * loaded by stream operations are processed first, in load order. It then 1401 * lazily loads any remaining service providers. If this loader's provider 1402 * caches are cleared by invoking the {@link #reload() reload} method then 1403 * existing streams for this service loader should be discarded. The returned 1404 * stream's source {@link Spliterator spliterator} is <em>fail-fast</em> and 1405 * will throw {@link ConcurrentModificationException} if the provider cache 1406 * has been cleared. </p> 1407 * 1408 * <p> The following examples demonstrate usage. The first example creates 1409 * a stream of {@code CodecFactory} objects, the second example is the same 1410 * except that it sorts the providers by provider class name (and so locate 1411 * all providers). 1412 * <pre>{@code 1413 * Stream<CodecFactory> providers = ServiceLoader.load(CodecFactory.class) 1414 * .stream() 1415 * .map(Provider::get); 1416 * 1417 * Stream<CodecFactory> providers = ServiceLoader.load(CodecFactory.class) 1418 * .stream() 1419 * .sorted(Comparator.comparing(p -> p.type().getName())) 1420 * .map(Provider::get); 1421 * }</pre> 1422 * 1423 * @return A stream that lazily loads providers for this loader's service 1424 * 1425 * @since 9 1426 */ stream()1427 public Stream<Provider<S>> stream() { 1428 // use cached providers as the source when all providers loaded 1429 if (loadedAllProviders) { 1430 return loadedProviders.stream(); 1431 } 1432 1433 // create lookup iterator if needed 1434 if (lookupIterator2 == null) { 1435 lookupIterator2 = newLookupIterator(); 1436 } 1437 1438 // use lookup iterator and cached providers as source 1439 Spliterator<Provider<S>> s = new ProviderSpliterator<>(lookupIterator2); 1440 return StreamSupport.stream(s, false); 1441 } 1442 1443 private class ProviderSpliterator<T> implements Spliterator<Provider<T>> { 1444 final int expectedReloadCount = ServiceLoader.this.reloadCount; 1445 final Iterator<Provider<T>> iterator; 1446 int index; 1447 ProviderSpliterator(Iterator<Provider<T>> iterator)1448 ProviderSpliterator(Iterator<Provider<T>> iterator) { 1449 this.iterator = iterator; 1450 } 1451 1452 @Override trySplit()1453 public Spliterator<Provider<T>> trySplit() { 1454 return null; 1455 } 1456 1457 @Override 1458 @SuppressWarnings("unchecked") tryAdvance(Consumer<? super Provider<T>> action)1459 public boolean tryAdvance(Consumer<? super Provider<T>> action) { 1460 if (ServiceLoader.this.reloadCount != expectedReloadCount) 1461 throw new ConcurrentModificationException(); 1462 Provider<T> next = null; 1463 if (index < loadedProviders.size()) { 1464 next = (Provider<T>) loadedProviders.get(index++); 1465 } else if (iterator.hasNext()) { 1466 next = iterator.next(); 1467 loadedProviders.add((Provider<S>)next); 1468 index++; 1469 } else { 1470 loadedAllProviders = true; 1471 } 1472 if (next != null) { 1473 action.accept(next); 1474 return true; 1475 } else { 1476 return false; 1477 } 1478 } 1479 1480 @Override characteristics()1481 public int characteristics() { 1482 // not IMMUTABLE as structural interference possible 1483 // not NOTNULL so that the characteristics are a subset of the 1484 // characteristics when all Providers have been located. 1485 return Spliterator.ORDERED; 1486 } 1487 1488 @Override estimateSize()1489 public long estimateSize() { 1490 return Long.MAX_VALUE; 1491 } 1492 } 1493 1494 // Android-removed: JPMS is not supported. 1495 /* 1496 * Creates a new service loader for the given service type, class 1497 * loader, and caller. 1498 * 1499 * @param <S> the class of the service type 1500 * 1501 * @param service 1502 * The interface or abstract class representing the service 1503 * 1504 * @param loader 1505 * The class loader to be used to load provider-configuration files 1506 * and provider classes, or {@code null} if the system class 1507 * loader (or, failing that, the bootstrap class loader) is to be 1508 * used 1509 * 1510 * @param callerModule 1511 * The caller's module for which a new service loader is created 1512 * 1513 * @return A new service loader 1514 * 1515 static <S> ServiceLoader<S> load(Class<S> service, 1516 ClassLoader loader, 1517 Module callerModule) 1518 { 1519 return new ServiceLoader<>(callerModule, service, loader); 1520 } 1521 */ 1522 1523 // Android-changed: removed module mentions. 1524 /** 1525 * Creates a new service loader for the given service. The service loader 1526 * uses the given class loader as the starting point to locate service 1527 * providers for the service. 1528 * 1529 * @apiNote If the class path of the class loader includes remote network 1530 * URLs then those URLs may be dereferenced in the process of searching for 1531 * provider-configuration files. 1532 * 1533 * <p> This activity is normal, although it may cause puzzling entries to be 1534 * created in web-server logs. If a web server is not configured correctly, 1535 * however, then this activity may cause the provider-loading algorithm to fail 1536 * spuriously. 1537 * 1538 * <p> A web server should return an HTTP 404 (Not Found) response when a 1539 * requested resource does not exist. Sometimes, however, web servers are 1540 * erroneously configured to return an HTTP 200 (OK) response along with a 1541 * helpful HTML error page in such cases. This will cause a {@link 1542 * ServiceConfigurationError} to be thrown when this class attempts to parse 1543 * the HTML page as a provider-configuration file. The best solution to this 1544 * problem is to fix the misconfigured web server to return the correct 1545 * response code (HTTP 404) along with the HTML error page. 1546 * 1547 * @param <S> the class of the service type 1548 * 1549 * @param service 1550 * The interface or abstract class representing the service 1551 * 1552 * @param loader 1553 * The class loader to be used to load provider-configuration files 1554 * and provider classes, or {@code null} if the system class 1555 * loader (or, failing that, the bootstrap class loader) is to be 1556 * used 1557 * 1558 * @return A new service loader 1559 * 1560 * @throws ServiceConfigurationError 1561 * if the service type is not accessible to the caller <!-- or the 1562 * caller is in an explicit module and its module descriptor does 1563 * not declare that it uses {@code service} --/> 1564 * 1565 * @revised 9 1566 */ 1567 @CallerSensitive load(Class<S> service, ClassLoader loader)1568 public static <S> ServiceLoader<S> load(Class<S> service, 1569 ClassLoader loader) 1570 { 1571 return new ServiceLoader<>(Reflection.getCallerClass(), service, loader); 1572 } 1573 1574 // Android-changed: removed module mentions. 1575 /** 1576 * Creates a new service loader for the given service type, using the 1577 * current thread's {@linkplain java.lang.Thread#getContextClassLoader 1578 * context class loader}. 1579 * 1580 * <p> An invocation of this convenience method of the form 1581 * <pre>{@code 1582 * ServiceLoader.load(service) 1583 * }</pre> 1584 * 1585 * is equivalent to 1586 * 1587 * <pre>{@code 1588 * ServiceLoader.load(service, Thread.currentThread().getContextClassLoader()) 1589 * }</pre> 1590 * 1591 * @apiNote Service loader objects obtained with this method should not be 1592 * cached VM-wide. For example, different applications in the same VM may 1593 * have different thread context class loaders. A lookup by one application 1594 * may locate a service provider that is only visible via its thread 1595 * context class loader and so is not suitable to be located by the other 1596 * application. Memory leaks can also arise. A thread local may be suited 1597 * to some applications. 1598 * 1599 * @param <S> the class of the service type 1600 * 1601 * @param service 1602 * The interface or abstract class representing the service 1603 * 1604 * @return A new service loader 1605 * 1606 * @throws ServiceConfigurationError 1607 * if the service type is not accessible to the caller 1608 * 1609 * @revised 9 1610 */ 1611 @CallerSensitive load(Class<S> service)1612 public static <S> ServiceLoader<S> load(Class<S> service) { 1613 ClassLoader cl = Thread.currentThread().getContextClassLoader(); 1614 return new ServiceLoader<>(Reflection.getCallerClass(), service, cl); 1615 } 1616 1617 // Android-changed: module and platformClassLoader mentions removed. 1618 /** 1619 * Creates a new service loader for the given service type, using the 1620 * extension class loader. 1621 * 1622 * <p>This convenience method simply locates the extension class loader, 1623 * call it {@code extClassLoader}, and then returns 1624 * 1625 * <pre>{@code 1626 * ServiceLoader.load(service, extClassLoader) 1627 * }</pre> 1628 * 1629 * <p> This method is intended for use when only installed providers are 1630 * desired. The resulting service will only find and load providers that 1631 * have been installed into the current Java virtual machine. 1632 * 1633 * @param <S> the class of the service type 1634 * 1635 * @param service 1636 * The interface or abstract class representing the service 1637 * 1638 * @return A new service loader 1639 * 1640 * @throws ServiceConfigurationError 1641 * if the service type is not accessible to the caller 1642 * 1643 * @revised 9 1644 */ 1645 @CallerSensitive loadInstalled(Class<S> service)1646 public static <S> ServiceLoader<S> loadInstalled(Class<S> service) { 1647 // Android-changed: there is no platformClassLoader, using extension classloader. 1648 // ClassLoader cl = ClassLoader.getPlatformClassLoader(); 1649 ClassLoader cl = ClassLoader.getSystemClassLoader(); 1650 ClassLoader prev = null; 1651 while (cl != null) { 1652 prev = cl; 1653 cl = cl.getParent(); 1654 } 1655 return new ServiceLoader<>(Reflection.getCallerClass(), service, prev); 1656 } 1657 1658 // Android-removed: JPMS is not supported. 1659 /* 1660 * Creates a new service loader for the given service type to load service 1661 * providers from modules in the given module layer and its ancestors. It 1662 * does not locate providers in unnamed modules. The ordering that the service 1663 * loader's {@link #iterator() iterator} and {@link #stream() stream} locate 1664 * providers and yield elements is as follows: 1665 * 1666 * <ul> 1667 * <li><p> Providers are located in a module layer before locating providers 1668 * in parent layers. Traversal of parent layers is depth-first with each 1669 * layer visited at most once. For example, suppose L0 is the boot layer, L1 1670 * and L2 are modules layers with L0 as their parent. Now suppose that L3 is 1671 * created with L1 and L2 as the parents (in that order). Using a service 1672 * loader to locate providers with L3 as the context will locate providers 1673 * in the following order: L3, L1, L0, L2. </p></li> 1674 * 1675 * <li><p> If a module declares more than one provider then the providers 1676 * are located in the order that its module descriptor 1677 * {@linkplain java.lang.module.ModuleDescriptor.Provides#providers() 1678 * lists the providers}. Providers added dynamically by instrumentation 1679 * agents are always located after providers declared by the module. </p></li> 1680 * 1681 * <li><p> The ordering of modules in a module layer is not defined. </p></li> 1682 * </ul> 1683 * 1684 * @apiNote Unlike the other load methods defined here, the service type 1685 * is the second parameter. The reason for this is to avoid source 1686 * compatibility issues for code that uses {@code load(S, null)}. 1687 * 1688 * @param <S> the class of the service type 1689 * 1690 * @param layer 1691 * The module layer 1692 * 1693 * @param service 1694 * The interface or abstract class representing the service 1695 * 1696 * @return A new service loader 1697 * 1698 * @throws ServiceConfigurationError 1699 * if the service type is not accessible to the caller or the 1700 * caller is in an explicit module and its module descriptor does 1701 * not declare that it uses {@code service} 1702 * 1703 * @since 9 1704 * 1705 @CallerSensitive 1706 public static <S> ServiceLoader<S> load(ModuleLayer layer, Class<S> service) { 1707 return new ServiceLoader<>(Reflection.getCallerClass(), layer, service); 1708 } 1709 */ 1710 1711 /** 1712 * Load the first available service provider of this loader's service. This 1713 * convenience method is equivalent to invoking the {@link #iterator() 1714 * iterator()} method and obtaining the first element. It therefore 1715 * returns the first element from the provider cache if possible, it 1716 * otherwise attempts to load and instantiate the first provider. 1717 * 1718 * <p> The following example loads the first available service provider. If 1719 * no service providers are located then it uses a default implementation. 1720 * <pre>{@code 1721 * CodecFactory factory = ServiceLoader.load(CodecFactory.class) 1722 * .findFirst() 1723 * .orElse(DEFAULT_CODECSET_FACTORY); 1724 * }</pre> 1725 * @return The first service provider or empty {@code Optional} if no 1726 * service providers are located 1727 * 1728 * @throws ServiceConfigurationError 1729 * If a provider class cannot be loaded for any of the reasons 1730 * specified in the <a href="#errors">Errors</a> section above. 1731 * 1732 * @since 9 1733 */ findFirst()1734 public Optional<S> findFirst() { 1735 Iterator<S> iterator = iterator(); 1736 if (iterator.hasNext()) { 1737 return Optional.of(iterator.next()); 1738 } else { 1739 return Optional.empty(); 1740 } 1741 } 1742 1743 /** 1744 * Clear this loader's provider cache so that all providers will be 1745 * reloaded. 1746 * 1747 * <p> After invoking this method, subsequent invocations of the {@link 1748 * #iterator() iterator} or {@link #stream() stream} methods will lazily 1749 * locate providers (and instantiate in the case of {@code iterator}) 1750 * from scratch, just as is done by a newly-created service loader. 1751 * 1752 * <p> This method is intended for use in situations in which new service 1753 * providers can be installed into a running Java virtual machine. 1754 */ reload()1755 public void reload() { 1756 lookupIterator1 = null; 1757 instantiatedProviders.clear(); 1758 1759 lookupIterator2 = null; 1760 loadedProviders.clear(); 1761 loadedAllProviders = false; 1762 1763 // increment count to allow CME be thrown 1764 reloadCount++; 1765 } 1766 1767 // BEGIN Android-added: loadFromSystemProperty(), for internal use. 1768 // Instantiates a class from a system property (used elsewhere in libcore). 1769 /** 1770 * Internal API to support built-in SPIs that check a system property first. 1771 * Returns an instance specified by a property with the class' binary name, or null if 1772 * no such property is set. 1773 * @hide 1774 */ loadFromSystemProperty(final Class<S> service)1775 public static <S> S loadFromSystemProperty(final Class<S> service) { 1776 try { 1777 final String className = System.getProperty(service.getName()); 1778 if (className != null) { 1779 Class<?> c = ClassLoader.getSystemClassLoader().loadClass(className); 1780 return (S) c.newInstance(); 1781 } 1782 return null; 1783 } catch (Exception e) { 1784 throw new Error(e); 1785 } 1786 } 1787 // END Android-added: loadFromSystemProperty(), for internal use. 1788 1789 /** 1790 * Returns a string describing this service. 1791 * 1792 * @return A descriptive string 1793 */ toString()1794 public String toString() { 1795 return "java.util.ServiceLoader[" + service.getName() + "]"; 1796 } 1797 1798 } 1799