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.pentaho.hadoop.shim.HadoopConfigurationLocator.java

/**
 * Locates an implementation of {@code service} using the {@link ServiceLoader}.
 *
 * @param cl Class loader to look for implementations in
 * @return The first implementation found.
 *//*from   w  w w .j av  a2s .  c  o  m*/
protected <T> T locateServiceImpl(ClassLoader cl, Class<T> service) {
    ServiceLoader<T> loader = ServiceLoader.load(service, cl);
    Iterator<T> iter = loader.iterator();
    if (iter.hasNext()) {
        return iter.next();
    }
    return null;
}

From source file:org.opoo.press.impl.FactoryImpl.java

public <T> T instantiate(Class<T> clazz) {
    ServiceLoader<T> loader = ServiceLoader.load(clazz, site.getClassLoader());
    Iterator<T> iterator = loader.iterator();
    if (iterator.hasNext()) {
        return apply(iterator.next());
    }/* w  w  w.  j av a  2s. c o  m*/

    String className = (String) configuration.get(clazz.getName());
    if (StringUtils.isBlank(className) || "none".equalsIgnoreCase(className)) {
        return null;
    }
    return newInstance(className);
}

From source file:org.opoo.press.impl.FactoryImpl.java

public <T> List<T> instantiateList(Class<T> clazz) {
    List<T> list = new ArrayList<T>();
    ServiceLoader<T> loader = ServiceLoader.load(clazz, site.getClassLoader());
    for (T t : loader) {
        t = apply(t);/*from  w  w  w .  j a  v a 2 s . c om*/
        log.debug("Load instance: {} => {}", clazz.getName(), t.getClass().getName());
        list.add(t);
    }

    Object o = configuration.get(clazz.getName());
    if (o instanceof List) {
        List<String> classNames = (List<String>) o;
        if (!classNames.isEmpty()) {
            for (String className : classNames) {
                T t = newInstance(className);
                log.debug("Create instance: {} => {}", clazz.getName(), className);
                list.add(t);
            }
        }
    } else if (o instanceof Map) {
        Map<String, String> classNames = (Map<String, String>) o;
        if (!classNames.isEmpty()) {
            for (Map.Entry<String, String> entry : classNames.entrySet()) {
                String name = entry.getKey();
                String className = entry.getValue();
                T t = newInstance(className);
                log.debug("Create instance: {} => {}", clazz.getName(), className);
                list.add(t);
            }
        }
    } else if (o != null) {
        log.warn("Configuration error: {} => {}", clazz.getName(), o);
    }

    return list;
}

From source file:org.jboss.forge.roaster.model.impl.JavaSourceImpl.java

private List<WildcardImportResolver> getImportResolvers() {
    if (resolvers == null) {
        resolvers = new ArrayList<>();
        for (WildcardImportResolver r : ServiceLoader.load(WildcardImportResolver.class,
                getClass().getClassLoader())) {
            resolvers.add(r);//ww  w .  j  av  a2s  .  c  o m
        }
    }
    if (resolvers.isEmpty()) {
        throw new IllegalStateException("No instances of [" + WildcardImportResolver.class.getName()
                + "] were found on the classpath.");
    }
    return resolvers;
}

From source file:org.opoo.press.impl.FactoryImpl.java

public <T> Map<String, T> instantiateMap(Class<T> clazz) {
    Map<String, T> map = new HashMap<String, T>();
    ServiceLoader<T> loader = ServiceLoader.load(clazz, site.getClassLoader());
    for (T t : loader) {
        if (t instanceof Named) {
            t = apply(t);//from   w ww .ja  v a  2 s.c  o m
            log.debug("Load instance for '{}': {} => {}", ((Named) t).getName(), clazz.getName(),
                    t.getClass().getName());
            map.put(((Named) t).getName(), t);
        }
    }

    Object o = configuration.get(clazz.getName());
    if (o instanceof List) {
        List<String> classNames = (List<String>) o;
        if (!classNames.isEmpty()) {
            for (String className : classNames) {
                T t = newInstance(className);
                if (t instanceof Named) {
                    log.debug("Create instance for '{}': {} => {}", ((Named) t).getName(), clazz.getName(),
                            className);
                    map.put(((Named) t).getName(), t);
                }
            }
        }

    } else if (o instanceof Map) {
        Map<String, String> classNames = (Map<String, String>) o;
        if (!classNames.isEmpty()) {
            for (Map.Entry<String, String> entry : classNames.entrySet()) {
                String name = entry.getKey();
                String className = entry.getValue();
                T t = newInstance(className);
                log.debug("Create instance for '{}': {} => {}", name, clazz.getName(), className);
                map.put(name, t);
            }
        }
    } else if (o != null) {
        log.warn("Configuration error: {} => {}", clazz.getName(), o);
    }

    return map;
}

From source file:org.terracotta.config.TCConfigurationParser.java

private static ServiceLoader<ServiceConfigParser> loadConfigurationParserClasses(ClassLoader loader) {
    return ServiceLoader.load(ServiceConfigParser.class, loader);
}

From source file:org.jpos.q2.Q2.java

private void startOSGIFramework() throws BundleException {
    Iterator<FrameworkFactory> iter = ServiceLoader.load(FrameworkFactory.class, loader).iterator();
    if (iter.hasNext()) {
        FrameworkFactory frameworkFactory = iter.next();
        Map<String, String> config = new HashMap<String, String>();
        osgiFramework = frameworkFactory.newFramework(config);
        osgiFramework.start();//  w ww .  ja v  a2 s.c om
    } else {
        getLog().warn("OSGI framework not found");
    }
}

From source file:com.raise.orgs.impl.cfg.ProcessEngineConfigurationImpl.java

protected void initConfigurators() {

    allConfigurators = new ArrayList<ProcessEngineConfigurator>();

    // Configurators that are explicitely added to the config
    if (configurators != null) {
        for (ProcessEngineConfigurator configurator : configurators) {
            allConfigurators.add(configurator);
        }// ww  w  . j  a v a  2s  .  co m
    }

    // Auto discovery through ServiceLoader
    if (enableConfiguratorServiceLoader) {
        ClassLoader classLoader = getClassLoader();
        if (classLoader == null) {
            classLoader = ReflectUtil.getClassLoader();
        }

        ServiceLoader<ProcessEngineConfigurator> configuratorServiceLoader = ServiceLoader
                .load(ProcessEngineConfigurator.class, classLoader);
        int nrOfServiceLoadedConfigurators = 0;
        for (ProcessEngineConfigurator configurator : configuratorServiceLoader) {
            allConfigurators.add(configurator);
            nrOfServiceLoadedConfigurators++;
        }

        if (nrOfServiceLoadedConfigurators > 0) {
            log.info("Found {} auto-discoverable Process Engine Configurator{}",
                    nrOfServiceLoadedConfigurators++, nrOfServiceLoadedConfigurators > 1 ? "s" : "");
        }

        if (allConfigurators.size() > 0) {

            // Order them according to the priorities (usefule for dependent configurator)
            Collections.sort(allConfigurators, new Comparator<ProcessEngineConfigurator>() {
                @Override
                public int compare(ProcessEngineConfigurator configurator1,
                        ProcessEngineConfigurator configurator2) {
                    int priority1 = configurator1.getPriority();
                    int priority2 = configurator2.getPriority();

                    if (priority1 < priority2) {
                        return -1;
                    } else if (priority1 > priority2) {
                        return 1;
                    }
                    return 0;
                }
            });

            // Execute the configurators
            log.info("Found {} Process Engine Configurators in total:", allConfigurators.size());
            for (ProcessEngineConfigurator configurator : allConfigurators) {
                log.info("{} (priority:{})", configurator.getClass(), configurator.getPriority());
            }

        }

    }
}

From source file:org.codehaus.enunciate.modules.BasicAppModule.java

/**
 * Whether to exclude a file from copying to the WEB-INF/lib directory.
 *
 * @param file The file to exclude./*from   ww w  .  j  ava2 s .c  om*/
 * @return Whether to exclude a file from copying to the lib directory.
 */
protected boolean knownExclude(File file) throws IOException {
    //instantiate a loader with this library only in its path...
    URLClassLoader loader = new URLClassLoader(new URL[] { file.toURL() }, null);
    if (loader.findResource("META-INF/enunciate/preserve-in-war") != null) {
        debug("%s is a known include because it contains the entry META-INF/enunciate/preserve-in-war.", file);
        //if a jar happens to have the enunciate "preserve-in-war" file, it is NOT excluded.
        return false;
    } else if (loader
            .findResource(com.sun.tools.apt.Main.class.getName().replace('.', '/').concat(".class")) != null) {
        debug("%s is a known exclude because it appears to be tools.jar.", file);
        //exclude tools.jar.
        return true;
    } else if (loader.findResource(
            net.sf.jelly.apt.Context.class.getName().replace('.', '/').concat(".class")) != null) {
        debug("%s is a known exclude because it appears to be apt-jelly.", file);
        //exclude apt-jelly-core.jar
        return true;
    } else if (loader.findResource(net.sf.jelly.apt.freemarker.FreemarkerModel.class.getName().replace('.', '/')
            .concat(".class")) != null) {
        debug("%s is a known exclude because it appears to be the apt-jelly-freemarker libs.", file);
        //exclude apt-jelly-freemarker.jar
        return true;
    } else if (loader.findResource(
            freemarker.template.Configuration.class.getName().replace('.', '/').concat(".class")) != null) {
        debug("%s is a known exclude because it appears to be the freemarker libs.", file);
        //exclude freemarker.jar
        return true;
    } else if (loader.findResource(Enunciate.class.getName().replace('.', '/').concat(".class")) != null) {
        debug("%s is a known exclude because it appears to be the enunciate core jar.", file);
        //exclude enunciate-core.jar
        return true;
    } else if (loader.findResource("javax/servlet/ServletContext.class") != null) {
        debug("%s is a known exclude because it appears to be the servlet api.", file);
        //exclude the servlet api.
        return true;
    } else if (loader.findResource(
            "org/codehaus/enunciate/modules/xfire_client/EnunciatedClientSoapSerializerHandler.class") != null) {
        debug("%s is a known exclude because it appears to be the enunciated xfire client tools jar.", file);
        //exclude xfire-client-tools
        return true;
    } else if (loader.findResource("javax/swing/SwingBeanInfoBase.class") != null) {
        debug("%s is a known exclude because it appears to be dt.jar.", file);
        //exclude dt.jar
        return true;
    } else if (loader.findResource("HTMLConverter.class") != null) {
        debug("%s is a known exclude because it appears to be htmlconverter.jar.", file);
        return true;
    } else if (loader.findResource("sun/tools/jconsole/JConsole.class") != null) {
        debug("%s is a known exclude because it appears to be jconsole.jar.", file);
        return true;
    } else if (loader.findResource("sun/jvm/hotspot/debugger/Debugger.class") != null) {
        debug("%s is a known exclude because it appears to be sa-jdi.jar.", file);
        return true;
    } else if (loader.findResource("sun/io/ByteToCharDoubleByte.class") != null) {
        debug("%s is a known exclude because it appears to be charsets.jar.", file);
        return true;
    } else if (loader.findResource("com/sun/deploy/ClientContainer.class") != null) {
        debug("%s is a known exclude because it appears to be deploy.jar.", file);
        return true;
    } else if (loader.findResource("com/sun/javaws/Globals.class") != null) {
        debug("%s is a known exclude because it appears to be javaws.jar.", file);
        return true;
    } else if (loader.findResource("javax/crypto/SecretKey.class") != null) {
        debug("%s is a known exclude because it appears to be jce.jar.", file);
        return true;
    } else if (loader.findResource("sun/net/www/protocol/https/HttpsClient.class") != null) {
        debug("%s is a known exclude because it appears to be jsse.jar.", file);
        return true;
    } else if (loader.findResource("sun/plugin/JavaRunTime.class") != null) {
        debug("%s is a known exclude because it appears to be plugin.jar.", file);
        return true;
    } else if (loader.findResource("com/sun/corba/se/impl/activation/ServerMain.class") != null) {
        debug("%s is a known exclude because it appears to be rt.jar.", file);
        return true;
    } else if (ServiceLoader.load(DeploymentModule.class, loader).iterator().hasNext()) {
        debug("%s is a known exclude because it appears to be an enunciate module.", file);
        //exclude by default any deployment module libraries.
        return true;
    }

    return false;
}

From source file:org.activiti5.engine.impl.cfg.ProcessEngineConfigurationImpl.java

protected void initConfigurators() {

    allConfigurators = new ArrayList<ProcessEngineConfigurator>();

    // Configurators that are explicitely added to the config
    if (configurators != null) {
        for (ProcessEngineConfigurator configurator : configurators) {
            allConfigurators.add(configurator);
        }// w ww.j a va 2s  .  co m
    }

    // Auto discovery through ServiceLoader
    if (enableConfiguratorServiceLoader) {
        ClassLoader classLoader = getClassLoader();
        if (classLoader == null) {
            classLoader = ReflectUtil.getClassLoader();
        }

        ServiceLoader<ProcessEngineConfigurator> configuratorServiceLoader = ServiceLoader
                .load(ProcessEngineConfigurator.class, classLoader);
        int nrOfServiceLoadedConfigurators = 0;
        for (ProcessEngineConfigurator configurator : configuratorServiceLoader) {
            allConfigurators.add(configurator);
            nrOfServiceLoadedConfigurators++;
        }

        if (nrOfServiceLoadedConfigurators > 0) {
            log.info("Found {} auto-discoverable Process Engine Configurator{}",
                    nrOfServiceLoadedConfigurators++, nrOfServiceLoadedConfigurators > 1 ? "s" : "");
        }

        if (!allConfigurators.isEmpty()) {

            // Order them according to the priorities (usefule for dependent configurator)
            Collections.sort(allConfigurators, new Comparator<ProcessEngineConfigurator>() {
                @Override
                public int compare(ProcessEngineConfigurator configurator1,
                        ProcessEngineConfigurator configurator2) {
                    int priority1 = configurator1.getPriority();
                    int priority2 = configurator2.getPriority();

                    if (priority1 < priority2) {
                        return -1;
                    } else if (priority1 > priority2) {
                        return 1;
                    }
                    return 0;
                }
            });

            // Execute the configurators
            log.info("Found {} Process Engine Configurators in total:", allConfigurators.size());
            for (ProcessEngineConfigurator configurator : allConfigurators) {
                log.info("{} (priority:{})", configurator.getClass(), configurator.getPriority());
            }

        }

    }
}