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 transformer plugins//from www.j  a  va 2s  .c  om
 *
 * @return map of transformer plugins, or empty map if not found
 */
public static Map<String, Transformer> getTransformerPlugins() {
    Map<String, Transformer> transformers = new HashMap<String, Transformer>();
    ServiceLoader<Transformer> plugins = ServiceLoader.load(Transformer.class);
    for (Transformer plugin : plugins) {
        transformers.put(plugin.getId(), plugin);
    }
    return transformers;
}

From source file:org.apache.tinkerpop.gremlin.groovy.engine.GremlinExecutor.java

private ScriptEngines createScriptEngines() {
    // plugins already on the path - ones static to the classpath
    final List<GremlinPlugin> globalPlugins = new ArrayList<>();
    ServiceLoader.load(GremlinPlugin.class).forEach(globalPlugins::add);

    return new ScriptEngines(se -> {
        // this first part initializes the scriptengines Map
        for (Map.Entry<String, EngineSettings> config : settings.entrySet()) {
            final String language = config.getKey();
            se.reload(language, new HashSet<>(config.getValue().getImports()),
                    new HashSet<>(config.getValue().getStaticImports()), config.getValue().getConfig());
        }/*w w  w .  j av  a2 s.  c om*/

        // use grabs dependencies and returns plugins to load
        final List<GremlinPlugin> pluginsToLoad = new ArrayList<>(globalPlugins);
        use.forEach(u -> {
            if (u.size() != 3)
                logger.warn(
                        "Could not resolve dependencies for [{}].  Each entry for the 'use' configuration must include [groupId, artifactId, version]",
                        u);
            else {
                logger.info("Getting dependencies for [{}]", u);
                pluginsToLoad.addAll(se.use(u.get(0), u.get(1), u.get(2)));
            }
        });

        // now that all dependencies are in place, the imports can't get messed up if a plugin tries to execute
        // a script (as the script engine appends the import list to the top of all scripts passed to the engine).
        // only enable those plugins that are configured to be enabled.
        se.loadPlugins(pluginsToLoad.stream().filter(plugin -> enabledPlugins.contains(plugin.getName()))
                .collect(Collectors.toList()));

        // initialization script eval can now be performed now that dependencies are present with "use"
        for (Map.Entry<String, EngineSettings> config : settings.entrySet()) {
            final String language = config.getKey();

            // script engine initialization files that fail will only log warnings - not fail server initialization
            final AtomicBoolean hasErrors = new AtomicBoolean(false);
            config.getValue().getScripts().stream().map(File::new).filter(f -> {
                if (!f.exists()) {
                    logger.warn("Could not initialize {} ScriptEngine with {} as file does not exist", language,
                            f);
                    hasErrors.set(true);
                }

                return f.exists();
            }).map(f -> {
                try {
                    return Pair.with(f, Optional.of(new FileReader(f)));
                } catch (IOException ioe) {
                    logger.warn("Could not initialize {} ScriptEngine with {} as file could not be read - {}",
                            language, f, ioe.getMessage());
                    hasErrors.set(true);
                    return Pair.with(f, Optional.<FileReader>empty());
                }
            }).filter(p -> p.getValue1().isPresent()).map(p -> Pair.with(p.getValue0(), p.getValue1().get()))
                    .forEachOrdered(p -> {
                        try {
                            final Bindings bindings = new SimpleBindings();
                            bindings.putAll(globalBindings);

                            // evaluate init scripts with hard reference so as to ensure it doesn't get garbage collected
                            bindings.put(GremlinGroovyScriptEngine.KEY_REFERENCE_TYPE,
                                    GremlinGroovyScriptEngine.REFERENCE_TYPE_HARD);

                            // the returned object should be a Map of initialized global bindings
                            final Object initializedBindings = se.eval(p.getValue1(), bindings, language);
                            if (initializedBindings != null && initializedBindings instanceof Map)
                                globalBindings.putAll((Map) initializedBindings);
                            else
                                logger.warn(
                                        "Initialization script {} did not return a Map - no global bindings specified",
                                        p.getValue0());

                            logger.info("Initialized {} ScriptEngine with {}", language, p.getValue0());
                        } catch (ScriptException sx) {
                            hasErrors.set(true);
                            logger.warn(
                                    "Could not initialize {} ScriptEngine with {} as script could not be evaluated - {}",
                                    language, p.getValue0(), sx.getMessage());
                        }
                    });
        }
    });
}

From source file:org.mrgeo.mapalgebra.MapAlgebraParser.java

public TreeMap<Integer, MapAlgebraPreprocessor> getPreprocessors() {
    if (_preprocessors == null) {
        ServiceLoader<MapAlgebraPreprocessor> loader = ServiceLoader.load(MapAlgebraPreprocessor.class);

        _preprocessors = new TreeMap<Integer, MapAlgebraPreprocessor>();

        for (MapAlgebraPreprocessor s : loader) {
            _preprocessors.put(s.getOrder(), s);
        }//from ww w  .  j a va2  s .  co m
    }

    return _preprocessors;
}

From source file:org.opencms.ui.apps.CmsWorkplaceAppManager.java

/**
 * Loads the app categories.<p>//from   ww  w  .j  a  va2s  . co m
 *
 * @return the app categories
 */
private Map<String, I_CmsAppCategory> loadCategories() {

    Map<String, I_CmsAppCategory> appCategories = new HashMap<String, I_CmsAppCategory>();
    CmsAppCategory main = new CmsAppCategory(MAIN_CATEGORY_ID, null, 0, 0);
    appCategories.put(main.getId(), main);
    CmsAppCategory legacy = new CmsAppCategory(LEGACY_CATEGORY_ID, null, 1, 0);
    appCategories.put(legacy.getId(), legacy);
    Iterator<I_CmsAppCategory> categoryIt = ServiceLoader.load(I_CmsAppCategory.class).iterator();
    while (categoryIt.hasNext()) {
        try {
            I_CmsAppCategory cat = categoryIt.next();
            if (!appCategories.containsKey(cat.getId())
                    || (appCategories.get(cat.getId()).getPriority() < cat.getPriority())) {
                appCategories.put(cat.getId(), cat);
            }
        } catch (Throwable t) {
            LOG.error("Error loading workplace app category from classpath.", t);
        }
    }
    return appCategories;
}

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

/**
 * Gets an subscriber plugin//from w  ww  .j  a  va2 s . co m
 *
 * @param id plugin identifier
 * @return an Subscriber plugin, or null if not found
 */
public static Subscriber getSubscriber(String id) {
    Class<Subscriber> clazz = (Class<Subscriber>) cache.getIfPresent("subscriber" + 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<Subscriber> plugins = ServiceLoader.load(Subscriber.class);
    for (Subscriber plugin : plugins) {
        if (id.equals(plugin.getId())) {
            return plugin;
        }
    }

    File groovyFile = getPathFile("plugins/subscriber/" + id + ".groovy");
    if (groovyFile.exists()) {
        GroovyClassLoader gcl = new GroovyClassLoader();
        try {
            clazz = gcl.parseClass(groovyFile);
            cache.put("subscriber" + 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:com.googlecode.fascinator.api.PluginManager.java

/**
 * Get a list of Subscriber plugins//from  w  ww .j  a va2s  .c  o  m
 *
 * @return map of Subscriber plugin, or empty map if not found
 */
public static Map<String, Subscriber> getSubscriberPlugins() {
    Map<String, Subscriber> access_plugins = new HashMap<String, Subscriber>();
    ServiceLoader<Subscriber> plugins = ServiceLoader.load(Subscriber.class);
    for (Subscriber plugin : plugins) {
        access_plugins.put(plugin.getId(), plugin);
    }
    return access_plugins;
}

From source file:org.acmsl.queryj.api.AbstractTemplate.java

/**
 * Builds the correct chain./*w  w w.  ja  v a  2  s. com*/
 * @param context the context.
 * @return the specific {@link FillTemplateChain}.
 * @throws QueryJBuildException if the template chain cannot be built.
 */
@SuppressWarnings("unchecked")
@NotNull
public List<FillTemplateChain<? extends FillHandler<?>>> buildFillTemplateChains(@NotNull final C context)
        throws QueryJBuildException {
    @NotNull
    final List<FillTemplateChain<? extends FillHandler<?>>> result = new ArrayList<>();

    @Nullable
    final Class<FillTemplateChainFactory<C>> factoryClass = retrieveFillTemplateChainFactoryClass(context,
            getPlaceholderPackage());

    if (factoryClass != null) {
        @Nullable
        final ServiceLoader<FillTemplateChainFactory<C>> loader = ServiceLoader.load(factoryClass);

        if (loader != null) {
            for (@NotNull
            final FillTemplateChainFactory<C> factory : loader) {
                result.add((FillTemplateChain<? extends FillHandler<?>>) factory.createFillChain(context));
            }
        } else {
            throw new CannotFindPlaceholderImplementationException(factoryClass);
        }
    } else {
        throw new CannotFindPlaceholderImplementationException(context.getClass().getName());
    }

    return result;
}

From source file:edu.kit.dama.mdm.content.mets.MetsMetadataExtractor.java

private void buildExtractorMap() {
    LOGGER.debug("Looking for 'MetsTypeExtractor' plugins!");
    String prefix = "Plugin:";
    extractorMap = new HashMap();
    for (IMetsTypeExtractor plugin : ServiceLoader.load(IMetsTypeExtractor.class)) {
        String name = plugin.getName();
        String namespace = plugin.getNamespace();
        String pluginKey = prefix + name;
        LOGGER.info("Found plugin for schema identifier '{}'!", name);
        // Check if schema is 'registered' as Metadataschema.

        if (checkForSchema(name) || namespace.length() > 0) { // dummy test 
            if (extractorMap.containsKey(pluginKey)) {
                String className = extractorMap.get(pluginKey).getClass().toString();
                LOGGER.error("Two plugins with the same schema identifier '{}' exists: {} / {}", name,
                        className, plugin.getClass().toString());
            }/*from w  ww.  j  av a  2  s.  co m*/
            extractorMap.put(pluginKey, plugin);
        }
    }
}

From source file:org.kie.server.services.jbpm.JbpmKieServerExtension.java

@Override
public List<Object> getAppComponents(SupportedTransports type) {
    ServiceLoader<KieServerApplicationComponentsService> appComponentsServices = ServiceLoader
            .load(KieServerApplicationComponentsService.class);
    List<Object> appComponentsList = new ArrayList<Object>();
    Object[] services = { deploymentService, definitionService, processService, userTaskService,
            runtimeDataService, executorService, formManagerService, queryService,
            processInstanceMigrationService, processInstanceAdminService, userTaskAdminService, context };
    for (KieServerApplicationComponentsService appComponentsService : appComponentsServices) {
        appComponentsList.addAll(appComponentsService.getAppComponents(EXTENSION_NAME, type, services));
    }/*from  ww  w.  j  a v a 2 s  .  co m*/
    return appComponentsList;
}

From source file:jmri.InstanceManager.java

/**
 * Default constructor for the InstanceManager.
 *///from www . j av  a  2 s  .  c  om
public InstanceManager() {
    ServiceLoader.load(InstanceInitializer.class).forEach((provider) -> {
        provider.getInitalizes().forEach((cls) -> {
            this.initializers.put(cls, provider);
            log.debug("Using {} to provide default instance of {}", provider.getClass().getName(),
                    cls.getName());
        });
    });
}