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.caricah.iotracah.bootstrap.runner.ResourceService.java

public ServiceLoader<ConfigHandler> getConfigurationSetLoader() {

    return ServiceLoader.load(ConfigHandler.class);
}

From source file:maltcms.ui.fileHandles.properties.tools.PropertyLoader.java

/**
 * @param optionValues//from   w  w w .j  av a2s  .c  om
 */
public static String[] getListServiceProviders(String optionValue) {
    List<String> ret = new ArrayList<>();
    Class<?> c;
    try {
        c = Class.forName(optionValue);
        Logger.getLogger(PropertyLoader.class.getName()).log(Level.INFO, "Loading service: {0}", c.getName());
        ServiceLoader<?> sl = ServiceLoader.load(c);
        for (Object o : sl) {
            if (o != null) {
                ret.add(o.getClass().getName());
            }
        }
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (Exception | Error e) {
        e.printStackTrace();
    }

    if (ret.size() == 0) {
        return new String[] { "Can not find any Services for " + optionValue };
    } else {
        return ret.toArray(new String[] {});
    }
}

From source file:org.cache2k.core.util.Log.java

/**
 * Finds a logger we can use. First we start with looking for a registered
 * service provider. Then apache commons logging. As a fallback we use JDK logging.
 *//*w  w  w  . j  ava2 s . c  o m*/
private static void initializeLogFactory() {
    ServiceLoader<LogFactory> loader = ServiceLoader.load(LogFactory.class);
    for (LogFactory lf : loader) {
        logFactory = lf;
        log("New instance, using: " + logFactory.getClass().getName());
        return;
    }
    try {
        final org.slf4j.ILoggerFactory lf = org.slf4j.LoggerFactory.getILoggerFactory();
        if (!(lf instanceof NOPLoggerFactory)) {
            logFactory = new LogFactory() {
                @Override
                public Log getLog(String s) {
                    return new Slf4jLogger(lf.getLogger(s));
                }
            };
            log("New instance, using SLF4J logging");
            return;
        }
    } catch (NoClassDefFoundError ignore) {
    }
    try {
        final org.apache.commons.logging.LogFactory cl = org.apache.commons.logging.LogFactory.getFactory();
        logFactory = new LogFactory() {
            @Override
            public Log getLog(String s) {
                return new CommonsLogger(cl.getInstance(s));
            }
        };
        log("New instance, using commons logging");
        return;
    } catch (NoClassDefFoundError ignore) {
    }
    logFactory = new LogFactory() {
        @Override
        public Log getLog(String s) {
            return new JdkLogger(Logger.getLogger(s));
        }
    };
    log("New instance, using JDK logging");
}

From source file:org.kie.workbench.common.migration.cli.MigrationApp.java

public MigrationApp(String args[]) {

    actualConfig = parseToolConfigOrExit(args);

    ServiceLoader<MigrationTool> migrationLoader = ServiceLoader.load(MigrationTool.class);

    migrationLoader.forEach(migrationTool -> migrationTools.add(migrationTool));

    Collections.sort(migrationTools, Comparator.comparing(MigrationTool::getPriority));
}

From source file:org.lable.oss.dynamicconfig.di.DynamicConfigModule.java

@Provides
@Singleton/*from   ww  w  .j a v a 2  s  .co  m*/
public HierarchicalConfigurationDeserializer provideDeserializer() throws ConfigurationException {
    ServiceLoader<HierarchicalConfigurationDeserializer> serviceLoader = ServiceLoader
            .load(HierarchicalConfigurationDeserializer.class);

    Iterator<HierarchicalConfigurationDeserializer> iterator = serviceLoader.iterator();
    if (!iterator.hasNext()) {
        throw new ConfigurationException("No HierarchicalConfigurationDeserializer found on the classpath. "
                + "You may need to load a module containing a suitable deserializer.");
    }

    HierarchicalConfigurationDeserializer hierarchicalConfigurationDeserializer = iterator.next();
    logger.info("Found HierarchicalConfigurationDeserializer {}; providing it to the configuration system.",
            hierarchicalConfigurationDeserializer.getClass().getName());
    return hierarchicalConfigurationDeserializer;
}

From source file:uk.trainwatch.app.util.Main.java

private static int run(String... args) throws Exception {

    // Load all of the utility implementations
    ServiceLoader<Utility> loader = ServiceLoader.load(Utility.class);
    Map<String, Utility> tools = StreamSupport.stream(loader.spliterator(), false)
            .collect(Collectors.toMap(Utility::getName, Function.identity()));

    Supplier<String> toolNames = () -> tools.keySet().stream().sorted()
            .collect(Collectors.joining(", ", "Available tools: ", ""));

    Consumer<Utility> showHelp = u -> new HelpFormatter().printHelp(u.getName(), u.getOptions());

    if (args.length == 0) {
        LOG.log(Level.INFO, toolNames);
        return 1;
    }//w  w  w.  j a  v  a 2s  . c  o m

    String toolName = args[0];

    if ("-?".equals(toolName) || "--help".equals(toolName)) {
        HelpFormatter hf = new HelpFormatter();
        tools.keySet().stream().sorted().map(tools::get).filter(Objects::nonNull).forEach(showHelp);
    } else {
        Utility util = getUtility(tools, toolNames, toolName);
        if (util != null) {

            String toolArgs[] = Arrays.copyOfRange(args, 1, args.length);

            if (toolArgs.length == 0 || "-?".equals(toolArgs[0]) || "--help".equals(toolArgs[0])) {
                new HelpFormatter().printHelp(util.getName(), util.getOptions());
            } else {
                try {
                    CommandLineParser parser = new BasicParser();
                    CommandLine cmd = parser.parse(util.getOptions(), toolArgs);
                    if (util.parseArgs(cmd)) {
                        // Simple banner for identifying whats being run
                        LoggingUtils.logBanner("Utility: " + util.getName());
                        try {
                            CDIUtils.inject(util);
                            util.call();
                            return 0;
                        } finally {
                            LoggingUtils.logBanner("End run of " + util.getName());
                        }
                    } else {
                        LOG.log(Level.WARNING, () -> "Failed to parse args " + cmd);
                        showHelp.accept(util);
                    }
                } catch (UnrecognizedOptionException ex) {
                    LOG.log(Level.WARNING, ex, ex::getMessage);
                    showHelp.accept(util);
                } catch (UncheckedSQLException ex) {
                    LOG.log(Level.SEVERE, null, ex.getCause());
                } catch (Exception ex) {
                    LOG.log(Level.SEVERE, null, ex);
                }
            }
        }
    }
    return 1;
}

From source file:com.caricah.iotracah.bootstrap.runner.ResourceService.java

public ServiceLoader<LogHandler> getLogSetLoader() {

    return ServiceLoader.load(LogHandler.class);
}

From source file:com.alibaba.dragoon.common.protocol.transport.DragoonMessageCodec.java

public DragoonMessageCodec() {
    decoders.add(new DefaultDragoonMessageDecoder());

    ServiceLoader<DragoonMessageDecoder> serviceLoader = ServiceLoader.load(DragoonMessageDecoder.class);
    Iterator<DragoonMessageDecoder> it = serviceLoader.iterator();
    while (it.hasNext()) {
        DragoonMessageDecoder decoder = it.next();
        decoders.add(decoder);/*  www .  j  av a  2s .  c  o  m*/
    }
}

From source file:org.apache.accumulo.shell.commands.ExtensionCommand.java

@Override
public int execute(String fullCommand, CommandLine cl, Shell shellState) throws Exception {
    if (cl.hasOption(enable.getOpt())) {
        extensions = ServiceLoader.load(ShellExtension.class);
        for (ShellExtension se : extensions) {

            loadedExtensions.add(se.getExtensionName());
            String header = "-- " + se.getExtensionName() + " Extension Commands ---------";
            loadedHeaders.add(header);//from   w w  w  .jav a2  s.  c o m
            shellState.commandGrouping.put(header, se.getCommands());

            for (Command cmd : se.getCommands()) {
                String name = se.getExtensionName() + "::" + cmd.getName();
                loadedCommands.add(name);
                shellState.commandFactory.put(name, cmd);
            }
        }
    } else if (cl.hasOption(disable.getOpt())) {
        // Remove the headers
        for (String header : loadedHeaders) {
            shellState.commandGrouping.remove(header);
        }
        // remove the commands
        for (String name : loadedCommands) {
            shellState.commandFactory.remove(name);
        }
        // Reset state
        loadedExtensions.clear();
        extensions.reload();
    } else if (cl.hasOption(list.getOpt())) {
        shellState.printLines(loadedExtensions.iterator(), true);
    } else {
        printHelp(shellState);
    }
    return 0;
}

From source file:org.apache.accumulo.core.util.shell.commands.ExtensionCommand.java

public int execute(String fullCommand, CommandLine cl, Shell shellState) throws Exception {
    if (cl.hasOption(enable.getOpt())) {
        extensions = ServiceLoader.load(ShellExtension.class);
        for (ShellExtension se : extensions) {

            loadedExtensions.add(se.getExtensionName());
            String header = "-- " + se.getExtensionName() + " Extension Commands ---------";
            loadedHeaders.add(header);//from w  w w  . j  a v a2 s . co m
            shellState.commandGrouping.put(header, se.getCommands());

            for (Command cmd : se.getCommands()) {
                String name = se.getExtensionName() + "::" + cmd.getName();
                loadedCommands.add(name);
                shellState.commandFactory.put(name, cmd);
            }
        }
    } else if (cl.hasOption(disable.getOpt())) {
        //Remove the headers
        for (String header : loadedHeaders) {
            shellState.commandGrouping.remove(header);
        }
        //remove the commands
        for (String name : loadedCommands) {
            shellState.commandFactory.remove(name);
        }
        //Reset state
        loadedExtensions.clear();
        extensions.reload();
    } else if (cl.hasOption(list.getOpt())) {
        shellState.printLines(loadedExtensions.iterator(), true);
    } else {
        printHelp(shellState);
    }
    return 0;
}