Example usage for java.util ServiceLoader load

List of usage examples for java.util ServiceLoader load

Introduction

In this page you can find the example usage for java.util ServiceLoader load.

Prototype

@CallerSensitive
public static <S> ServiceLoader<S> load(ModuleLayer layer, Class<S> service) 

Source Link

Document

Creates a new service loader for the given service type to load service providers from modules in the given module layer and its ancestors.

Usage

From source file:org.keycloak.adapters.authentication.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 {//  w w w  .j  ava2s  . c om
            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);
            }
        }
    }
}

From source file:org.seedstack.seed.security.internal.SecurityPlugin.java

public SecurityPlugin() {
    for (SecurityProvider securityProvider : ServiceLoader.load(SecurityProvider.class,
            SeedReflectionUtils.findMostCompleteClassLoader(SecurityPlugin.class))) {
        securityProviders.add(securityProvider);
    }/*from  w  w w .ja v  a  2  s.c  o m*/
}

From source file:org.overlord.sramp.common.derived.ArtifactDeriverFactory.java

/**
  * Loads any extended derivers.  These can be contributed via the
  * standard Java service loading mechanism.
  *///from  ww  w.ja v a2 s.c om
private static void loadExtendedDerivers() {
    // First load via the standard ServiceRegistry mechanism.
    Set<DeriverProvider> providers = ServiceRegistryUtil.getServices(DeriverProvider.class);
    for (DeriverProvider provider : providers) {
        Map<String, ArtifactDeriver> derivers = provider.createArtifactDerivers();
        if (derivers != null && !derivers.isEmpty()) {
            extendedDerivers.putAll(derivers);
        }
    }

    // Allow users to provide a directory path where we will check for JARs that
    // contain DeriverProvider implementations.
    Collection<ClassLoader> loaders = new LinkedList<ClassLoader>();
    String customDeriverDirPath = System.getProperty(SrampConstants.SRAMP_CUSTOM_DERIVER_DIR);
    if (customDeriverDirPath != null && customDeriverDirPath.trim().length() > 0) {
        File directory = new File(customDeriverDirPath);
        if (directory.isDirectory()) {
            List<URL> jarURLs = new ArrayList<URL>();
            Collection<File> jarFiles = FileUtils.listFiles(directory, new String[] { "jar" }, false); //$NON-NLS-1$
            for (File jarFile : jarFiles) {
                try {
                    URL jarUrl = jarFile.toURI().toURL();
                    jarURLs.add(jarUrl);
                } catch (MalformedURLException e) {
                }
            }
            URL[] urls = jarURLs.toArray(new URL[jarURLs.size()]);
            ClassLoader jarCL = new URLClassLoader(urls, Thread.currentThread().getContextClassLoader());
            loaders.add(jarCL);
        }
    }
    // Now load all of these contributed DeriverProvider implementations
    for (ClassLoader loader : loaders) {
        for (DeriverProvider provider : ServiceLoader.load(DeriverProvider.class, loader)) {
            Map<String, ArtifactDeriver> derivers = provider.createArtifactDerivers();
            if (derivers != null && !derivers.isEmpty()) {
                extendedDerivers.putAll(derivers);
            }
        }
    }
}

From source file:com.asakusafw.workflow.executor.TaskExecutors.java

/**
 * Returns the default task executor objects via SPI.
 * @param serviceLoader the service loader
 * @return the default task executors/*from  w  ww  .  j a v a  2 s.  c  om*/
 */
public static Collection<TaskExecutor> loadDefaults(ClassLoader serviceLoader) {
    List<TaskExecutor> executors = new ArrayList<>();
    for (TaskExecutor executor : ServiceLoader.load(TaskExecutor.class, serviceLoader)) {
        executors.add(executor);
    }
    return executors;
}

From source file:org.artificer.integration.ExtensionFactory.java

/**
 * Loads any custom extensions.  These can be contributed via the standard Java service loading mechanism
 * or through custom jars in the dir identified through sramp.extension.customDir
 *///from w w w  .  ja  v a  2  s  .c  o m
private static void loadExtended() {
    // First load via the standard ServiceRegistry mechanism.
    Set<ArtifactTypeDetector> extendedTypeDetectors = ServiceRegistryUtil
            .getServices(ArtifactTypeDetector.class);
    typeDetectors.addAll(extendedTypeDetectors);
    Set<ArtifactBuilderProvider> extendedBuilderProviders = ServiceRegistryUtil
            .getServices(ArtifactBuilderProvider.class);
    builderProviders.addAll(extendedBuilderProviders);

    // Allow users to provide a directory path where we will check for JARs that
    // contain extension implementations.
    Collection<ClassLoader> loaders = new LinkedList<ClassLoader>();
    String customDirPath = System.getProperty(ArtificerConstants.ARTIFICER_CUSTOM_EXTENSION_DIR);
    if (customDirPath != null && customDirPath.trim().length() > 0) {
        File directory = new File(customDirPath);
        if (directory.isDirectory()) {
            List<URL> jarURLs = new ArrayList<URL>();
            Collection<File> jarFiles = FileUtils.listFiles(directory, new String[] { "jar" }, false);
            for (File jarFile : jarFiles) {
                try {
                    URL jarUrl = jarFile.toURI().toURL();
                    jarURLs.add(jarUrl);
                } catch (MalformedURLException e) {
                }
            }
            URL[] urls = jarURLs.toArray(new URL[jarURLs.size()]);
            ClassLoader jarCL = new URLClassLoader(urls, Thread.currentThread().getContextClassLoader());
            loaders.add(jarCL);
        }
    }
    for (ClassLoader loader : loaders) {
        for (ArtifactTypeDetector typeDetector : ServiceLoader.load(ArtifactTypeDetector.class, loader)) {
            typeDetectors.add(typeDetector);
        }
        for (ArtifactBuilderProvider builderProvider : ServiceLoader.load(ArtifactBuilderProvider.class,
                loader)) {
            builderProviders.add(builderProvider);
        }
    }
}

From source file:org.seedstack.seed.security.internal.SeedSecurityCorePlugin.java

/**
 * Plugin constructor//  ww  w  .  j a  va  2  s  .  co m
 */
public SeedSecurityCorePlugin() {
    ServiceLoader<SeedSecurityPlugin> loader = ServiceLoader.load(SeedSecurityPlugin.class,
            SeedReflectionUtils.findMostCompleteClassLoader(SeedSecurityCorePlugin.class));
    Iterator<SeedSecurityPlugin> it = loader.iterator();
    if (!it.hasNext()) {
        securityPlugins.add(new DefaultSecurityPlugin());
    } else {
        while (it.hasNext()) {
            securityPlugins.add(it.next());
        }
    }
}

From source file:org.overlord.sramp.integration.ExtensionFactory.java

/**
 * Loads any custom extensions.  These can be contributed via the standard Java service loading mechanism
 * or through custom jars in the dir identified through sramp.extension.customDir
 *//*from w w  w.  j  a va  2s .  c  om*/
private static void loadExtended() {
    // First load via the standard ServiceRegistry mechanism.
    Set<ArtifactTypeDetector> extendedTypeDetectors = ServiceRegistryUtil
            .getServices(ArtifactTypeDetector.class);
    typeDetectors.addAll(extendedTypeDetectors);
    Set<ArtifactBuilderProvider> extendedBuilderProviders = ServiceRegistryUtil
            .getServices(ArtifactBuilderProvider.class);
    builderProviders.addAll(extendedBuilderProviders);

    // Allow users to provide a directory path where we will check for JARs that
    // contain extension implementations.
    Collection<ClassLoader> loaders = new LinkedList<ClassLoader>();
    String customDirPath = System.getProperty(SrampConstants.SRAMP_CUSTOM_EXTENSION_DIR);
    if (customDirPath != null && customDirPath.trim().length() > 0) {
        File directory = new File(customDirPath);
        if (directory.isDirectory()) {
            List<URL> jarURLs = new ArrayList<URL>();
            Collection<File> jarFiles = FileUtils.listFiles(directory, new String[] { "jar" }, false); //$NON-NLS-1$
            for (File jarFile : jarFiles) {
                try {
                    URL jarUrl = jarFile.toURI().toURL();
                    jarURLs.add(jarUrl);
                } catch (MalformedURLException e) {
                }
            }
            URL[] urls = jarURLs.toArray(new URL[jarURLs.size()]);
            ClassLoader jarCL = new URLClassLoader(urls, Thread.currentThread().getContextClassLoader());
            loaders.add(jarCL);
        }
    }
    for (ClassLoader loader : loaders) {
        for (ArtifactTypeDetector typeDetector : ServiceLoader.load(ArtifactTypeDetector.class, loader)) {
            typeDetectors.add(typeDetector);
        }
        for (ArtifactBuilderProvider builderProvider : ServiceLoader.load(ArtifactBuilderProvider.class,
                loader)) {
            builderProviders.add(builderProvider);
        }
    }
}

From source file:com.twosigma.beaker.sql.JDBCClient.java

public void loadDrivers(List<String> pathList) {
    synchronized (this) {

        dsMap = new HashMap<>();
        drivers = new HashSet<>();

        Set<URL> urlSet = new HashSet<>();

        String dbDriverString = System.getenv("BEAKER_JDBC_DRIVER_LIST");
        if (dbDriverString != null && !dbDriverString.isEmpty()) {
            String[] dbDriverList = dbDriverString.split(File.pathSeparator);
            for (String s : dbDriverList) {
                try {
                    urlSet.add(toURL(s));
                } catch (MalformedURLException e) {
                    logger.error(e.getMessage());
                }//from www  .  j  a va2 s  .c  o m
            }
        }

        if (pathList != null) {
            for (String path : pathList) {
                path = path.trim();
                if (path.startsWith("--") || path.startsWith("#")) {
                    continue;
                }
                try {
                    urlSet.add(toURL(path));
                } catch (MalformedURLException e) {
                    logger.error(e.getMessage());
                }
            }
        }

        URLClassLoader loader = new URLClassLoader(urlSet.toArray(new URL[urlSet.size()]));

        ServiceLoader<Driver> loadedDrivers = ServiceLoader.load(Driver.class, loader);
        Iterator<Driver> driversIterator = loadedDrivers.iterator();
        try {
            while (driversIterator.hasNext()) {
                Driver d = driversIterator.next();
                drivers.add(d);
            }
        } catch (Throwable t) {
            logger.error(t.getMessage());
        }
    }
}

From source file:io.druid.initialization.Initialization.java

/**
 * Look for extension modules for the given class from both classpath and extensions directory. A user should never
 * put the same two extensions in classpath and extensions directory, if he/she does that, the one that is in the
 * classpath will be loaded, the other will be ignored.
 *
 * @param config Extensions configuration
 * @param clazz  The class of extension module (e.g., DruidModule)
 *
 * @return A collection that contains distinct extension modules
 */// ww w . ja  va  2  s  .  co  m
public synchronized static <T> Collection<T> getFromExtensions(ExtensionsConfig config, Class<T> clazz) {
    final Set<T> retVal = Sets.newHashSet();
    final Set<String> loadedExtensionNames = Sets.newHashSet();

    if (config.searchCurrentClassloader()) {
        for (T module : ServiceLoader.load(clazz, Thread.currentThread().getContextClassLoader())) {
            final String moduleName = module.getClass().getCanonicalName();
            if (moduleName == null) {
                log.warn(
                        "Extension module [%s] was ignored because it doesn't have a canonical name, is it a local or anonymous class?",
                        module.getClass().getName());
            } else if (!loadedExtensionNames.contains(moduleName)) {
                log.info("Adding classpath extension module [%s] for class [%s]", moduleName, clazz.getName());
                loadedExtensionNames.add(moduleName);
                retVal.add(module);
            }
        }
    }

    for (File extension : getExtensionFilesToLoad(config)) {
        log.info("Loading extension [%s] for class [%s]", extension.getName(), clazz.getName());
        try {
            final URLClassLoader loader = getClassLoaderForExtension(extension);
            for (T module : ServiceLoader.load(clazz, loader)) {
                final String moduleName = module.getClass().getCanonicalName();
                if (moduleName == null) {
                    log.warn(
                            "Extension module [%s] was ignored because it doesn't have a canonical name, is it a local or anonymous class?",
                            module.getClass().getName());
                } else if (!loadedExtensionNames.contains(moduleName)) {
                    log.info("Adding local file system extension module [%s] for class [%s]", moduleName,
                            clazz.getName());
                    loadedExtensionNames.add(moduleName);
                    retVal.add(module);
                }
            }
        } catch (Exception e) {
            throw Throwables.propagate(e);
        }
    }

    // update the map with currently loaded modules
    extensionsMap.put(clazz, retVal);

    return retVal;
}

From source file:org.apache.nifi.registry.extension.ExtensionManager.java

/**
 * Loads implementations of the given extension class from the given class loader.
 *
 * @param extensionClass the extension/service class
 * @param extensionClassLoader the class loader to search
 */// w w  w  . j  a va2  s.  c  o  m
private void loadExtensions(final Class extensionClass, final ExtensionClassLoader extensionClassLoader) {
    final ServiceLoader<?> serviceLoader = ServiceLoader.load(extensionClass, extensionClassLoader);
    for (final Object o : serviceLoader) {
        final String extensionClassName = o.getClass().getCanonicalName();
        if (classLoaderMap.containsKey(extensionClassName)) {
            final String currDir = extensionClassLoader.getRootDir();
            final String existingDir = classLoaderMap.get(extensionClassName).getRootDir();
            LOGGER.warn("Skipping {} from {} which was already found in {}",
                    new Object[] { extensionClassName, currDir, existingDir });
        } else {
            classLoaderMap.put(o.getClass().getCanonicalName(), extensionClassLoader);
        }
    }
}