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(Class<S> service) 

Source Link

Document

Creates a new service loader for the given service type, using the current thread's java.lang.Thread#getContextClassLoader context class loader .

Usage

From source file:com.googlecode.fascinator.api.PluginManager.java

/**
 * Get a list of harvester plugins/*from  w  w  w.  j a  va  2s . c  o m*/
 *
 * @return map of harvester plugins, or empty map if not found
 */
public static Map<String, Harvester> getHarvesterPlugins() {
    Map<String, Harvester> harvesters = new HashMap<String, Harvester>();
    ServiceLoader<Harvester> plugins = ServiceLoader.load(Harvester.class);
    for (Harvester plugin : plugins) {
        harvesters.put(plugin.getId(), plugin);
    }
    return harvesters;
}

From source file:org.jboss.set.aphrodite.Aphrodite.java

private void initialiseStreams(AphroditeConfig mutableConfig) throws AphroditeException {
    if (mutableConfig.getStreamConfigs().isEmpty() && repositories.isEmpty()) {
        throw new AphroditeException("Unable to initialise any Stream Services as no "
                + RepositoryService.class.getName() + " have been created.");
    }//from  w w w  .  j  a va 2  s .c om

    for (StreamService ss : ServiceLoader.load(StreamService.class)) {
        try {
            boolean initialised = ss.init(this, mutableConfig);
            if (initialised)
                streamServices.add(ss);
        } catch (NotFoundException e) {
            throw new AphroditeException(
                    "Unable to initiatilise Aphrodite as an error was thrown when initiating "
                            + ss.getClass().getName() + ": " + e);
        }
    }
}

From source file:datascript.instance.DataScriptInstanceTool.java

private void prepareExtensions(String[] args)
        throws IOException, InstantiationException, IllegalAccessException {
    if (cli == null)
        return;/*from w  ww .j a v  a2 s  . c  o  m*/

    // normalize slashes and backslashes
    fileName = new File(args[args.length - 1]).getPath();

    extensions = new ArrayList<Extension>();
    ServiceLoader<Extension> loader = ServiceLoader.load(Extension.class);
    Iterator<Extension> it = loader.iterator();
    while (it.hasNext()) {
        Extension extension = it.next();
        extensions.add(extension);
        extension.getOptions(rdsOptions);
    }

    CmdLineParser parser = new CmdLineParser();
    try {
        cli = parser.parse(rdsOptions, args, false);
    } catch (ParseException pe) {
        HelpFormatter hf = new HelpFormatter();
        hf.printHelp(pe.getMessage(), rdsOptions);
    }

    for (Extension extension : extensions) {
        extension.setParameters(this);
    }
}

From source file:org.apache.ace.agent.launcher.Launcher.java

private FrameworkFactory loadFrameworkFactory() throws IllegalStateException {
    ServiceLoader<FrameworkFactory> frameworkFactoryLoader = ServiceLoader.load(FrameworkFactory.class);
    Iterator<FrameworkFactory> frameworkFactoryIterator = frameworkFactoryLoader.iterator();
    if (!frameworkFactoryIterator.hasNext()) {
        throw new IllegalStateException("Unable to load any FrameworkFactory");
    }//from   www  .  jav a2s  .  c  om
    return frameworkFactoryIterator.next();
}

From source file:org.sikuli.scriptrunner.ScriptRunner.java

public static void initScriptingSupport() {
    if (isReady) {
        return;/*from  ww  w. j a v  a2s  .  c  om*/
    }
    log(lvl, "initScriptingSupport: enter");
    if (scriptRunner.isEmpty()) {
        EndingTypes.put("py", CPYTHON);
        EndingTypes.put("rb", CRUBY);
        EndingTypes.put("txt", CPLAIN);
        for (String k : EndingTypes.keySet()) {
            typeEndings.put(EndingTypes.get(k), k);
        }
        ServiceLoader<IScriptRunner> rloader = ServiceLoader.load(IScriptRunner.class);
        Iterator<IScriptRunner> rIterator = rloader.iterator();
        while (rIterator.hasNext()) {
            IScriptRunner current = null;
            try {
                current = rIterator.next();
            } catch (ServiceConfigurationError e) {
                log(lvl, "initScriptingSupport: warning: %s", e.getMessage());
                continue;
            }
            String name = current.getName();
            if (name != null && !name.startsWith("Not")) {
                scriptRunner.put(name, current);
                current.init(null);
                log(lvl, "initScriptingSupport: added: %s", name);
            }
        }
    }
    if (scriptRunner.isEmpty()) {
        Debug.error("Settings: No scripting support available. Rerun Setup!");
        String em = "Terminating: No scripting support available. Rerun Setup!";
        log(-1, em);
        if (Settings.isRunningIDE) {
            Sikulix.popError(em, "IDE has problems ...");
        }
        System.exit(1);
    } else {
        RDEFAULT = (String) scriptRunner.keySet().toArray()[0];
        EDEFAULT = scriptRunner.get(RDEFAULT).getFileEndings()[0];
        for (IScriptRunner r : scriptRunner.values()) {
            for (String e : r.getFileEndings()) {
                if (!supportedRunner.containsKey(EndingTypes.get(e))) {
                    supportedRunner.put(EndingTypes.get(e), r);
                }
            }
        }
    }
    log(lvl, "initScriptingSupport: exit with defaultrunner: %s (%s)", RDEFAULT, EDEFAULT);
    isReady = true;
}

From source file:org.ejbca.ui.web.admin.configuration.CustomCertExtensionMBean.java

public List<SelectItem> getAvailableCustomCertificateExtensions() {
    if (availableCertificateExtensions == null) {
        availableCertificateExtensions = new HashMap<String, CustomCertificateExtension>();
        availableCertificateExtensionsList = new ArrayList<SelectItem>();
        ServiceLoader<? extends CustomCertificateExtension> serviceLoader = ServiceLoader
                .load(CustomCertificateExtension.class);
        for (CustomCertificateExtension extension : serviceLoader) {
            availableCertificateExtensionsList
                    .add(new SelectItem(extension.getClass().getCanonicalName(), extension.getDisplayName()));
            availableCertificateExtensions.put(extension.getClass().getCanonicalName(), extension);
        }//from   w  w w  .  j ava2  s .co  m
        Collections.sort(availableCertificateExtensionsList, new Comparator<SelectItem>() {
            @Override
            public int compare(SelectItem o1, SelectItem o2) {
                return o1.getLabel().compareTo(o2.getLabel());
            }
        });
    }
    return availableCertificateExtensionsList;
}

From source file:io.bifroest.commons.boot.BootLoaderNG.java

/**
 * Finds all subsystems provided via ServiceLoader
 *///from ww  w . j  ava  2s . com
@SuppressWarnings("unchecked")
private void findAvailableSubsystems() {
    for (Subsystem<E> sub : ServiceLoader.load(Subsystem.class)) {
        systemsAvailable.put(sub.getSystemIdentifier(), sub);
        log.debug("Found: " + sub.getSystemIdentifier());
    }
}

From source file:com.googlecode.fascinator.api.PluginManager.java

/**
 * Gets a indexer plugin/*  ww  w  .jav  a  2 s. c o m*/
 *
 * @param id plugin identifier
 * @return a indexer plugin, or null if not found
 */
public static Indexer getIndexer(String id) {
    Class<Indexer> clazz = (Class<Indexer>) cache.getIfPresent("indexer" + id);
    if (clazz != null) {
        try {
            return clazz.newInstance();
        } catch (Exception e) {
            // Throwing RuntimeException to keep it unchecked
            // TODO: Remove later
            throw new RuntimeException(e);
        }
    }
    ServiceLoader<Indexer> plugins = ServiceLoader.load(Indexer.class);
    for (Indexer plugin : plugins) {
        if (id.equals(plugin.getId())) {
            return plugin;
        }
    }
    File groovyFile = getPathFile("plugins/indexer/" + id + ".groovy");
    if (groovyFile.exists()) {
        GroovyClassLoader gcl = new GroovyClassLoader();
        try {
            clazz = gcl.parseClass(groovyFile);
            cache.put("indexer" + id, clazz);
            return clazz.newInstance();

        } catch (Exception e) {
            // Throwing RuntimeException to keep it unchecked
            // TODO: Remove later
            throw new RuntimeException(e);
        }

    }

    return null;
}

From source file:org.corpus_tools.pepper.connectors.impl.PepperOSGiConnector.java

/**
 * Starts the OSGi Equinox environment./*ww w  . ja  v  a  2 s.com*/
 * 
 * @return
 * @throws Exception
 */
protected BundleContext startEquinox() throws Exception {
    BundleContext bc = null;

    frameworkProperties = new HashMap<String, String>();
    frameworkProperties.put(Constants.FRAMEWORK_SYSTEMPACKAGES_EXTRA, getSharedPackages());
    frameworkProperties.put(EclipseStarter.PROP_CLEAN, "true");
    frameworkProperties.put(EclipseStarter.PROP_CONSOLE, "true");
    frameworkProperties.put(EclipseStarter.PROP_NOSHUTDOWN, "true");
    frameworkProperties.put(EclipseStarter.PROP_INSTALL_AREA,
            getConfiguration().getTempPath().getCanonicalPath());

    /*
     * Use implementation-independent OSGi framework launching API* to be
     * able to launch more than one framework instance. This might be needed
     * by library consumers which are running Pepper from within an OSGi
     * framework (e.g., Atomic).
     * 
     * The framework launching API uses the Java SPI mechanism to load a
     * framework factory?. This assumes that there is an R4.1-compliant
     * OSGi framework on the classpath.
     * 
     * *Instead of EclipseStarter.
     */
    FrameworkFactory frameworkFactory = ServiceLoader.load(FrameworkFactory.class).iterator().next();
    Framework oSGiframework = frameworkFactory.newFramework(frameworkProperties);
    oSGiframework.start();
    bc = oSGiframework.getBundleContext();

    return bc;
}

From source file:com.fitbur.testify.system.SpringSystemTest.java

public ServerContext getServerContext(TestContext testContext, String methodName) {
    Object testInstance = testContext.getTestInstance();
    return testContext.getAnnotation(App.class).map(p -> {
        Class<?> appType = p.value();
        ServiceLoader<ServerProvider> serviceLoader = ServiceLoader.load(ServerProvider.class);
        ArrayList<ServerProvider> serverProviders = Lists.newArrayList(serviceLoader);

        checkState(!serverProviders.isEmpty(),
                "ServiceProvider provider implementation not found in the classpath");

        checkState(serverProviders.size() == 1,
                "Multiple ServiceProvider provider implementations found in the classpath. "
                        + "Please insure there is only one ServiceProvider provider implementation "
                        + "in the classpath.");
        ServerProvider provider = serverProviders.get(0);

        interceptor = new SpringSystemServletInterceptor(testContext, methodName, serviceAnnotations,
                classTestNeeds, classTestNeedContainers);

        Class<?> proxyAppType = BYTE_BUDDY.subclass(appType).method(not(isDeclaredBy(Object.class)))
                .intercept(to(interceptor).filter(not(isDeclaredBy(Object.class)))).make()
                .load(getClass().getClassLoader(), ClassLoadingStrategy.Default.WRAPPER).getLoaded();

        Set<Class<?>> handles = new HashSet<>();
        handles.add(proxyAppType);/*w w  w.  java2  s  . c o  m*/
        SpringServletContainerInitializer initializer = new SpringServletContainerInitializer();

        SpringSystemServerDescriptor descriptor = new SpringSystemServerDescriptor(p, testContext, initializer,
                handles);

        Object configuration = provider.configuration(descriptor);
        testContext.getConfigMethod(configuration.getClass()).map(m -> m.getMethod()).ifPresent(m -> {
            AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
                try {
                    m.setAccessible(true);
                    m.invoke(testInstance, configuration);
                } catch (Exception e) {
                    checkState(false, "Call to config method '%s' in test class '%s' failed.", m.getName(),
                            descriptor.getTestClassName());
                    throw Throwables.propagate(e);
                }

                return null;
            });
        });

        ServerInstance serverInstance = provider.init(descriptor, configuration);
        serverInstance.start();

        SpringServiceLocator serviceLocator = interceptor.getServiceLocator();

        serviceLocator.addConstant(serverInstance.getClass().getSimpleName(), serverInstance);

        ServerContext serverContext = new ServerContext(provider, descriptor, serverInstance, serviceLocator,
                configuration);
        serviceLocator.addConstant(serverContext.getClass().getSimpleName(), serverContext);

        TestCaseInstance testCaseInstance = new TestCaseInstance(methodName, testInstance);
        serviceLocator.addConstant(testCaseInstance.getTestName(), testCaseInstance);

        return serverContext;

    }).get();
}