下面列出了java.util.ServiceLoader.Provider#java.util.ServiceLoader 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private HashMap<String, ModelServerEndpoint> getEndpoints(EndpointTypes type)
throws InvalidPluginException {
ServiceLoader<ModelServerEndpoint> loader = ServiceLoader.load(ModelServerEndpoint.class);
HashMap<String, ModelServerEndpoint> ep = new HashMap<>();
for (ModelServerEndpoint mep : loader) {
Class<? extends ModelServerEndpoint> modelServerEndpointClassObj = mep.getClass();
Annotation[] annotations = modelServerEndpointClassObj.getAnnotations();
for (Annotation a : annotations) {
if (validateEndpointPlugin(a, type)) {
if (ep.get(((Endpoint) a).urlPattern()) != null) {
throw new InvalidPluginException(
"Multiple plugins found for endpoint "
+ "\""
+ ((Endpoint) a).urlPattern()
+ "\"");
}
logger.info("Loading plugin for endpoint {}", ((Endpoint) a).urlPattern());
ep.put(((Endpoint) a).urlPattern(), mep);
}
}
}
return ep;
}
public NameService run() {
Iterator<NameServiceDescriptor> itr =
ServiceLoader.load(NameServiceDescriptor.class)
.iterator();
while (itr.hasNext()) {
NameServiceDescriptor nsd = itr.next();
if (providerName.
equalsIgnoreCase(nsd.getType()+","
+nsd.getProviderName())) {
try {
return nsd.createNameService();
} catch (Exception e) {
e.printStackTrace();
System.err.println(
"Cannot create name service:"
+providerName+": " + e);
}
}
}
return null;
}
EngineImpl(Map<String, SectionHelperFactory<?>> sectionHelperFactories, List<ValueResolver> valueResolvers,
List<NamespaceResolver> namespaceResolvers, List<TemplateLocator> locators,
List<ResultMapper> resultMappers, Function<String, SectionHelperFactory<?>> sectionHelperFunc,
List<ParserHook> parserHooks) {
this.sectionHelperFactories = Collections.unmodifiableMap(new HashMap<>(sectionHelperFactories));
this.valueResolvers = sort(valueResolvers);
this.namespaceResolvers = ImmutableList.copyOf(namespaceResolvers);
this.evaluator = new EvaluatorImpl(this.valueResolvers);
this.templates = new ConcurrentHashMap<>();
this.locators = sort(locators);
ServiceLoader<PublisherFactory> loader = ServiceLoader.load(PublisherFactory.class);
Iterator<PublisherFactory> iterator = loader.iterator();
if (iterator.hasNext()) {
this.publisherFactory = iterator.next();
} else {
this.publisherFactory = null;
}
if (iterator.hasNext()) {
throw new IllegalStateException(
"Multiple reactive factories found: " + StreamSupport.stream(loader.spliterator(), false)
.map(Object::getClass).map(Class::getName).collect(Collectors.joining(",")));
}
this.resultMappers = sort(resultMappers);
this.sectionHelperFunc = sectionHelperFunc;
this.parserHooks = parserHooks;
}
/**
* Initialize a specific type
*
* @param type
* the initializer specific type, see
* {@link Initializer#initialize(Object)}
* @param classloader
* a specific class loader to use
*/
public static void initialize ( final Object type, final ClassLoader classloader )
{
logger.debug ( "Initializing: {}", type );
final ServiceLoader<Initializer> loader = ServiceLoader.load ( Initializer.class, classloader );
final Iterator<Initializer> i = loader.iterator ();
while ( i.hasNext () )
{
final Initializer initializer = i.next ();
logger.debug ( "Processing: {}", initializer );
try
{
initializer.initialize ( type );
}
catch ( final Exception e )
{
logger.info ( "Failed to initialize", e );
}
}
}
/**
* Test Module::addUses
*/
public void testAddUses() {
Module thisModule = Main.class.getModule();
assertFalse(thisModule.canUse(Service.class));
try {
ServiceLoader.load(Service.class);
assertTrue(false);
} catch (ServiceConfigurationError expected) { }
Module result = thisModule.addUses(Service.class);
assertTrue(result== thisModule);
assertTrue(thisModule.canUse(Service.class));
ServiceLoader.load(Service.class); // no exception
}
@Before
public void setUp() throws Exception {
ServiceLoader<DigitalObjectPlugin> pluginLoader = ServiceLoader.load(DigitalObjectPlugin.class);
config = AppConfigurationFactory.getInstance().create(new HashMap<String, String>() {{
put(AppConfiguration.PROPERTY_APP_HOME, temp.getRoot().getPath());
}});
MetaModelRepository.setInstance(
StreamSupport.stream(pluginLoader.spliterator(), false)
.map(digitalObjectPlugin -> digitalObjectPlugin.getId())
.toArray(String[]::new)
);
DigitalObjectManager.setDefault(new DigitalObjectManager(
config,
EasyMock.createNiceMock(ImportBatchManager.class),
remoteStorage,
MetaModelRepository.getInstance(),
EasyMock.createNiceMock(UserManager.class)));
}
private static void resolveLoggers() {
// NOTE: Here we cannot use {@code SpiLoader} directly because it depends on the RecordLog.
ServiceLoader<Logger> loggerLoader = ServiceLoader.load(Logger.class);
for (Logger logger : loggerLoader) {
LogTarget annotation = logger.getClass().getAnnotation(LogTarget.class);
if (annotation == null) {
continue;
}
String name = annotation.value();
// Load first encountered logger if multiple loggers are associated with the same name.
if (StringUtil.isNotBlank(name) && !LOGGER_MAP.containsKey(name)) {
LOGGER_MAP.put(name, logger);
System.out.println("Sentinel Logger SPI loaded for <" + name + ">: "
+ logger.getClass().getCanonicalName());
}
}
}
@Test
public void testDynamicClassLoaderService() throws MalformedURLException {
// this will check that the java service loader works on a classloader that is mutable
new JarRuntimeInfo((URL) null, null, null);
// given
ExtensibleUrlClassLoader urlClassLoader = new ExtensibleUrlClassLoader(new URL[0]);
// 2 comp installer
assertThat(ServiceLoader.load(ComponentInstaller.class, urlClassLoader),
IsIterableWithSize.<ComponentInstaller> iterableWithSize(2));
// when
urlClassLoader.addURL(new URL("mvn:org.talend.components/multiple-runtime-comp/0.18.0"));
// then
// 3 comp installer
assertThat(ServiceLoader.load(ComponentInstaller.class, urlClassLoader),
IsIterableWithSize.<ComponentInstaller> iterableWithSize(3));
}
/**
* Load the sorted and prototype SPI instance list for provided SPI interface.
*
* Note: each call return different instances, i.e. prototype instance, not singleton instance.
*
* @param clazz class of the SPI
* @param <T> SPI type
* @return sorted and different SPI instance list
* @since 1.7.2
*/
public static <T> List<T> loadPrototypeInstanceListSorted(Class<T> clazz) {
try {
// Not use SERVICE_LOADER_MAP, to make sure the instances loaded are different.
ServiceLoader<T> serviceLoader = ServiceLoaderUtil.getServiceLoader(clazz);
List<SpiOrderWrapper<T>> orderWrappers = new ArrayList<>();
for (T spi : serviceLoader) {
int order = SpiOrderResolver.resolveOrder(spi);
// Since SPI is lazy initialized in ServiceLoader, we use online sort algorithm here.
SpiOrderResolver.insertSorted(orderWrappers, spi, order);
RecordLog.debug("[SpiLoader] Found {} SPI: {} with order {}", clazz.getSimpleName(),
spi.getClass().getCanonicalName(), order);
}
List<T> list = new ArrayList<>(orderWrappers.size());
for (int i = 0; i < orderWrappers.size(); i++) {
list.add(orderWrappers.get(i).spi);
}
return list;
} catch (Throwable t) {
RecordLog.error("[SpiLoader] ERROR: loadPrototypeInstanceListSorted failed", t);
t.printStackTrace();
return new ArrayList<>();
}
}
@Override
public LoggingBackend run() {
final Iterator<LoggerFinder> iterator =
ServiceLoader.load(LoggerFinder.class, ClassLoader.getSystemClassLoader())
.iterator();
if (iterator.hasNext()) {
return LoggingBackend.CUSTOM; // Custom Logger Provider is registered
}
// No custom logger provider: we will be using the default
// backend.
final Iterator<DefaultLoggerFinder> iterator2 =
ServiceLoader.loadInstalled(DefaultLoggerFinder.class)
.iterator();
if (iterator2.hasNext()) {
// LoggingProviderImpl is registered. The default
// implementation is java.util.logging
String cname = System.getProperty("java.util.logging.config.class");
String fname = System.getProperty("java.util.logging.config.file");
return (cname != null || fname != null)
? LoggingBackend.JUL_WITH_CONFIG
: LoggingBackend.JUL_DEFAULT;
} else {
// SimpleConsoleLogger is used
return LoggingBackend.NONE;
}
}
@Test
void jvmOnlyInParentSpi() throws IOException {
final Predicate<String> parentClasses = name -> true;
try (final URLClassLoader parent =
new URLClassLoader(new URL[0], Thread.currentThread().getContextClassLoader());
final ConfigurableClassLoader loader = new ConfigurableClassLoader("test", new URL[0], parent,
parentClasses, parentClasses.negate(), new String[0], new String[] {
new File(System.getProperty("java.home")).toPath().toAbsolutePath().toString() })) {
// can be loaded cause in the JVM
assertTrue(ServiceLoader.load(FileSystemProvider.class, loader).iterator().hasNext());
// this is in the (test) classloader but not available to the classloader
final List<TestEngine> junitEngines = StreamSupport
.stream(ServiceLoader.load(TestEngine.class, loader).spliterator(), false)
.collect(toList());
assertTrue(junitEngines.isEmpty());
}
}
/**
* Configure the web application.
*
* @param webApplication the web application.
*/
@Override
public void configure(WebApplication webApplication) {
if (LOGGER.isLoggable(FINER)) {
LOGGER.log(FINER, "Starting ServletContainerInitializer processing");
}
ServiceLoader<ServletContainerInitializer> serviceLoader = ServiceLoader.load(
ServletContainerInitializer.class, webApplication.getClassLoader());
for (ServletContainerInitializer initializer : serviceLoader) {
if (LOGGER.isLoggable(FINE)) {
LOGGER.log(INFO, "Adding initializer: {0}", initializer.getClass().getName());
}
webApplication.addInitializer(initializer);
}
if (LOGGER.isLoggable(FINER)) {
LOGGER.log(FINER, "Finished ServletContainerInitializer processing");
}
}
public NameService run() {
Iterator<NameServiceDescriptor> itr =
ServiceLoader.load(NameServiceDescriptor.class)
.iterator();
while (itr.hasNext()) {
NameServiceDescriptor nsd = itr.next();
if (providerName.
equalsIgnoreCase(nsd.getType()+","
+nsd.getProviderName())) {
try {
return nsd.createNameService();
} catch (Exception e) {
e.printStackTrace();
System.err.println(
"Cannot create name service:"
+providerName+": " + e);
}
}
}
return null;
}
/**
* Load the first-found specific SPI instance
*
* @param clazz class of the SPI interface
* @param <T> SPI type
* @return the first specific SPI instance if exists, or else return null
* @since 1.7.0
*/
public static <T> T loadFirstInstance(Class<T> clazz) {
AssertUtil.notNull(clazz, "SPI class cannot be null");
try {
String key = clazz.getName();
// Not thread-safe, as it's expected to be resolved in a thread-safe context.
ServiceLoader<T> serviceLoader = SERVICE_LOADER_MAP.get(key);
if (serviceLoader == null) {
serviceLoader = ServiceLoaderUtil.getServiceLoader(clazz);
SERVICE_LOADER_MAP.put(key, serviceLoader);
}
Iterator<T> iterator = serviceLoader.iterator();
if (iterator.hasNext()) {
return iterator.next();
} else {
return null;
}
} catch (Throwable t) {
RecordLog.error("[SpiLoader] ERROR: loadFirstInstance failed", t);
t.printStackTrace();
return null;
}
}
private static boolean loadProviderAsService() {
Iterator<HttpServerProvider> i =
ServiceLoader.load(HttpServerProvider.class,
ClassLoader.getSystemClassLoader())
.iterator();
for (;;) {
try {
if (!i.hasNext())
return false;
provider = i.next();
return true;
} catch (ServiceConfigurationError sce) {
if (sce.getCause() instanceof SecurityException) {
// Ignore the security exception, try the next provider
continue;
}
throw sce;
}
}
}
private static Class<? extends TokenIdentifier>
getClassForIdentifier(Text kind) {
Class<? extends TokenIdentifier> cls = null;
synchronized (Token.class) {
if (tokenKindMap == null) {
tokenKindMap = Maps.newHashMap();
for (TokenIdentifier id : ServiceLoader.load(TokenIdentifier.class)) {
tokenKindMap.put(id.getKind(), id.getClass());
}
}
cls = tokenKindMap.get(kind);
}
if (cls == null) {
LOG.warn("Cannot find class for token kind " + kind);
return null;
}
return cls;
}
static AuthProvider load(Vertx vertx, JsonObject config) {
ServiceLoader<ShellAuth> loader = ServiceLoader.load(ShellAuth.class);
Iterator<ShellAuth> factories = loader.iterator();
while (factories.hasNext()) {
try {
// might fail to start (missing classes for example...
ShellAuth auth = factories.next();
if (auth != null) {
if (auth.provider().equals(config.getString("provider", ""))) {
return auth.create(vertx, config);
}
}
} catch (RuntimeException e) {
// continue...
}
}
throw new VertxException("Provider not found [" + config.getString("provider", "") + "] / check your classpath");
}
/**
* Invoke to find all services for given service type using specified class loader
*
* @param classLoader specified class loader
* @param serviceType given service type
* @return List of found services
*/
public static <T> List<T> load(ClassLoader classLoader, Class<T> serviceType) {
List<T> foundServices = new ArrayList<>();
Iterator<T> iterator = ServiceLoader.load(serviceType, classLoader).iterator();
while (checkHasNextSafely(iterator)) {
try {
T item = iterator.next();
foundServices.add(item);
LOGGER.debug(String.format("Found %s [%s]", serviceType.getSimpleName(), item.toString()));
} catch (ServiceConfigurationError e) {
LOGGER.trace("Can't find services using Java SPI", e);
LOGGER.error(e.getMessage());
}
}
return foundServices;
}
@Override
protected HttpClient createService(ClientConfiguration configuration) {
final HttpURLConnectionFactory connectionFactory = configuration.getHttpURLConnectionFactory();
final HttpClientImpl client = new HttpClientImpl(PlatformClient.getService(Gson.class), connectionFactory, configuration);
final ServiceLoader<RequestHandlerProvider> requestLoader = ServiceLoader.load(RequestHandlerProvider.class);
final Iterator<RequestHandlerProvider> requestIterator = requestLoader.iterator();
while (requestIterator.hasNext()) {
client.addRequestHandler(requestIterator.next().getHandler(configuration));
}
final ServiceLoader<ResponseHandlerProvider> responseLoader = ServiceLoader.load(ResponseHandlerProvider.class);
final Iterator<ResponseHandlerProvider> responseIterator = responseLoader.iterator();
while (responseIterator.hasNext()) {
client.addResponseHandler(responseIterator.next().getHandler(configuration));
}
return client;
}
private void locateRecoveryRegistry() {
if (registry == null) {
for (String locatorClasse : RESOURCE_RECOVERY_CLASS_NAMES) {
try {
ServiceLoader<ActiveMQRegistry> sl = ServiceLoader.load(ActiveMQRegistry.class);
if (sl.iterator().hasNext()) {
registry = sl.iterator().next();
}
} catch (Throwable e) {
ActiveMQJMSBridgeLogger.LOGGER.debug("unable to load recovery registry " + locatorClasse, e);
}
if (registry != null) {
break;
}
}
if (registry != null) {
ActiveMQJMSBridgeLogger.LOGGER.debug("Recovery Registry located = " + registry);
}
}
}
private static AsynchronousChannelProvider loadProviderAsService() {
ServiceLoader<AsynchronousChannelProvider> sl =
ServiceLoader.load(AsynchronousChannelProvider.class,
ClassLoader.getSystemClassLoader());
Iterator<AsynchronousChannelProvider> i = sl.iterator();
for (;;) {
try {
return (i.hasNext()) ? i.next() : null;
} catch (ServiceConfigurationError sce) {
if (sce.getCause() instanceof SecurityException) {
// Ignore the security exception, try the next provider
continue;
}
throw sce;
}
}
}
@Inject
public IKAnalyzerProvider(Index index, @IndexSettings Settings indexSettings, Environment env, @Assisted String name, @Assisted Settings settings) {
super(index, indexSettings, name, settings);
loader = ServiceLoader.load(Configuration.class);
Iterator<Configuration> iterator = loader.iterator();
if (!iterator.hasNext()) {
throw new NotFoundIKAnalyzerConfigurationImplementation();
}
analyzer = new IKAnalyzer(iterator.next().init(index, indexSettings, env, name, settings));
}
/**
* Description: <br>
*
* @author 王伟<br>
* @taskId <br>
* @return <br>
*/
private static TxConsumer getConsumer() {
if (txConsumer == null) {
ServiceLoader<TxConsumer> serviceLoader = ServiceLoader.load(TxConsumer.class);
Iterator<TxConsumer> iterator = serviceLoader.iterator();
if (iterator.hasNext()) {
txConsumer = iterator.next();
}
}
return txConsumer;
}
/**
* Uses SPI to find a {@link DataSourceFactory} with the requested name or
* {@code null} if one is not found.
*
* @param name the name of the class that implements the factory
* @return a {@link DataSourceFactory} for {@code name} or {@code null} if one
* is not found
*/
public static DataSourceFactory newFactory(String name) {
if (name == null) throw new IllegalArgumentException("DataSourceFactory name is null");
return ServiceLoader
.load(DataSourceFactory.class)
.stream()
.filter(p -> p.type().getName().equals(name))
.findFirst()
.map(Provider::get)
.orElse(null);
}
private static Set<String> getSupportedPackages() {
Set<String> result = new HashSet<>();
stream(ServiceLoader.load(ResourceFactoryConfig.class).spliterator(), false)
.map(config -> config.getSupportedPackages().stream()
.map(it -> it + ".")
.collect(Collectors.toSet()))
.forEach(result::addAll);
return result;
}
private static void loadAuthenticators(Map<String, ClientCredentialsProvider> authenticators, ClassLoader classLoader) {
Iterator<ClientCredentialsProvider> iterator = ServiceLoader.load(ClientCredentialsProvider.class, classLoader).iterator();
while (iterator.hasNext()) {
try {
ClientCredentialsProvider authenticator = iterator.next();
logger.debugf("Loaded clientCredentialsProvider %s", authenticator.getId());
authenticators.put(authenticator.getId(), authenticator);
} catch (ServiceConfigurationError e) {
if (logger.isDebugEnabled()) {
logger.debug("Failed to load clientCredentialsProvider with classloader: " + classLoader, e);
}
}
}
}
private static synchronized Sequencer loadConglomSequencer(){
Sequencer s=CONGLOM_SEQUENCE;
if(s==null){
ServiceLoader<Sequencer> loader=ServiceLoader.load(Sequencer.class);
Iterator<Sequencer> iter=loader.iterator();
if(!iter.hasNext())
throw new IllegalStateException("No Sequencers found!");
s=CONGLOM_SEQUENCE=iter.next();
}
return s;
}
private static System.LoggerFinder loadDefaultImplementation() {
final SecurityManager sm = System.getSecurityManager();
final Iterator<DefaultLoggerFinder> iterator;
if (sm == null) {
iterator = ServiceLoader.loadInstalled(DefaultLoggerFinder.class).iterator();
} else {
// We use limited do privileged here - the minimum set of
// permissions required to 'see' the META-INF/services resources
// seems to be CLASSLOADER_PERMISSION and READ_PERMISSION.
// Note that do privileged is required because
// otherwise the SecurityManager will prevent the ServiceLoader
// from seeing the installed provider.
PrivilegedAction<Iterator<DefaultLoggerFinder>> pa = () ->
ServiceLoader.loadInstalled(DefaultLoggerFinder.class).iterator();
iterator = AccessController.doPrivileged(pa, null,
LOGGERFINDER_PERMISSION, CLASSLOADER_PERMISSION,
READ_PERMISSION);
}
DefaultLoggerFinder result = null;
try {
// Iterator iterates with the access control context stored
// at ServiceLoader creation time.
if (iterator.hasNext()) {
result = iterator.next();
}
} catch (RuntimeException x) {
throw new ServiceConfigurationError(
"Failed to instantiate default LoggerFinder", x);
}
if (result == null) {
result = new DefaultLoggerFinder();
}
return result;
}
private static ArrayList getAllLookupServices() {
synchronized (PrintServiceLookup.class) {
ArrayList listOfLookupServices = getListOfLookupServices();
if (listOfLookupServices != null) {
return listOfLookupServices;
} else {
listOfLookupServices = initListOfLookupServices();
}
try {
java.security.AccessController.doPrivileged(
new java.security.PrivilegedExceptionAction() {
public Object run() {
Iterator<PrintServiceLookup> iterator =
ServiceLoader.load(PrintServiceLookup.class).
iterator();
ArrayList los = getListOfLookupServices();
while (iterator.hasNext()) {
try {
los.add(iterator.next());
} catch (ServiceConfigurationError err) {
/* In the applet case, we continue */
if (System.getSecurityManager() != null) {
err.printStackTrace();
} else {
throw err;
}
}
}
return null;
}
});
} catch (java.security.PrivilegedActionException e) {
}
return listOfLookupServices;
}
}
private static <T> T findServiceProvider(final Class<T> type) {
try {
return AccessController.doPrivileged(new PrivilegedAction<T>() {
public T run() {
final ServiceLoader<T> serviceLoader = ServiceLoader.load(type);
final Iterator<T> iterator = serviceLoader.iterator();
if (iterator.hasNext()) {
return iterator.next();
} else {
return null;
}
}
});
} catch(ServiceConfigurationError e) {
// It is not possible to wrap an error directly in
// FactoryConfigurationError - so we need to wrap the
// ServiceConfigurationError in a RuntimeException.
// The alternative would be to modify the logic in
// FactoryConfigurationError to allow setting a
// Throwable as the cause, but that could cause
// compatibility issues down the road.
final RuntimeException x = new RuntimeException(
"Provider for " + type + " cannot be created", e);
final FactoryConfigurationError error =
new FactoryConfigurationError(x, x.getMessage());
throw error;
}
}