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 Project: multi-model-server   Author: awslabs   File: PluginsManager.java    License: Apache License 2.0 6 votes vote down vote up
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 #2
Source Project: jdk8u60   Author: chenghanpeng   File: InetAddress.java    License: GNU General Public License v2.0 6 votes vote down vote up
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 #3
Source Project: quarkus   Author: quarkusio   File: EngineImpl.java    License: Apache License 2.0 6 votes vote down vote up
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 #4
Source Project: neoscada   Author: eclipse   File: ServiceLoaderProcessor.java    License: Eclipse Public License 1.0 6 votes vote down vote up
/**
 * 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 #5
Source Project: openjdk-jdk9   Author: AdoptOpenJDK   File: Main.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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 Project: proarc   Author: proarc   File: DigitalObjectPluginTest.java    License: GNU General Public License v3.0 6 votes vote down vote up
@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 #7
Source Project: Sentinel   Author: alibaba   File: LoggerSpiProvider.java    License: Apache License 2.0 6 votes vote down vote up
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 #8
Source Project: components   Author: Talend   File: ExtensibleUrlClassLoaderTest.java    License: Apache License 2.0 6 votes vote down vote up
@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 #9
Source Project: Sentinel   Author: alibaba   File: SpiLoader.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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 #10
Source Project: component-runtime   Author: Talend   File: ConfigurableClassLoaderTest.java    License: Apache License 2.0 6 votes vote down vote up
@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 #11
Source Project: piranha   Author: piranhacloud   File: ServletContainerInitializerExtension.java    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * 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 #12
Source Project: jdk8u-jdk   Author: lambdalab-mirror   File: InetAddress.java    License: GNU General Public License v2.0 6 votes vote down vote up
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 #13
Source Project: Sentinel   Author: alibaba   File: SpiLoader.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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 #14
Source Project: jdk8u-jdk   Author: frohoff   File: HttpServerProvider.java    License: GNU General Public License v2.0 6 votes vote down vote up
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 #15
Source Project: hadoop   Author: naver   File: Token.java    License: Apache License 2.0 6 votes vote down vote up
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 #16
Source Project: vertx-shell   Author: vert-x3   File: ShellAuth.java    License: 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 #17
Source Project: allure1   Author: allure-framework   File: ServiceLoaderUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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 #18
Source Project: dolphin-platform   Author: canoo   File: HttpClientProvider.java    License: Apache License 2.0 6 votes vote down vote up
@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 #19
Source Project: activemq-artemis   Author: apache   File: JMSBridgeImpl.java    License: Apache License 2.0 6 votes vote down vote up
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 #20
Source Project: jdk8u-jdk   Author: lambdalab-mirror   File: AsynchronousChannelProvider.java    License: GNU General Public License v2.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 #21
Source Project: es-ik   Author: zacker330   File: IKAnalyzerProvider.java    License: Apache License 2.0 5 votes vote down vote up
@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));
}
 
Example #22
Source Project: framework   Author: ww20081120   File: RetryJob.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example #23
Source Project: pgadba   Author: pgjdbc   File: DataSourceFactory.java    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * 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);
}
 
Example #24
Source Project: okta-sdk-java   Author: okta   File: DefaultResourceFactory.java    License: Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #25
Source Project: keycloak   Author: keycloak   File: ClientCredentialsProviderUtils.java    License: Apache License 2.0 5 votes vote down vote up
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);
            }
        }
    }
}
 
Example #26
Source Project: spliceengine   Author: splicemachine   File: ConglomerateUtils.java    License: 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 #27
Source Project: openjdk-jdk9   Author: AdoptOpenJDK   File: LoggerFinderLoader.java    License: GNU General Public License v2.0 5 votes vote down vote up
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;
}
 
Example #28
Source Project: jdk1.8-source-analysis   Author: raysonfang   File: PrintServiceLookup.java    License: Apache License 2.0 5 votes vote down vote up
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;
    }
}
 
Example #29
Source Project: openjdk-jdk8u   Author: AdoptOpenJDK   File: FactoryFinder.java    License: GNU General Public License v2.0 5 votes vote down vote up
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 #30
Source Project: solace-integration-guides   Author: SolaceLabs   File: JMSConnectionFactoryProviderTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void validateServiceIsLocatableViaServiceLoader() {
    ServiceLoader<ControllerService> loader = ServiceLoader.<ControllerService> load(ControllerService.class);
    Iterator<ControllerService> iter = loader.iterator();
    boolean present = false;
    while (iter.hasNext()) {
        ControllerService cs = iter.next();
        assertTrue(cs instanceof JMSConnectionFactoryProviderDefinition);
        present = true;
    }
    assertTrue(present);
}