java.util.ServiceLoader.Provider#java.util.ServiceLoader源码实例Demo

下面列出了java.util.ServiceLoader.Provider#java.util.ServiceLoader 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: multi-model-server   文件: PluginsManager.java
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;
}
 
源代码2 项目: jdk8u60   文件: InetAddress.java
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;
}
 
源代码3 项目: quarkus   文件: EngineImpl.java
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;
}
 
源代码4 项目: neoscada   文件: ServiceLoaderProcessor.java
/**
 * 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 );
        }
    }
}
 
源代码5 项目: openjdk-jdk9   文件: Main.java
/**
 * 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
}
 
源代码6 项目: proarc   文件: DigitalObjectPluginTest.java
@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)));
}
 
源代码7 项目: Sentinel   文件: LoggerSpiProvider.java
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());
        }
    }
}
 
源代码8 项目: components   文件: ExtensibleUrlClassLoaderTest.java
@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));

}
 
源代码9 项目: Sentinel   文件: SpiLoader.java
/**
 * 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<>();
    }
}
 
源代码10 项目: Bytecoder   文件: BootstrapLogger.java
@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");
    }
}
 
源代码13 项目: jdk8u-jdk   文件: InetAddress.java
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;
}
 
源代码14 项目: Sentinel   文件: SpiLoader.java
/**
 * 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;
    }
}
 
源代码15 项目: jdk8u-jdk   文件: HttpServerProvider.java
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;
        }
    }
}
 
源代码16 项目: hadoop   文件: Token.java
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;
}
 
源代码17 项目: vertx-shell   文件: ShellAuth.java
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");
}
 
源代码18 项目: allure1   文件: ServiceLoaderUtils.java
/**
 * 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;
}
 
源代码19 项目: dolphin-platform   文件: HttpClientProvider.java
@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;
}
 
源代码20 项目: activemq-artemis   文件: JMSBridgeImpl.java
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);
      }
   }
}
 
源代码21 项目: jdk8u-jdk   文件: AsynchronousChannelProvider.java
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;
        }
    }
}
 
源代码22 项目: es-ik   文件: IKAnalyzerProvider.java
@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));
}
 
源代码23 项目: framework   文件: RetryJob.java
/**
 * 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;
}
 
源代码24 项目: pgadba   文件: DataSourceFactory.java
/**
 * 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);
}
 
源代码25 项目: okta-sdk-java   文件: DefaultResourceFactory.java
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;
}
 
源代码26 项目: keycloak   文件: ClientCredentialsProviderUtils.java
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);
            }
        }
    }
}
 
源代码27 项目: spliceengine   文件: ConglomerateUtils.java
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;
}
 
源代码28 项目: openjdk-jdk9   文件: LoggerFinderLoader.java
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;
    }
}
 
源代码30 项目: openjdk-jdk8u   文件: FactoryFinder.java
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;
    }
}