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:com.asakusafw.runtime.stage.AbstractStageClient.java

/**
 * Configures the {@link Job} object for this stage.
 * @param job the target job//from   w  w w .j  a v a2  s.  c  o  m
 * @param variables current variable table
 * @throws IOException if failed to configure the job
 * @throws InterruptedException if interrupted while configuring {@link Job} object
 */
protected void configureStage(Job job, VariableTable variables) throws IOException, InterruptedException {
    ClassLoader loader = job.getConfiguration().getClassLoader();
    for (StageConfigurator configurator : ServiceLoader.load(StageConfigurator.class, loader)) {
        configurator.configure(job);
    }
}

From source file:org.jtalks.jcommune.plugin.api.PluginLoader.java

private synchronized void initPluginList() {
    classLoader = new PluginClassLoader(folder);
    ServiceLoader<Plugin> pluginLoader = ServiceLoader.load(Plugin.class, classLoader);
    List<Plugin> plugins = new ArrayList<>();
    for (Plugin plugin : pluginLoader) {
        plugins.add(plugin);//from  www.  j  av  a  2 s  . c  o  m
    }
    this.plugins = plugins;
}

From source file:com.asakusafw.runtime.flow.RuntimeResourceManager.java

/**
 * Loads the available resources.//from   ww w . j av  a2 s. c  o m
 * In this implementation, the method collects service information from
 * {@code META-INF/services/com.asakusafw.runtime.core.RuntimeResource}
 * and creates {@link RuntimeResource} implementations on them via SPI.
 * @return the loaded resources
 * @throws IOException if failed to load the resources
 */
protected List<RuntimeResource> load() throws IOException {
    List<RuntimeResource> results = new ArrayList<>();
    ClassLoader loader = configuration.getClassLoader();
    try {
        for (RuntimeResource resource : ServiceLoader.load(RuntimeResource.class, loader)) {
            if (resource instanceof Configurable) {
                ((Configurable) resource).setConf(configuration.getConf());
            }
            results.add(resource);
        }
    } catch (RuntimeException e) {
        throw new IOException(
                MessageFormat.format("Failed to load resources ({0})", RuntimeResource.class.getName()), e);
    }
    return results;
}

From source file:nor.core.Nor.java

private void init(final List<URL> jarUrls) throws IOException {
    LOGGER.entering("init");

    /*/*from  w  ww . j a v a 2s  .  com*/
     * Create a proxy server.
     */
    this.server = new ProxyServer(this.handler, this.router);

    final String pluginPath = System.getProperty("nor.plugin");
    if (pluginPath != null) {

        final File dir = new File(pluginPath);
        if (dir.isDirectory()) {

            for (final File f : dir.listFiles()) {

                try {

                    jarUrls.add(f.toURI().toURL());

                } catch (final MalformedURLException e) {

                    LOGGER.catched(Level.WARNING, "init", e);

                }

            }

        }

    }

    /*
     * Load installed plugins
     */
    for (final URL url : jarUrls) {

        final URLClassLoader loader = new URLClassLoader(new URL[] { url });
        for (final Plugin p : ServiceLoader.load(Plugin.class, loader)) {

            final String name = p.getClass().getName();
            if (this.enable(p)) {

                final File common = new File(this.rootConfDir, String.format(ConfigFileTemplate, name));
                final File local = new File(this.localConfDir, String.format(ConfigFileTemplate, name));
                p.init(common, local);

                this.server.attach(p);
                this.plugins.add(p);

                LOGGER.info("init", "Loading a plugin {0}", p.getClass().getName());

            }

        }

    }

    /*
     * Load a routing table.
     */
    final File route = new File(this.localConfDir, "route.conf");
    if (!route.exists()) {

        final InputStream in = this.getClass().getResourceAsStream("route.conf");
        final BufferedReader r = new BufferedReader(new InputStreamReader(in));
        final PrintWriter w = new PrintWriter(new FileWriter(route));

        String buf;
        while ((buf = r.readLine()) != null) {

            w.println(buf);

        }
        w.close();
        r.close();

    }

    final Properties routings = new Properties();
    final Reader rin = new FileReader(route);
    routings.load(rin);
    rin.close();
    for (final Object key : routings.keySet()) {

        final String skey = (String) key;
        this.router.put(skey, routings.getProperty(skey));

    }

    LOGGER.exiting("init");
}

From source file:mobac.mapsources.loader.MapPackManager.java

public void loadMapPack(File mapPackFile, MapSourcesManager mapSourcesManager)
        throws CertificateException, IOException, MapSourceCreateException {
    // testMapPack(mapPackFile);
    URLClassLoader urlCl;//from   w  w  w.  j a va  2  s .c  o m
    URL url = mapPackFile.toURI().toURL();
    urlCl = new MapPackClassLoader(url, ClassLoader.getSystemClassLoader());
    InputStream manifestIn = urlCl.getResourceAsStream("META-INF/MANIFEST.MF");
    String rev = null;
    if (manifestIn != null) {
        Manifest mf = new Manifest(manifestIn);
        rev = mf.getMainAttributes().getValue("MapPackRevision");
        manifestIn.close();
        if (rev != null) {
            if ("exported".equals(rev)) {
                rev = ProgramInfo.getRevisionStr();
            } else {
                rev = Integer.toString(Utilities.parseSVNRevision(rev));
            }
        }
        mf = null;
    }
    MapSourceLoaderInfo loaderInfo = new MapSourceLoaderInfo(LoaderType.MAPPACK, mapPackFile, rev);
    final Iterator<MapSource> iterator = ServiceLoader.load(MapSource.class, urlCl).iterator();

    while (iterator.hasNext()) {
        try {
            MapSource ms = iterator.next();
            ms.setLoaderInfo(loaderInfo);
            mapSourcesManager.addMapSource(ms);
            log.trace("Loaded map source: " + ms.toString() + " (name: " + ms.getName() + ")");
        } catch (Error e) {
            urlCl = null;
            throw new MapSourceCreateException("Failed to load a map sources from map pack: "
                    + mapPackFile.getName() + " " + e.getMessage(), e);
        }
    }
}

From source file:org.keycloak.authz.server.admin.resource.PolicyResource.java

private PolicyProviderAdminResource getPolicyProviderAdminResource(
        final @PathParam("policyType") String policyType) {
    if (!this.policyTypeResources.containsKey(policyType)) {
        for (PolicyProviderAdminResource loadedProvider : ServiceLoader.load(PolicyProviderAdminResource.class,
                getClass().getClassLoader())) {
            this.policyTypeResources.put(loadedProvider.getType(), loadedProvider);
        }//  www .  ja v a 2  s . co  m
    }

    PolicyProviderAdminResource resource = this.policyTypeResources.get(policyType);

    if (resource != null) {
        ResteasyProviderFactory.getInstance().injectProperties(resource);
        resource.init(this.resourceServer);
    }

    return resource;
}

From source file:org.nuunframework.kernel.Kernel.java

@SuppressWarnings("unchecked")
private void fetchPlugins() {
    // plugin from kernel call api
    Iterator<Plugin> iterator1 = pluginsToAdd.values().iterator();

    // TODO add unit and test integration test for this
    if (spiPluginEnabled) {
        pluginLoader = ServiceLoader.load(Plugin.class, Thread.currentThread().getContextClassLoader());

        // plugin from service loader
        Iterator<Plugin> iterator2 = pluginLoader.iterator();
        pluginIterators = Arrays.asList(iterator2, iterator1);
    } else {/*from w w  w.j  a  va 2s.c om*/
        pluginIterators = Arrays.asList(iterator1);
    }

    fetchedPlugins = new LinkedList<Plugin>();

    for (Iterator<Plugin> iterator : pluginIterators) {
        Plugin plugin;
        while (iterator.hasNext()) {
            plugin = iterator.next();
            fetchedPlugins.add(plugin);
        }

    }
}

From source file:datascript.tools.DataScriptTool.java

/**
 * Installs all extensions that are configured in the services manifest and
 * detects all options of each extension installed.
 *  //from   w ww  .j  av a 2 s.  c  om
 * @throws IOException
 * @throws InstantiationException
 * @throws IllegalAccessException
 */
private void prepareExtensions() {
    ServiceLoader<Extension> loader = ServiceLoader.load(Extension.class, getClass().getClassLoader());
    Iterator<Extension> it = loader.iterator();
    while (it.hasNext()) {
        Extension extension = it.next();
        extensions.add(extension);
        extension.getOptions(rdsOptionsToAccept);
        extension.setParameters(this);
    }
}

From source file:org.overlord.sramp.shell.ShellCommandFactory.java

/**
 * Discover any contributed commands, both on the classpath and registered
 * in the .sramp/commands.ini file in the user's home directory.
 *///www  . j a v  a  2  s  . com
private void discoverContributedCommands() {
    List<ClassLoader> commandClassloaders = new ArrayList<ClassLoader>();
    commandClassloaders.add(Thread.currentThread().getContextClassLoader());

    // Register commands listed in the user's commands.ini config file
    String userHome = System.getProperty("user.home", "/"); //$NON-NLS-1$ //$NON-NLS-2$
    String commandsDirName = System.getProperty("s-ramp.shell.commandsDir", //$NON-NLS-1$
            userHome + "/.s-ramp/commands"); //$NON-NLS-1$
    File commandsDir = new File(commandsDirName);
    if (!commandsDir.exists()) {
        commandsDir.mkdirs();
    }
    if (commandsDir.isDirectory()) {
        try {
            Collection<File> jarFiles = FileUtils.listFiles(commandsDir, new String[] { "jar" }, false); //$NON-NLS-1$
            List<URL> jarURLs = new ArrayList<URL>(jarFiles.size());
            for (File jarFile : jarFiles) {
                jarURLs.add(jarFile.toURI().toURL());
            }
            URL[] urls = jarURLs.toArray(new URL[jarURLs.size()]);
            ClassLoader extraCommandsCL = new URLClassLoader(urls,
                    Thread.currentThread().getContextClassLoader());
            commandClassloaders.add(extraCommandsCL);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // Now that we have identified all ClassLoaders to check for commands, iterate
    // through them all and use the Java ServiceLoader mechanism to actually
    // load the commands.
    for (ClassLoader classLoader : commandClassloaders) {
        for (ShellCommandProvider provider : ServiceLoader.load(ShellCommandProvider.class, classLoader)) {
            Map<String, Class<? extends ShellCommand>> commands = provider.provideCommands();
            for (Map.Entry<String, Class<? extends ShellCommand>> entry : commands.entrySet()) {
                QName qualifiedCmdName = new QName(provider.getNamespace(), entry.getKey());
                registry.put(qualifiedCmdName, entry.getValue());
            }
        }
    }
}

From source file:org.deegree.cs.persistence.CRSManager.java

/**
 * Returns all available {@link CRSStore} providers.
 * /* w  ww .  j a v  a  2  s .c  om*/
 * @return all available providers, keys: config namespace, value: provider instance
 */
private synchronized Map<String, CRSStoreProvider> getProviders() {
    if (nsToProvider == null) {
        nsToProvider = new HashMap<String, CRSStoreProvider>();
        try {
            ServiceLoader<CRSStoreProvider> loaded;
            if (workspace != null) {
                loaded = ServiceLoader.load(CRSStoreProvider.class, workspace.getModuleClassLoader());
            } else {
                loaded = ServiceLoader.load(CRSStoreProvider.class);
            }
            for (CRSStoreProvider provider : loaded) {
                LOG.debug("CRS store provider: " + provider + ", namespace: " + provider.getConfigNamespace());
                if (nsToProvider.containsKey(provider.getConfigNamespace())) {
                    LOG.error("Multiple crs store providers for config namespace: '"
                            + provider.getConfigNamespace() + "' on classpath -- omitting provider '"
                            + provider.getClass().getName() + "'.");
                    continue;
                }
                nsToProvider.put(provider.getConfigNamespace(), provider);
            }
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }

    }
    return nsToProvider;
}