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:Main.java

public static void main(String[] args) {
    ServiceLoader<JavaCompiler> compilers = ServiceLoader.load(JavaCompiler.class);
    System.out.println(compilers.toString());

    for (JavaCompiler compiler : compilers)
        System.out.println(compiler);
}

From source file:EnumAlternateJavaCompilers.java

public static void main(String[] args) {
    ServiceLoader<JavaCompiler> compilers;
    compilers = ServiceLoader.load(JavaCompiler.class);
    System.out.println(compilers.toString());

    for (JavaCompiler compiler : compilers)
        System.out.println(compiler);
}

From source file:org.anarres.dblx.core.Main.java

public static void main(String[] args) throws Exception {
    Stopwatch stopwatch = Stopwatch.createStarted();
    Arguments arguments = new Arguments(args);
    GenericApplicationContext context = new GenericApplicationContext();
    AnnotatedBeanDefinitionReader reader = new AnnotatedBeanDefinitionReader(context);
    reader.register(AppConfiguration.class);
    for (AppConfiguration.Provider configurationProvider : ServiceLoader
            .load(AppConfiguration.Provider.class)) {
        for (Class<?> configurationClass : configurationProvider.getConfigurationClasses()) {
            LOG.debug("Registering additional ServerConfiguration class " + configurationClass.getName());
            reader.register(configurationClass);
        }/*from  w w w .  j  a  v  a  2 s. c  om*/
    }
    SpringUtils.addConfigurations(context, arguments);
    context.refresh();
    context.registerShutdownHook();
    context.start();

    LOG.info("Ready; startup took " + stopwatch);
}

From source file:org.lenskit.cli.Main.java

public static void main(String[] args) {
    ArgumentParser parser = ArgumentParsers.newArgumentParser("lenskit")
            .description("Work with LensKit recommenders and data.");
    Logging.addLoggingGroup(parser);/*from w ww.  j a v  a2 s  .  c o m*/

    Subparsers subparsers = parser.addSubparsers().metavar("COMMAND").title("commands");
    ServiceLoader<Command> loader = ServiceLoader.load(Command.class);
    for (Command cmd : loader) {
        Subparser cp = subparsers.addParser(cmd.getName()).help(cmd.getHelp()).setDefault("command", cmd);
        cmd.configureArguments(cp);
    }

    try {
        Namespace options = parser.parseArgs(args);
        Logging.configureLogging(options);
        Runtime rt = Runtime.getRuntime();
        logger.info("Starting LensKit {} on Java {} from {}", LenskitInfo.lenskitVersion(),
                SystemUtils.JAVA_VERSION, SystemUtils.JAVA_VENDOR);
        logger.debug("Built from Git revision {}", LenskitInfo.getHeadRevision());
        logger.debug("Using VM '{}' version {} from {}", SystemUtils.JAVA_VM_NAME, SystemUtils.JAVA_VM_VERSION,
                SystemUtils.JAVA_VM_VENDOR);
        logger.info("Have {} processors and heap limit of {} MiB", rt.availableProcessors(),
                rt.maxMemory() >> 20);
        Command cmd = options.get("command");
        cmd.execute(options);
        logger.info("If you use LensKit in published research, please see http://lenskit.org/research/");
    } catch (ArgumentParserException e) {
        parser.handleError(e);
        System.exit(1);
    } catch (Exception e) {
        logger.error("error running command: " + e, e);
        System.exit(2);
    }
}

From source file:org.apache.batchee.cli.BatchEECLI.java

public static void main(final String[] args) {
    final Iterator<CliConfiguration> configuration = ServiceLoader.load(CliConfiguration.class).iterator();
    final CliConfiguration cliConfiguration = configuration.hasNext() ? configuration.next()
            : new DefaultCliConfiguration();

    final Map<String, Class<? extends Runnable>> commands = new TreeMap<String, Class<? extends Runnable>>();
    if (cliConfiguration.addDefaultCommands()) {
        for (final Class<? extends Runnable> type : Arrays.asList(Names.class, Start.class, Restart.class,
                Status.class, Running.class, Stop.class, Abandon.class, Instances.class, Executions.class,
                StepExecutions.class, Eviction.class)) {
            addCommand(commands, type);// w  w w  . j a v  a  2s.  co m
        }
    }
    final Iterator<Class<? extends UserCommand>> userCommands = cliConfiguration.userCommands();
    if (userCommands != null) {
        while (userCommands.hasNext()) {
            addCommand(commands, userCommands.next());
        }
    }

    if (args == null || args.length == 0) {
        System.err.print(help(commands));
        return;
    }

    final Class<? extends Runnable> cmd = commands.get(args[0]);
    if (cmd == null) {
        if (args[0].equals("help")) {
            if (args.length > 1) {
                final Class<? extends Runnable> helpCmd = commands.get(args[1]);
                if (helpCmd != null) {
                    printHelp(helpCmd.getAnnotation(Command.class),
                            buildOptions(helpCmd, new HashMap<String, Field>()));
                    return;
                }
            } // else let use the default help
        }
        System.err.print(help(commands));
        return;
    }

    // build the command now
    final Command command = cmd.getAnnotation(Command.class);
    if (command == null) {
        System.err.print(help(commands));
        return;
    }

    final Map<String, Field> fields = new HashMap<String, Field>();
    final Options options = buildOptions(cmd, fields);

    final Collection<String> newArgs = new ArrayList<String>(asList(args));
    newArgs.remove(newArgs.iterator().next());

    final CommandLineParser parser = new DefaultParser();
    try {
        final CommandLine line = parser.parse(options, newArgs.toArray(new String[newArgs.size()]));
        cliConfiguration.decorate(instantiate(cmd, cliConfiguration, fields, !newArgs.isEmpty(), line)).run();
    } catch (final ParseException e) {
        printHelp(command, options);
    } catch (final RuntimeException e) {
        Class<?> current = e.getClass();
        while (current != null) {
            final Exit annotation = current.getAnnotation(Exit.class);
            if (annotation != null) {
                System.exit(annotation.value());
            }
            current = current.getSuperclass();
        }
        throw e;
    } catch (final InstantiationException e) {
        throw new IllegalStateException(e);
    } catch (final IllegalAccessException e) {
        throw new IllegalStateException(e);
    }
}

From source file:com.artistech.tuio.mouse.ZeroMqMouse.java

/**
 * Main entry point for ZeroMQ integration.
 *
 * @param args//from  w w w.jav  a2 s . c  o  m
 * @throws AWTException
 * @throws java.io.IOException
 */
public static void main(String[] args) throws AWTException, java.io.IOException {
    //read off the TUIO port from the command line
    String zeromq_port;

    Options options = new Options();
    options.addOption("z", "zeromq-port", true, "ZeroMQ Server:Port to subscribe to. (-z localhost:5565)");
    options.addOption("h", "help", false, "Show this message.");
    HelpFormatter formatter = new HelpFormatter();

    try {
        CommandLineParser parser = new org.apache.commons.cli.BasicParser();
        CommandLine cmd = parser.parse(options, args);

        if (cmd.hasOption("help")) {
            formatter.printHelp("tuio-mouse-driver", options);
            return;
        } else {
            if (cmd.hasOption("z") || cmd.hasOption("zeromq-port")) {
                zeromq_port = cmd.getOptionValue("z");
            } else {
                System.err.println("The zeromq-port value must be specified.");
                formatter.printHelp("tuio-mouse-driver", options);
                return;
            }
        }
    } catch (ParseException ex) {
        System.err.println("Error Processing Command Options:");
        formatter.printHelp("tuio-mouse-driver", options);
        return;
    }

    //load conversion services
    ServiceLoader<ProtoConverter> services = ServiceLoader.load(ProtoConverter.class);

    //create zeromq context
    ZMQ.Context context = ZMQ.context(1);

    // Connect our subscriber socket
    ZMQ.Socket subscriber = context.socket(ZMQ.SUB);
    subscriber.setIdentity(ZeroMqMouse.class.getName().getBytes());

    //this could change I guess so we can get different data subscrptions.
    subscriber.subscribe("TuioCursor".getBytes());
    //        subscriber.subscribe("TuioTime".getBytes());
    subscriber.connect("tcp://" + zeromq_port);

    System.out.println("Subscribed to " + zeromq_port + " for ZeroMQ messages.");

    // Get updates, expect random Ctrl-C death
    String msg = "";
    MouseDriver md = new MouseDriver();
    while (!msg.equalsIgnoreCase("END")) {
        boolean success = false;
        byte[] recv = subscriber.recv();

        com.google.protobuf.GeneratedMessage message = null;
        TuioPoint pt = null;
        String type = recv.length > 0 ? new String(recv) : "";
        recv = subscriber.recv();
        switch (type) {
        case "TuioCursor.PROTOBUF":
            try {
                //it is a cursor?
                message = com.artistech.protobuf.TuioProtos.Cursor.parseFrom(recv);
                success = true;
            } catch (Exception ex) {
            }
            break;
        case "TuioTime.PROTOBUF":
            //                    try {
            //                        //it is a cursor?
            //                        message = com.artistech.protobuf.TuioProtos.Time.parseFrom(recv);
            //                        success = true;
            //                    } catch (Exception ex) {
            //                    }
            break;
        case "TuioObject.PROTOBUF":
            try {
                //it is a cursor?
                message = com.artistech.protobuf.TuioProtos.Object.parseFrom(recv);
                success = true;
            } catch (Exception ex) {
            }
            break;
        case "TuioBlob.PROTOBUF":
            try {
                //it is a cursor?
                message = com.artistech.protobuf.TuioProtos.Blob.parseFrom(recv);
                success = true;
            } catch (Exception ex) {
            }
            break;
        case "TuioCursor.JSON":
            try {
                //it is a cursor?
                pt = mapper.readValue(recv, TUIO.TuioCursor.class);
                success = true;
            } catch (Exception ex) {
            }
            break;
        case "TuioTime.JSON":
            //                    try {
            //                        //it is a cursor?
            //                        pt = mapper.readValue(recv, TUIO.TuioTime.class);
            //                        success = true;
            //                    } catch (Exception ex) {
            //                    }
            break;
        case "TuioObject.JSON":
            try {
                //it is a cursor?
                pt = mapper.readValue(recv, TUIO.TuioObject.class);
                success = true;
            } catch (Exception ex) {
            }
            break;
        case "TuioBlob.JSON":
            try {
                //it is a cursor?
                pt = mapper.readValue(recv, TUIO.TuioBlob.class);
                success = true;
            } catch (Exception ex) {
            }
            break;
        case "TuioTime.OBJECT":
            break;
        case "TuioCursor.OBJECT":
        case "TuioObject.OBJECT":
        case "TuioBlob.OBJECT":
            try {
                //Try reading the data as a serialized Java object:
                try (ByteArrayInputStream bis = new ByteArrayInputStream(recv)) {
                    //Try reading the data as a serialized Java object:
                    ObjectInput in = new ObjectInputStream(bis);
                    Object o = in.readObject();
                    //if it is of type Point (Cursor, Object, Blob), process:
                    if (TuioPoint.class.isAssignableFrom(o.getClass())) {
                        pt = (TuioPoint) o;
                        process(pt, md);
                    }

                    success = true;
                }
            } catch (java.io.IOException | ClassNotFoundException ex) {
            } finally {
            }
            break;
        default:
            success = false;
            break;
        }

        if (message != null && success) {
            //ok, so we have a message that is not null, so it was protobuf:
            Object o = null;

            //look for a converter that will suppor this objec type and convert:
            for (ProtoConverter converter : services) {
                if (converter.supportsConversion(message)) {
                    o = converter.convertFromProtobuf(message);
                    break;
                }
            }

            //if the type is of type Point (Cursor, Blob, Object), process:
            if (o != null && TuioPoint.class.isAssignableFrom(o.getClass())) {
                pt = (TuioPoint) o;
            }
        }

        if (pt != null) {
            process(pt, md);
        }
    }
}

From source file:org.datacleaner.spark.Main.java

public static void main(final String[] args) throws Exception {
    if (args.length < 2) {
        throw new IllegalArgumentException("The number of arguments is incorrect. Usage:\n"
                + " <configuration file (conf.xml) path> <job file (.analysis.xml) path> [properties file path]\n"
                + "Got: " + Arrays.toString(args));
    }//w w w. jav  a 2s  .c  o m

    final SparkConf conf = new SparkConf().setAppName("DataCleaner-spark");
    final JavaSparkContext sparkContext = new JavaSparkContext(conf);

    final URI confXmlPath = URI.create(args[0]);
    final URI analysisJobXmlPath = URI.create(args[1]);

    final URI propertiesPath;
    if (args.length > 2) {
        propertiesPath = URI.create(args[2]);
    } else {
        propertiesPath = null;
    }

    final SparkJobContext sparkJobContext = new SparkJobContext(confXmlPath, analysisJobXmlPath, propertiesPath,
            sparkContext);

    final ServiceLoader<SparkJobLifeCycleListener> listenerLoaders = ServiceLoader
            .load(SparkJobLifeCycleListener.class);

    for (final SparkJobLifeCycleListener listener : listenerLoaders) {
        sparkJobContext.addSparkJobLifeCycleListener(listener);
    }

    final SparkAnalysisRunner sparkAnalysisRunner = new SparkAnalysisRunner(sparkContext, sparkJobContext);
    try {
        final AnalysisResultFuture result = sparkAnalysisRunner.run();

        result.await();

        if (sparkJobContext.isResultEnabled()) {
            final Resource resultResource = ResultFilePathUtils.getResultResource(sparkContext,
                    sparkJobContext);
            logger.info("DataCleaner result will be written to: {}", resultResource);
            saveResult(result, resultResource);
        } else {
            logger.info("DataCleaner result will not be written - disabled");
        }
    } finally {
        sparkContext.stop();
    }
}

From source file:fi.iki.elonen.SimpleWebServer.java

/**
 * Starts as a standalone file server and waits for Enter.
 *//*from ww w  .  j a  va 2 s.c o  m*/
public static void main(String[] args) {
    // Defaults
    int port = 8080;

    String host = null; // bind to all interfaces by default
    List<File> rootDirs = new ArrayList<File>();
    boolean quiet = false;
    String cors = null;
    Map<String, String> options = new HashMap<String, String>();

    // Parse command-line, with short and long versions of the options.
    for (int i = 0; i < args.length; ++i) {
        if ("-h".equalsIgnoreCase(args[i]) || "--host".equalsIgnoreCase(args[i])) {
            host = args[i + 1];
        } else if ("-p".equalsIgnoreCase(args[i]) || "--port".equalsIgnoreCase(args[i])) {
            if (args[i + 1].equals("public")) {
                port = PUBLIC;
            } else if (args[i + 1].equals("private")) {
                port = PRIVATE;
            } else {
                port = Integer.parseInt(args[i + 1]);
            }
        } else if ("-q".equalsIgnoreCase(args[i]) || "--quiet".equalsIgnoreCase(args[i])) {
            quiet = true;
        } else if ("-d".equalsIgnoreCase(args[i]) || "--dir".equalsIgnoreCase(args[i])) {
            rootDirs.add(new File(args[i + 1]).getAbsoluteFile());
        } else if (args[i].startsWith("--cors")) {
            cors = "*";
            int equalIdx = args[i].indexOf('=');
            if (equalIdx > 0) {
                cors = args[i].substring(equalIdx + 1);
            }
        } else if ("--licence".equalsIgnoreCase(args[i])) {
            System.out.println(SimpleWebServer.LICENCE + "\n");
        } else if (args[i].startsWith("-X:")) {
            int dot = args[i].indexOf('=');
            if (dot > 0) {
                String name = args[i].substring(0, dot);
                String value = args[i].substring(dot + 1, args[i].length());
                options.put(name, value);
            }
        }
    }

    if (rootDirs.isEmpty()) {
        rootDirs.add(new File(".").getAbsoluteFile());
    }
    options.put("host", host);
    options.put("port", "" + port);
    options.put("quiet", String.valueOf(quiet));
    StringBuilder sb = new StringBuilder();
    for (File dir : rootDirs) {
        if (sb.length() > 0) {
            sb.append(":");
        }
        try {
            sb.append(dir.getCanonicalPath());
        } catch (IOException ignored) {
        }
    }
    options.put("home", sb.toString());
    ServiceLoader<WebServerPluginInfo> serviceLoader = ServiceLoader.load(WebServerPluginInfo.class);
    for (WebServerPluginInfo info : serviceLoader) {
        String[] mimeTypes = info.getMimeTypes();
        for (String mime : mimeTypes) {
            String[] indexFiles = info.getIndexFilesForMimeType(mime);
            if (!quiet) {
                System.out.print("# Found plugin for Mime type: \"" + mime + "\"");
                if (indexFiles != null) {
                    System.out.print(" (serving index files: ");
                    for (String indexFile : indexFiles) {
                        System.out.print(indexFile + " ");
                    }
                }
                System.out.println(").");
            }
            registerPluginForMimeType(indexFiles, mime, info.getWebServerPlugin(mime), options);
        }
    }
    ServerRunner.executeInstance(new SimpleWebServer(host, port, rootDirs, quiet, cors));
}

From source file:io.fluo.core.metrics.ReporterUtil.java

public static AutoCloseable setupReporters(final Environment env, final String domain) {
    ServiceLoader<ReporterStarter> serviceLoader = ServiceLoader.load(ReporterStarter.class);

    final List<AutoCloseable> allReporters = new ArrayList<>();

    for (ReporterStarter rs : serviceLoader) {
        List<AutoCloseable> reporters = rs.start(new Params() {

            @Override//from   w  w  w  .j a v a2 s.c  o  m
            public Configuration getConfiguration() {
                return env.getConfiguration();
            }

            @Override
            public MetricRegistry getMetricRegistry() {
                return env.getSharedResources().getMetricRegistry();
            }

            @Override
            public String getDomain() {
                return domain;
            }
        });

        allReporters.addAll(reporters);
    }

    if (allReporters.size() == 0) {
        JmxReporter jmxReporter = JmxReporter.forRegistry(env.getSharedResources().getMetricRegistry())
                .inDomain(domain).build();
        jmxReporter.start();
        allReporters.add(jmxReporter);
    }

    return new AutoCloseable() {

        @Override
        public void close() {
            for (AutoCloseable closeable : allReporters) {
                try {
                    closeable.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    };
}

From source file:eu.itesla_project.commons.tools.Main.java

private static void printUsage() {
    StringBuilder usage = new StringBuilder();
    usage.append("usage: " + TOOL_NAME + " COMMAND [ARGS]\n\nAvailable commands are:\n\n");

    List<Tool> allTools = Lists.newArrayList(ServiceLoader.load(Tool.class)).stream()
            .filter(t -> !t.getCommand().isHidden()).collect(Collectors.toList());

    // group commands by theme
    Multimap<String, Tool> toolsByTheme = Multimaps.index(allTools, new Function<Tool, String>() {
        @Override//from   w  w  w  .j av  a2 s .co  m
        public String apply(Tool tool) {
            return tool.getCommand().getTheme();
        }
    });

    for (Map.Entry<String, Collection<Tool>> entry : toolsByTheme.asMap().entrySet()) {
        String theme = entry.getKey();
        List<Tool> tools = new ArrayList<>(entry.getValue());
        Collections.sort(tools, new Comparator<Tool>() {
            @Override
            public int compare(Tool t1, Tool t2) {
                return t1.getCommand().getName().compareTo(t2.getCommand().getName());
            }
        });
        usage.append(theme != null ? theme : "Others").append(":\n");
        for (Tool tool : tools) {
            usage.append(String.format("   %-40s %s", tool.getCommand().getName(),
                    tool.getCommand().getDescription())).append("\n");
        }
        usage.append("\n");
    }

    System.err.print(usage);
    System.exit(1);
}