Java Code Examples for java.util.ServiceLoader#iterator()

The following examples show how to use java.util.ServiceLoader#iterator() . 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: SelectorProvider.java    From Bytecoder with Apache License 2.0 6 votes vote down vote up
private static boolean loadProviderAsService() {

        ServiceLoader<SelectorProvider> sl =
            ServiceLoader.load(SelectorProvider.class,
                               ClassLoader.getSystemClassLoader());
        Iterator<SelectorProvider> i = sl.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 2
Source File: ServiceLoaderUtils.java    From oxygen with Apache License 2.0 6 votes vote down vote up
/**
 * 加载服务列表
 *
 * @param clazz 类
 * @param loader 类加载器
 * @param <T> 泛型
 * @return services
 */
public <T> List<T> loadServices(Class<T> clazz, ClassLoader loader) {
  List<T> list = new ArrayList<>();
  ServiceLoader<T> serviceLoader;
  if (loader != null) {
    serviceLoader = ServiceLoader.load(clazz, loader);
  } else {
    serviceLoader = ServiceLoader.load(clazz);
  }
  Iterator<T> it = serviceLoader.iterator();
  if (it.hasNext()) {
    it.forEachRemaining(list::add);
    return list;
  }
  if (loader == null) {
    // for tccl
    serviceLoader = ServiceLoader.load(clazz, ServiceLoaderUtils.class.getClassLoader());
    it = serviceLoader.iterator();
    if (it.hasNext()) {
      it.forEachRemaining(list::add);
      return list;
    }
  }
  return list;
}
 
Example 3
Source File: AsynchronousChannelProvider.java    From j2objc with Apache License 2.0 6 votes vote down vote up
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 4
Source File: ShellAuth.java    From vertx-shell with Apache License 2.0 6 votes vote down vote up
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 5
Source File: SelectorProvider.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
private static boolean loadProviderAsService() {

        ServiceLoader<SelectorProvider> sl =
            ServiceLoader.load(SelectorProvider.class,
                               ClassLoader.getSystemClassLoader());
        Iterator<SelectorProvider> i = sl.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 6
Source File: SqlEnvironmentLoader.java    From spliceengine with GNU Affero General Public License v3.0 6 votes vote down vote up
private static synchronized SqlEnvironment initializeEnvironment(SConfiguration config,
                                                                 Snowflake snowflake,
                                                                 Connection internalConnection,
                                                                 DatabaseVersion spliceVersion){
    SqlEnvironment env = sqlEnv;
    if(env==null){
        ServiceLoader<SqlEnvironment> load = ServiceLoader.load(SqlEnvironment.class);
        Iterator<SqlEnvironment> iter = load.iterator();
        if(!iter.hasNext())
            throw new IllegalStateException("No SqlEnvironment found!");
        env = sqlEnv = iter.next();
        sqlEnv.initialize(config,snowflake,internalConnection,spliceVersion);
        if(iter.hasNext())
            throw new IllegalStateException("Only one SqlEnvironment is allowed!");
    }
    return env;
}
 
Example 7
Source File: MetadataFactoryService.java    From spliceengine with GNU Affero General Public License v3.0 5 votes vote down vote up
public static MetadataFactory newMetadataFactory(){
    ServiceLoader<MetadataFactory> factoryService = ServiceLoader.load(MetadataFactory.class);
    Iterator<MetadataFactory> iter = factoryService.iterator();
    if(!iter.hasNext())
        throw new IllegalStateException("No Metadatafactory service found!");
    MetadataFactory mf = null;
    MetadataFactory currentMF;
    while (iter.hasNext()) {
        currentMF = iter.next();
        if (mf == null || mf.getPriority() < currentMF.getPriority())
            mf = currentMF;
    }
    return mf;
}
 
Example 8
Source File: RasterOptionProvider.java    From geowave with Apache License 2.0 5 votes vote down vote up
private synchronized Map<String, RasterMergeStrategyProviderSpi> getRegisteredMergeStrategies() {
  if (registeredMergeStrategies == null) {
    registeredMergeStrategies = new HashMap<>();
    final ServiceLoader<RasterMergeStrategyProviderSpi> converters =
        ServiceLoader.load(RasterMergeStrategyProviderSpi.class);
    final Iterator<RasterMergeStrategyProviderSpi> it = converters.iterator();
    while (it.hasNext()) {
      final RasterMergeStrategyProviderSpi converter = it.next();
      registeredMergeStrategies.put(converter.getName(), converter);
    }
  }
  return registeredMergeStrategies;
}
 
Example 9
Source File: ServicePortFunctionDescriptorTest.java    From knox with Apache License 2.0 5 votes vote down vote up
@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 ServicePortFunctionDescriptor ) {
      return;
    }
  }
  fail( "Failed to find " + ServicePortFunctionDescriptor.class.getName() + " via service loader." );
}
 
Example 10
Source File: ProducerServiceLoader.java    From SimpleFlatMapper with MIT License 5 votes vote down vote up
public static  <T, P extends Producer<T>> void produceFromServiceLoader(ServiceLoader<P> serviceLoader, Consumer<T> consumer) {
    Iterator<P> iterator = serviceLoader.iterator();
    while(iterator.hasNext()) {
        try {
            iterator.next().produce(consumer);
        } catch (Throwable e) {
            System.err.println("Unexpected error on listing " + serviceLoader + " : "  + e);
            e.printStackTrace();
        }
    }
}
 
Example 11
Source File: EncryptUriDeploymentContributorTest.java    From knox with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("rawtypes")
@Test
public void testServiceLoader() throws Exception {
  ServiceLoader loader = ServiceLoader.load( ProviderDeploymentContributor.class );
  Iterator iterator = loader.iterator();
  assertThat( "Service iterator empty.", iterator.hasNext() );
  while( iterator.hasNext() ) {
    Object object = iterator.next();
    if( object instanceof EncryptUriDeploymentContributor ) {
      return;
    }
  }
  fail( "Failed to find " + EncryptUriDeploymentContributor.class.getName() + " via service loader." );
}
 
Example 12
Source File: ServiceFactoryBean.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
protected Object getObjectToExpose(ServiceLoader<?> serviceLoader) {
	Iterator<?> it = serviceLoader.iterator();
	if (!it.hasNext()) {
		throw new IllegalStateException(
				"ServiceLoader could not find service for type [" + getServiceType() + "]");
	}
	return it.next();
}
 
Example 13
Source File: MetaClientModuleFactoryTest.java    From crnk-framework with Apache License 2.0 5 votes vote down vote up
@Test
public void test() {
	ServiceLoader<ClientModuleFactory> loader = ServiceLoader.load(ClientModuleFactory.class);
	Iterator<ClientModuleFactory> iterator = loader.iterator();
	Assert.assertTrue(iterator.hasNext());
	ClientModuleFactory moduleFactory = iterator.next();
	Assert.assertFalse(iterator.hasNext());
	Module module = moduleFactory.create();
	Assert.assertTrue(module instanceof MetaModule);
}
 
Example 14
Source File: ConglomerateUtils.java    From spliceengine with GNU Affero General Public License v3.0 5 votes vote down vote up
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;
}
 
Example 15
Source File: GatewayServer.java    From knox with Apache License 2.0 5 votes vote down vote up
private static GatewayServices instantiateGatewayServices() {
  ServiceLoader<GatewayServices> loader = ServiceLoader.load( GatewayServices.class );
  Iterator<GatewayServices> services = loader.iterator();
  if (services.hasNext()) {
    return services.next();
  }
  return null;
}
 
Example 16
Source File: ParserManager.java    From song-parser-spi-demo with MIT License 5 votes vote down vote up
private static void loadInitialParsers() {
    ServiceLoader<Parser> loadedParsers = ServiceLoader.load(Parser.class);
    Iterator<Parser> driversIterator = loadedParsers.iterator();
    try{
        while(driversIterator.hasNext()) {
            driversIterator.next();
        }
    } catch(Throwable t) {
        // Do nothing
    }
}
 
Example 17
Source File: StreamingLedgerRuntimeLoader.java    From da-streamingledger with Apache License 2.0 4 votes vote down vote up
@GuardedBy("LOCK")
private static StreamingLedgerRuntimeProvider loadRuntimeProvider() {
    try {
        ServiceLoader<StreamingLedgerRuntimeProvider> serviceLoader =
                ServiceLoader.load(StreamingLedgerRuntimeProvider.class);

        Iterator<StreamingLedgerRuntimeProvider> iter = serviceLoader.iterator();

        // find the first service implementation
        StreamingLedgerRuntimeProvider firstProvider;
        if (iter.hasNext()) {
            firstProvider = iter.next();
        }
        else {
            throw new FlinkRuntimeException("No StreamingLedgerRuntimeProvider found. "
                    + "Please make sure you have a transaction runtime implementation in the classpath.");
        }

        // check if there is more than one service implementation
        if (iter.hasNext()) {
            String secondServiceName = "(could not load service implementation)";
            try {
                secondServiceName = iter.next().getClass().getName();
            }
            catch (Throwable ignored) {
            }

            throw new FlinkRuntimeException("Ambiguous: Found more than one StreamingLedgerRuntimeProvider: "
                    + firstProvider.getClass().getName() + " and " + secondServiceName);
        }

        return firstProvider;
    }
    catch (FlinkRuntimeException e) {
        // simply propagate without further wrapping, for simplicity
        throw e;
    }
    catch (Throwable t) {
        throw new FlinkRuntimeException("Could not load StreamingLedgerRuntimeProvider", t);
    }
}
 
Example 18
Source File: ServiceLoaderHelper.java    From ph-commons with Apache License 2.0 4 votes vote down vote up
/**
 * Uses the {@link ServiceLoader} to load all SPI implementations of the
 * passed class
 *
 * @param <T>
 *        The implementation type to be loaded
 * @param aSPIClass
 *        The SPI interface class. May not be <code>null</code>.
 * @param aClassLoader
 *        The class loader to use for the SPI loader. May not be
 *        <code>null</code>.
 * @param aLogger
 *        An optional logger to use. May be <code>null</code>.
 * @return A collection of all currently available plugins. Never
 *         <code>null</code>.
 */
@Nonnull
@ReturnsMutableCopy
public static <T> ICommonsList <T> getAllSPIImplementations (@Nonnull final Class <T> aSPIClass,
                                                             @Nonnull final ClassLoader aClassLoader,
                                                             @Nullable final Logger aLogger)
{
  ValueEnforcer.notNull (aSPIClass, "SPIClass");
  ValueEnforcer.notNull (aClassLoader, "ClassLoader");

  final Logger aRealLogger = aLogger != null ? aLogger : LOGGER;

  if (aRealLogger.isTraceEnabled ())
    aRealLogger.trace ("Trying to retrieve all SPI implementations of " + aSPIClass);

  if (!s_aCacheInterface.hasAnnotation (aSPIClass))
    if (LOGGER.isWarnEnabled ())
      LOGGER.warn (aSPIClass + " should have the @IsSPIInterface annotation");

  final ServiceLoader <T> aServiceLoader = ServiceLoader.<T> load (aSPIClass, aClassLoader);
  final ICommonsList <T> ret = new CommonsArrayList <> ();

  // We use the iterator to be able to catch exceptions thrown
  // when loading SPI implementations (e.g. the SPI implementation class does
  // not exist)
  final Iterator <T> aIterator = aServiceLoader.iterator ();
  while (aIterator.hasNext ())
  {
    try
    {
      final T aInstance = aIterator.next ();
      if (!s_aCacheImplementation.hasAnnotation (aInstance))
        if (LOGGER.isWarnEnabled ())
          LOGGER.warn (aInstance + " should have the @IsSPIImplementation annotation");
      ret.add (aInstance);
    }
    catch (final Exception ex)
    {
      aRealLogger.error ("Unable to load an SPI implementation of " + aSPIClass, ex);
    }
  }

  if (aRealLogger.isDebugEnabled ())
    aRealLogger.debug ("Finished retrieving all " + ret.size () + " SPI implementations of " + aSPIClass);

  return ret;
}
 
Example 19
Source File: AttachProvider.java    From jdk8u_jdk with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Returns a list of the installed attach providers.
 *
 * <p> An AttachProvider is installed on the platform if:
 *
 * <ul>
 *   <li><p>It is installed in a JAR file that is visible to the defining
 *   class loader of the AttachProvider type (usually, but not required
 *   to be, the {@link java.lang.ClassLoader#getSystemClassLoader system
 *   class loader}).</p></li>
 *
 *   <li><p>The JAR file contains a provider configuration named
 *   <tt>com.sun.tools.attach.spi.AttachProvider</tt> in the resource directory
 *   <tt>META-INF/services</tt>. </p></li>
 *
 *   <li><p>The provider configuration file lists the full-qualified class
 *   name of the AttachProvider implementation. </p></li>
 * </ul>
 *
 * <p> The format of the provider configuration file is one fully-qualified
 * class name per line. Space and tab characters surrounding each class name,
 * as well as blank lines are ignored. The comment character is
 *  <tt>'#'</tt> (<tt>0x23</tt>), and on each line all characters following
 * the first comment character are ignored. The file must be encoded in
 * UTF-8. </p>
 *
 * <p> AttachProvider implementations are loaded and instantiated
 * (using the zero-arg constructor) at the first invocation of this method.
 * The list returned by the first invocation of this method is the list
 * of providers. Subsequent invocations of this method return a list of the same
 * providers. The list is unmodifable.</p>
 *
 * @return  A list of the installed attach providers.
 */
public static List<AttachProvider> providers() {
    synchronized (lock) {
        if (providers == null) {
            providers = new ArrayList<AttachProvider>();

            ServiceLoader<AttachProvider> providerLoader =
                ServiceLoader.load(AttachProvider.class,
                                   AttachProvider.class.getClassLoader());

            Iterator<AttachProvider> i = providerLoader.iterator();

            while (i.hasNext()) {
                try {
                    providers.add(i.next());
                } catch (Throwable t) {
                    if (t instanceof ThreadDeath) {
                        ThreadDeath td = (ThreadDeath)t;
                        throw td;
                    }
                    // Ignore errors and exceptions
                    System.err.println(t);
                }
            }
        }
        return Collections.unmodifiableList(providers);
    }
}
 
Example 20
Source File: AttachProvider.java    From openjdk-jdk8u with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Returns a list of the installed attach providers.
 *
 * <p> An AttachProvider is installed on the platform if:
 *
 * <ul>
 *   <li><p>It is installed in a JAR file that is visible to the defining
 *   class loader of the AttachProvider type (usually, but not required
 *   to be, the {@link java.lang.ClassLoader#getSystemClassLoader system
 *   class loader}).</p></li>
 *
 *   <li><p>The JAR file contains a provider configuration named
 *   <tt>com.sun.tools.attach.spi.AttachProvider</tt> in the resource directory
 *   <tt>META-INF/services</tt>. </p></li>
 *
 *   <li><p>The provider configuration file lists the full-qualified class
 *   name of the AttachProvider implementation. </p></li>
 * </ul>
 *
 * <p> The format of the provider configuration file is one fully-qualified
 * class name per line. Space and tab characters surrounding each class name,
 * as well as blank lines are ignored. The comment character is
 *  <tt>'#'</tt> (<tt>0x23</tt>), and on each line all characters following
 * the first comment character are ignored. The file must be encoded in
 * UTF-8. </p>
 *
 * <p> AttachProvider implementations are loaded and instantiated
 * (using the zero-arg constructor) at the first invocation of this method.
 * The list returned by the first invocation of this method is the list
 * of providers. Subsequent invocations of this method return a list of the same
 * providers. The list is unmodifable.</p>
 *
 * @return  A list of the installed attach providers.
 */
public static List<AttachProvider> providers() {
    synchronized (lock) {
        if (providers == null) {
            providers = new ArrayList<AttachProvider>();

            ServiceLoader<AttachProvider> providerLoader =
                ServiceLoader.load(AttachProvider.class,
                                   AttachProvider.class.getClassLoader());

            Iterator<AttachProvider> i = providerLoader.iterator();

            while (i.hasNext()) {
                try {
                    providers.add(i.next());
                } catch (Throwable t) {
                    if (t instanceof ThreadDeath) {
                        ThreadDeath td = (ThreadDeath)t;
                        throw td;
                    }
                    // Ignore errors and exceptions
                    System.err.println(t);
                }
            }
        }
        return Collections.unmodifiableList(providers);
    }
}