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:net.sourceforge.pmd.lang.LanguageRegistry.java

private LanguageRegistry() {
    List<Language> languagesList = new ArrayList<>();
    // Use current class' classloader instead of the threads context classloader, see https://github.com/pmd/pmd/issues/1377
    ServiceLoader<Language> languageLoader = ServiceLoader.load(Language.class, getClass().getClassLoader());
    Iterator<Language> iterator = languageLoader.iterator();
    while (iterator.hasNext()) {
        try {//from   w  w w .  j  a v a  2  s  .  c  o  m
            Language language = iterator.next();
            languagesList.add(language);
        } catch (UnsupportedClassVersionError e) {
            // Some languages require java8 and are therefore only available
            // if java8 or later is used as runtime.
            System.err.println("Ignoring language for PMD: " + e.toString());
        }
    }

    // sort languages by terse name. Avoiding differences in the order of languages
    // across JVM versions / OS.
    Collections.sort(languagesList, new Comparator<Language>() {
        @Override
        public int compare(Language o1, Language o2) {
            return o1.getTerseName().compareToIgnoreCase(o2.getTerseName());
        }
    });

    // using a linked hash map to maintain insertion order
    languages = new LinkedHashMap<>();
    for (Language language : languagesList) {
        languages.put(language.getName(), language);
    }
}

From source file:uniol.apt.module.AptModuleRegistry.java

private AptModuleRegistry() {
    super();//from  ww  w. java  2  s.c o  m
    for (Module module : ServiceLoader.load(Module.class, getClass().getClassLoader())) {
        String moduleName = module.getClass().getCanonicalName();
        String name = module.getName();
        if (name == null || name.equals("") || !name.equals(name.toLowerCase())) {
            throw new RuntimeException(
                    String.format("Module %s reports an invalid name: %s", moduleName, name));
        }
        Module oldModule = findModule(name);
        if (oldModule != null && !oldModule.getClass().equals(module.getClass())) {
            throw new RuntimeException(String.format("Different modules claim, to have name %s:" + " %s and %s",
                    name, oldModule.getClass().getCanonicalName(), moduleName));
        }
        registerModule(module);
    }

}

From source file:de.zib.gndms.infra.system.PluggableTaskFlowProvider.java

public void loadPlugins(boolean checkDeps) {

    Map<String, TaskFlowFactory> plugins = new HashMap<String, TaskFlowFactory>(10);

    ServiceLoader<TaskFlowFactory> sl;
    if (getCl() != null)
        sl = ServiceLoader.load(TaskFlowFactory.class, getCl());
    else/*w  w  w .  j a va 2  s .  c om*/
        sl = ServiceLoader.load(TaskFlowFactory.class);

    for (TaskFlowFactory bp : sl) {
        try {
            register(bp, plugins);
        } catch (IllegalStateException e) {
            logger.warn(e.getMessage());
        }
    }

    setFactories(plugins);

    if (checkDeps)
        checkDeps();

    // call all PostConstruct methods
    for (TaskFlowFactory bp : sl) {
        for (Method method : bp.getClass().getDeclaredMethods()) {
            if (method.getAnnotation(PostConstruct.class) != null) {
                ReflectionUtils.makeAccessible(method);
                try {
                    method.invoke(bp, (Object[]) null);
                } catch (IllegalAccessException e) {
                    throw new RuntimeException(
                            "THIS IS NOT HAPPENING!!! Method had been made accessible but is not accessible anyway",
                            e);
                } catch (InvocationTargetException e) {
                    throw new RuntimeException(
                            "Could not call PostConstruct method (" + method.toGenericString() + ")", e);
                }
            }
        }
    }

    // todo this is just for development change this for releases:
    //        if ( getFactories().size() == 0 )
    //            throw new IllegalStateException( "no plugs found" );
}

From source file:org.teavm.classlib.java.lang.ClassLoaderNativeGenerator.java

private void generateSupplyResources(InjectorContext context) throws IOException {
    SourceWriter writer = context.getWriter();
    writer.append("{").indent();

    ClassLoader classLoader = context.getClassLoader();
    Set<String> resourceSet = new HashSet<>();
    SupplierContextImpl supplierContext = new SupplierContextImpl(context);
    for (ResourceSupplier supplier : ServiceLoader.load(ResourceSupplier.class, classLoader)) {
        String[] resources = supplier.supplyResources(supplierContext);
        if (resources != null) {
            resourceSet.addAll(Arrays.asList(resources));
        }/* www.  j av  a  2  s  .  c o  m*/
    }

    boolean first = true;
    for (String resource : resourceSet) {
        try (InputStream input = classLoader.getResourceAsStream(resource)) {
            if (input == null) {
                continue;
            }
            if (!first) {
                writer.append(',');
            }
            first = false;
            writer.newLine();
            String data = Base64.getEncoder().encodeToString(IOUtils.toByteArray(input));
            writer.append("\"").append(RenderingUtil.escapeString(resource)).append("\"");
            writer.ws().append(':').ws();
            writer.append("\"").append(data).append("\"");
        }
    }

    if (!first) {
        writer.newLine();
    }
    writer.outdent().append('}');
}

From source file:verdandi.plugin.PluginLoader.java

private void load(ClassLoader classLoader) {
    ServiceLoader<VerdandiPlugin> serviceLoader = ServiceLoader.load(VerdandiPlugin.class, classLoader);
    for (VerdandiPlugin verdandiPlugin : serviceLoader) {
        if (!classAlreadyLoaded(verdandiPlugin.getClass())) {
            plugins.add(verdandiPlugin);
        }//  w  w  w . j a  v a2  s .  co m
        LOG.debug("Loaded plugin " + verdandiPlugin.getClass().getCanonicalName());
    }

}

From source file:org.wso2.carbon.apimgt.tracing.TracingServiceImpl.java

private TracingServiceImpl() {
    try {/*from  w w  w.j  a v a  2s .  com*/
        String openTracerName = configuration.getFirstProperty(TracingConstants.OPEN_TRACER_NAME) != null
                ? configuration.getFirstProperty(TracingConstants.OPEN_TRACER_NAME)
                : TracingConstants.DEFAULT_OPEN_TRACER_NAME;

        Boolean remoteTracerEnabled = Boolean
                .valueOf(configuration.getFirstProperty(TracingConstants.OPEN_TRACER_ENABLED) != null
                        ? configuration.getFirstProperty(TracingConstants.OPEN_TRACER_ENABLED)
                        : TracingConstants.DEFAULT_OPEN_TRACER_ENABLED);

        String tracerName = (openTracerName != null && remoteTracerEnabled) ? openTracerName
                : TracingConstants.LOG;

        ServiceLoader<OpenTracer> openTracers = ServiceLoader.load(OpenTracer.class,
                OpenTracer.class.getClassLoader());
        Iterator iterator = openTracers.iterator();
        while (iterator.hasNext()) {
            OpenTracer openTracer = (OpenTracer) iterator.next();
            if (tracerName.equalsIgnoreCase(openTracer.getName())) {
                this.tracer = openTracer;
            }
        }
    } catch (Exception e) {
        log.error("Error in reading openTracerName", e);
    }
}

From source file:org.commonjava.test.compile.CompilerFixxxtureTest.java

@Test
public void compileDependingOnlyOnJDK_UseServiceLoader() throws Exception {
    final CompilerResult result = compiler.compileSourceDirWithThisClass("jdk-only-service", "org.test.Hello");

    FileUtils.write(Paths.get(result.getClasses().getAbsolutePath(), "META-INF", "services", "org.test.IHello")
            .toFile(), "org.test.Hello");

    final URLClassLoader ucl = result.getClassLoader();
    final Class<?> cls = ucl.loadClass("org.test.IHello");
    final ServiceLoader<?> loader = ServiceLoader.load(cls, ucl);
    final Object object = loader.iterator().next();

    final Method method = cls.getMethod("hello", new Class[] { String[].class });

    System.out.println(method);/*from  ww  w  .jav a  2s .  com*/
    method.invoke(object, new Object[] { new String[] { "Tester" } });
}

From source file:org.overlord.dtgov.services.deploy.DeployerFactory.java

/**
 * Loads any dtgov deployers. These can be contributed via the standard Java
 * service loading mechanism./*  w ww  . j a v a  2 s  . com*/
 */
private static void loadDeployers() {
    // First load via the standard ServiceRegistry mechanism.
    Set<DeployerProvider> providers = ServiceRegistryUtil.getServices(DeployerProvider.class);
    for (DeployerProvider provider : providers) {
        Map<String, Deployer> deployers_provider = provider.createDeployers();
        if (deployers_provider != null && !deployers_provider.isEmpty()) {
            deployers.putAll(deployers_provider);
        }
    }

    // Allow users to provide a directory path where we will check for JARs
    // that
    // contain Deployer implementations.
    Collection<ClassLoader> loaders = new LinkedList<ClassLoader>();
    String customDeployerDirPath = System.getProperty(DTGovConstants.DTGOV_CUSTOM_DEPLOYERS_DIR);
    if (customDeployerDirPath != null && customDeployerDirPath.trim().length() > 0) {
        File directory = new File(customDeployerDirPath);
        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 DeployerProvider implementations
    for (ClassLoader loader : loaders) {
        for (DeployerProvider provider : ServiceLoader.load(DeployerProvider.class, loader)) {
            Map<String, Deployer> deployers_provider = provider.createDeployers();
            if (deployers_provider != null && !deployers_provider.isEmpty()) {
                deployers.putAll(deployers_provider);
            }
        }
    }
}

From source file:com.intelligentsia.dowsers.entity.reference.ReferenceTest.java

@Test
public void testReferenceFactoryProviderReference() {
    final ServiceLoader<ReferenceFactory> loader = ServiceLoader.load(ReferenceFactory.class,
            Thread.currentThread().getContextClassLoader());
    assertTrue(loader.iterator().hasNext());
    final Reference urn = new Reference(Person.class);
    assertEquals("com.intelligentsia.dowsers.entity.model.Person", urn.getEntityClassName());
}

From source file:org.pentaho.database.service.ServiceLoaderDatabaseDialectProvider.java

public ServiceLoaderDatabaseDialectProvider() {
    this(databaseDialectClass -> ServiceLoader.load(databaseDialectClass,
            ServiceLoaderDatabaseDialectProvider.class.getClassLoader()));
}