java.util.ServiceLoader Java Examples
The following examples show how to use
java.util.ServiceLoader.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ServletContainerInitializerExtension.java From piranha with BSD 3-Clause "New" or "Revised" License | 6 votes |
/** * 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"); } }
Example #2
Source File: LoggerSpiProvider.java From Sentinel with Apache License 2.0 | 6 votes |
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()); } } }
Example #3
Source File: ServiceLoaderUtils.java From allure1 with Apache License 2.0 | 6 votes |
/** * 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; }
Example #4
Source File: DigitalObjectPluginTest.java From proarc with GNU General Public License v3.0 | 6 votes |
@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))); }
Example #5
Source File: Main.java From openjdk-jdk9 with GNU General Public License v2.0 | 6 votes |
/** * 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 }
Example #6
Source File: JMSBridgeImpl.java From activemq-artemis with Apache License 2.0 | 6 votes |
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); } } }
Example #7
Source File: HttpClientProvider.java From dolphin-platform with Apache License 2.0 | 6 votes |
@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; }
Example #8
Source File: AsynchronousChannelProvider.java From jdk8u-jdk with GNU General Public License v2.0 | 6 votes |
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; } } }
Example #9
Source File: ServiceLoaderProcessor.java From neoscada with Eclipse Public License 1.0 | 6 votes |
/** * 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 ); } } }
Example #10
Source File: ExtensibleUrlClassLoaderTest.java From components with Apache License 2.0 | 6 votes |
@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)); }
Example #11
Source File: ConfigurableClassLoaderTest.java From component-runtime with Apache License 2.0 | 6 votes |
@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()); } }
Example #12
Source File: ShellAuth.java From vertx-shell with Apache License 2.0 | 6 votes |
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"); }
Example #13
Source File: InetAddress.java From jdk8u-jdk with GNU General Public License v2.0 | 6 votes |
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; }
Example #14
Source File: SpiLoader.java From Sentinel with Apache License 2.0 | 6 votes |
/** * 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; } }
Example #15
Source File: HttpServerProvider.java From jdk8u-jdk with GNU General Public License v2.0 | 6 votes |
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; } } }
Example #16
Source File: EngineImpl.java From quarkus with Apache License 2.0 | 6 votes |
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; }
Example #17
Source File: InetAddress.java From jdk8u60 with GNU General Public License v2.0 | 6 votes |
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; }
Example #18
Source File: Token.java From hadoop with Apache License 2.0 | 6 votes |
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; }
Example #19
Source File: PluginsManager.java From multi-model-server with Apache License 2.0 | 6 votes |
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; }
Example #20
Source File: SpiLoader.java From Sentinel with Apache License 2.0 | 6 votes |
/** * 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<>(); } }
Example #21
Source File: FrontendFunctionDescriptorTest.java From knox with Apache License 2.0 | 5 votes |
@SuppressWarnings("rawtypes") @Test public void testServiceLoader() throws Exception { ServiceLoader loader = ServiceLoader.load( UrlRewriteFunctionDescriptor.class ); Iterator iterator = loader.iterator(); assertThat( "Service iterator empty.", iterator.hasNext() ); while( iterator.hasNext() ) { Object object = iterator.next(); if( object instanceof FrontendFunctionDescriptor ) { return; } } fail( "Failed to find " + FrontendFunctionDescriptor.class.getName() + " via service loader." ); }
Example #22
Source File: LocalFileSystemRegistrarTest.java From beam with Apache License 2.0 | 5 votes |
@Test public void testServiceLoader() { for (FileSystemRegistrar registrar : Lists.newArrayList(ServiceLoader.load(FileSystemRegistrar.class).iterator())) { if (registrar instanceof LocalFileSystemRegistrar) { Iterable<FileSystem> fileSystems = registrar.fromOptions(PipelineOptionsFactory.create()); assertThat(fileSystems, contains(instanceOf(LocalFileSystem.class))); return; } } fail("Expected to find " + LocalFileSystemRegistrar.class); }
Example #23
Source File: FileBasedWorkflowRepository.java From copper-engine with Apache License 2.0 | 5 votes |
private JavaCompiler getJavaCompiler() { JavaCompiler systemJavaCompiler = ToolProvider.getSystemJavaCompiler(); if (systemJavaCompiler != null) { return systemJavaCompiler; } logger.debug("System java compiler not found; searching for other java compilers..."); ServiceLoader<JavaCompiler> loader = ServiceLoader.load(JavaCompiler.class); Iterator<JavaCompiler> it = loader.iterator(); if (it.hasNext()) { JavaCompiler javaCompiler = it.next(); logger.debug("Found java compiler: {}", javaCompiler); return javaCompiler; } return null; }
Example #24
Source File: FileSystem.java From big-c with Apache License 2.0 | 5 votes |
private static void loadFileSystems() { synchronized (FileSystem.class) { if (!FILE_SYSTEMS_LOADED) { ServiceLoader<FileSystem> serviceLoader = ServiceLoader.load(FileSystem.class); for (FileSystem fs : serviceLoader) { SERVICE_FILE_SYSTEMS.put(fs.getScheme(), fs.getClass()); } FILE_SYSTEMS_LOADED = true; } } }
Example #25
Source File: AbstractChronology.java From Java8CN with Apache License 2.0 | 5 votes |
/** * Returns the available chronologies. * <p> * Each returned {@code Chronology} is available for use in the system. * The set of chronologies includes the system chronologies and * any chronologies provided by the application via ServiceLoader * configuration. * * @return the independent, modifiable set of the available chronology IDs, not null */ static Set<Chronology> getAvailableChronologies() { initCache(); // force initialization HashSet<Chronology> chronos = new HashSet<>(CHRONOS_BY_ID.values()); /// Add in Chronologies from the ServiceLoader configuration @SuppressWarnings("rawtypes") ServiceLoader<Chronology> loader = ServiceLoader.load(Chronology.class); for (Chronology chrono : loader) { chronos.add(chrono); } return chronos; }
Example #26
Source File: FlowHelper.java From framework with Apache License 2.0 | 5 votes |
/** * Description: <br> * * @author 王伟<br> * @taskId <br> * @param flowName * @return <br> */ private static FlowConfig match(final String flowName) { if (serviceLoader == null) { serviceLoader = ServiceLoader.load(FlowLoader.class); } FlowConfig flowConfig = null; for (FlowLoader flowLoader : serviceLoader) { flowConfig = flowLoader.load(flowName); if (flowConfig != null) { break; } } return flowConfig; }
Example #27
Source File: Infrastructure.java From smallrye-mutiny with Apache License 2.0 | 5 votes |
public static void reloadMultiInterceptors() { ServiceLoader<MultiInterceptor> interceptorLoader = ServiceLoader.load(MultiInterceptor.class); List<MultiInterceptor> interceptors = new ArrayList<>(); interceptorLoader.iterator().forEachRemaining(interceptors::add); interceptors.sort(Comparator.comparingInt(MultiInterceptor::ordinal)); MULTI_INTERCEPTORS.addAll(interceptors); }
Example #28
Source File: FactoryFinder.java From Bytecoder with Apache License 2.0 | 5 votes |
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; } }
Example #29
Source File: Transformer.java From smallrye-reactive-streams-operators with Apache License 2.0 | 5 votes |
private Transformer() { ServiceLoader<ExecutionModel> loader = ServiceLoader.load(ExecutionModel.class); Iterator<ExecutionModel> iterator = loader.iterator(); if (iterator.hasNext()) { model = iterator.next(); } else { model = i -> i; } }
Example #30
Source File: Plugins.java From pro with GNU General Public License v3.0 | 5 votes |
private static Stream<Provider<Plugin>> findDynamicPlugins(Path path) { var finder = ModuleFinder.of(path); var moduleNames = finder.findAll().stream().map(ref -> ref.descriptor().name()).collect(toUnmodifiableSet()); var boot = ModuleLayer.boot(); var cf = boot.configuration().resolve(finder, ModuleFinder.of(), moduleNames); var classLoader = new ClassLoader(Plugins.class.getClassLoader()) { /* empty */ }; var layer = boot.defineModulesWithOneLoader(cf, classLoader); var serviceLoader = ServiceLoader.load(layer, Plugin.class); return serviceLoader.stream(); }