Example usage for org.apache.commons.cli HelpFormatter HelpFormatter

List of usage examples for org.apache.commons.cli HelpFormatter HelpFormatter

Introduction

In this page you can find the example usage for org.apache.commons.cli HelpFormatter HelpFormatter.

Prototype

HelpFormatter

Source Link

Usage

From source file:edu.usc.pgroup.floe.client.commands.Scale.java

/**
 * Entry point for Scale command.//  www. ja v a 2s. c o  m
 * @param args command line arguments sent by the floe.py script.
 */
public static void main(final String[] args) {

    Options options = new Options();

    Option dirOption = OptionBuilder.withArgName("direction").hasArg().isRequired()
            .withDescription("Scale Direction.").create("dir");

    Option appOption = OptionBuilder.withArgName("name").hasArg().isRequired()
            .withDescription("Application Name").create("app");

    Option pelletNameOption = OptionBuilder.withArgName("name").hasArg().isRequired()
            .withDescription("Pellet Name").create("pellet");

    Option cntOption = OptionBuilder.withArgName("num").hasArg().withType(new String())
            .withDescription("Number of instances to scale up/down").create("cnt");

    options.addOption(dirOption);
    options.addOption(appOption);
    options.addOption(pelletNameOption);
    options.addOption(cntOption);

    CommandLineParser parser = new BasicParser();
    CommandLine line;

    try {
        line = parser.parse(options, args);

    } catch (ParseException e) {
        LOGGER.error("Invalid command: " + e.getMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("scale options", options);
        return;
    }

    String dir = line.getOptionValue("dir");
    String app = line.getOptionValue("app");
    String pellet = line.getOptionValue("pellet");
    String cnt = line.getOptionValue("cnt");

    LOGGER.info("direction: {}", dir);
    LOGGER.info("Application: {}", app);
    LOGGER.info("Pellet: {}", pellet);
    LOGGER.info("count: {}", cnt);

    ScaleDirection direction = Enum.valueOf(ScaleDirection.class, dir);
    int count = Integer.parseInt(cnt);
    try {
        FloeClient.getInstance().getClient().scale(direction, app, pellet, count);
    } catch (TException e) {
        LOGGER.error("Error while connecting to the coordinator: {}", e);
    }
}

From source file:com.edduarte.argus.Main.java

public static void main(String[] args) {

    installUncaughtExceptionHandler();//from ww w  .jav a  2s  . c o  m

    CommandLineParser parser = new GnuParser();
    Options options = new Options();

    options.addOption("t", "threads", true, "Number of threads to be used "
            + "for computation and indexing processes. Defaults to the number " + "of available cores.");

    options.addOption("p", "port", true, "Core server port. Defaults to 9000.");

    options.addOption("dbh", "db-host", true, "Database host. Defaults to localhost.");

    options.addOption("dbp", "db-port", true, "Database port. Defaults to 27017.");

    options.addOption("case", "preserve-case", false, "Keyword matching with case sensitivity.");

    options.addOption("stop", "stopwords", false, "Keyword matching with stopword filtering.");

    options.addOption("stem", "stemming", false, "Keyword matching with stemming (lexical variants).");

    options.addOption("h", "help", false, "Shows this help prompt.");

    CommandLine commandLine;
    try {
        // Parse the program arguments
        commandLine = parser.parse(options, args);
    } catch (ParseException ex) {
        logger.error("There was a problem processing the input arguments. "
                + "Write -h or --help to show the list of available commands.");
        logger.error(ex.getMessage(), ex);
        return;
    }

    if (commandLine.hasOption('h')) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("java -jar argus-core.jar", options);
        return;
    }

    int maxThreads = Runtime.getRuntime().availableProcessors() - 1;
    maxThreads = maxThreads > 0 ? maxThreads : 1;
    if (commandLine.hasOption('t')) {
        String threadsText = commandLine.getOptionValue('t');
        maxThreads = Integer.parseInt(threadsText);
        if (maxThreads <= 0 || maxThreads > 32) {
            logger.error("Invalid number of threads. Must be a number between 1 and 32.");
            return;
        }
    }

    int port = 9000;
    if (commandLine.hasOption('p')) {
        String portString = commandLine.getOptionValue('p');
        port = Integer.parseInt(portString);
    }

    String dbHost = "localhost";
    if (commandLine.hasOption("dbh")) {
        dbHost = commandLine.getOptionValue("dbh");
    }

    int dbPort = 27017;
    if (commandLine.hasOption("dbp")) {
        String portString = commandLine.getOptionValue("dbp");
        dbPort = Integer.parseInt(portString);
    }

    boolean isIgnoringCase = true;
    if (commandLine.hasOption("case")) {
        isIgnoringCase = false;
    }

    boolean isStoppingEnabled = false;
    if (commandLine.hasOption("stop")) {
        isStoppingEnabled = true;
    }

    boolean isStemmingEnabled = false;
    if (commandLine.hasOption("stem")) {
        isStemmingEnabled = true;
    }

    try {
        Context context = Context.getInstance();
        context.setIgnoreCase(isIgnoringCase);
        context.setStopwordsEnabled(isStoppingEnabled);
        context.setStemmingEnabled(isStemmingEnabled);
        context.start(port, maxThreads, dbHost, dbPort);

    } catch (Exception ex) {
        ex.printStackTrace();
        logger.info("Shutting down the server...");
        System.exit(1);
    }
}

From source file:com.edduarte.vokter.Main.java

public static void main(String[] args) {

    installUncaughtExceptionHandler();/*from  w w w  .j a  v a  2s  .c o  m*/

    CommandLineParser parser = new GnuParser();
    Options options = new Options();

    options.addOption("t", "threads", true, "Number of threads to be used "
            + "for computation and indexing processes. Defaults to the number " + "of available cores.");

    options.addOption("p", "port", true, "Core server port. Defaults to 9000.");

    options.addOption("dbh", "db-host", true, "Database host. Defaults to localhost.");

    options.addOption("dbp", "db-port", true, "Database port. Defaults to 27017.");

    options.addOption("case", "preserve-case", false, "Keyword matching with case sensitivity.");

    options.addOption("stop", "stopwords", false, "Keyword matching with stopword filtering.");

    options.addOption("stem", "stemming", false, "Keyword matching with stemming (lexical variants).");

    options.addOption("h", "help", false, "Shows this help prompt.");

    CommandLine commandLine;
    try {
        // Parse the program arguments
        commandLine = parser.parse(options, args);
    } catch (ParseException ex) {
        logger.error("There was a problem processing the input arguments. "
                + "Write -h or --help to show the list of available commands.");
        logger.error(ex.getMessage(), ex);
        return;
    }

    if (commandLine.hasOption('h')) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("java -jar vokter-core.jar", options);
        return;
    }

    int maxThreads = Runtime.getRuntime().availableProcessors() - 1;
    maxThreads = maxThreads > 0 ? maxThreads : 1;
    if (commandLine.hasOption('t')) {
        String threadsText = commandLine.getOptionValue('t');
        maxThreads = Integer.parseInt(threadsText);
        if (maxThreads <= 0 || maxThreads > 32) {
            logger.error("Invalid number of threads. Must be a number between 1 and 32.");
            return;
        }
    }

    int port = 9000;
    if (commandLine.hasOption('p')) {
        String portString = commandLine.getOptionValue('p');
        port = Integer.parseInt(portString);
    }

    String dbHost = "localhost";
    if (commandLine.hasOption("dbh")) {
        dbHost = commandLine.getOptionValue("dbh");
    }

    int dbPort = 27017;
    if (commandLine.hasOption("dbp")) {
        String portString = commandLine.getOptionValue("dbp");
        dbPort = Integer.parseInt(portString);
    }

    boolean isIgnoringCase = true;
    if (commandLine.hasOption("case")) {
        isIgnoringCase = false;
    }

    boolean isStoppingEnabled = false;
    if (commandLine.hasOption("stop")) {
        isStoppingEnabled = true;
    }

    boolean isStemmingEnabled = false;
    if (commandLine.hasOption("stem")) {
        isStemmingEnabled = true;
    }

    try {
        Context context = Context.getInstance();
        context.setIgnoreCase(isIgnoringCase);
        context.setStopwordsEnabled(isStoppingEnabled);
        context.setStemmingEnabled(isStemmingEnabled);
        context.start(port, maxThreads, dbHost, dbPort);

    } catch (Exception ex) {
        ex.printStackTrace();
        logger.info("Shutting down the server...");
        System.exit(1);
    }
}

From source file:GIST.IzbirkomExtractor.IzbirkomExtractor.java

/**
 * @param args//from   w  w  w . jav a2 s  .c  om
 */
public static void main(String[] args) {

    // process command-line options
    Options options = new Options();
    options.addOption("n", "noaddr", false, "do not do any address matching (for testing)");
    options.addOption("i", "info", false, "create and populate address information table");
    options.addOption("h", "help", false, "this message");

    // database connection
    options.addOption("s", "server", true, "database server to connect to");
    options.addOption("d", "database", true, "OSM database name");
    options.addOption("u", "user", true, "OSM database user name");
    options.addOption("p", "pass", true, "OSM database password");

    // logging options
    options.addOption("l", "logdir", true, "log file directory (default './logs')");
    options.addOption("e", "loglevel", true, "log level (default 'FINEST')");

    // automatically generate the help statement
    HelpFormatter help_formatter = new HelpFormatter();

    // database URI for connection
    String dburi = null;

    // Information message for help screen
    String info_msg = "IzbirkomExtractor [options] <html_directory>";

    try {
        CommandLineParser parser = new GnuParser();
        CommandLine cmd = parser.parse(options, args);

        if (cmd.hasOption('h') || cmd.getArgs().length != 1) {
            help_formatter.printHelp(info_msg, options);
            System.exit(1);
        }

        /* prohibit n and i together */
        if (cmd.hasOption('n') && cmd.hasOption('i')) {
            System.err.println("Options 'n' and 'i' cannot be used together.");
            System.exit(1);
        }

        /* require database arguments without -n */
        if (cmd.hasOption('n')
                && (cmd.hasOption('s') || cmd.hasOption('d') || cmd.hasOption('u') || cmd.hasOption('p'))) {
            System.err.println("Options 'n' and does not need any databse parameters.");
            System.exit(1);
        }

        /* require all 4 database options to be used together */
        if (!cmd.hasOption('n')
                && !(cmd.hasOption('s') && cmd.hasOption('d') && cmd.hasOption('u') && cmd.hasOption('p'))) {
            System.err.println(
                    "For database access all of the following arguments have to be specified: server, database, user, pass");
            System.exit(1);
        }

        /* useful variables */
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'kk:mm");
        String dateString = formatter.format(new Date());

        /* setup logging */
        File logdir = new File(cmd.hasOption('l') ? cmd.getOptionValue('l') : "logs");
        FileUtils.forceMkdir(logdir);
        File log_file_name = new File(
                logdir + "/" + IzbirkomExtractor.class.getName() + "-" + formatter.format(new Date()) + ".log");
        FileHandler log_file = new FileHandler(log_file_name.getPath());

        /* create "latest" link to currently created log file */
        Path latest_log_link = Paths.get(logdir + "/latest");
        Files.deleteIfExists(latest_log_link);
        Files.createSymbolicLink(latest_log_link, Paths.get(log_file_name.getName()));

        log_file.setFormatter(new SimpleFormatter());
        LogManager.getLogManager().reset(); // prevents logging to console
        logger.addHandler(log_file);
        logger.setLevel(cmd.hasOption('e') ? Level.parse(cmd.getOptionValue('e')) : Level.FINEST);

        // open directory with HTML files and create file list
        File dir = new File(cmd.getArgs()[0]);
        if (!dir.isDirectory()) {
            System.err.println("Unable to find directory '" + cmd.getArgs()[0] + "', exiting");
            System.exit(1);
        }
        PathMatcher pmatcher = FileSystems.getDefault()
                .getPathMatcher("glob:?  * ?*.html");
        ArrayList<File> html_files = new ArrayList<>();
        for (Path file : Files.newDirectoryStream(dir.toPath()))
            if (pmatcher.matches(file.getFileName()))
                html_files.add(file.toFile());
        if (html_files.size() == 0) {
            System.err.println("No matching HTML files found in '" + dir.getAbsolutePath() + "', exiting");
            System.exit(1);
        }

        // create csvResultSink
        FileOutputStream csvout_file = new FileOutputStream("parsed_addresses-" + dateString + ".csv");
        OutputStreamWriter csvout = new OutputStreamWriter(csvout_file, "UTF-8");
        ResultSink csvResultSink = new CSVResultSink(csvout, new CSVStrategy('|', '"', '#'));

        // Connect to DB and osmAddressMatcher
        AddressMatcher osmAddressMatcher;
        DBSink dbSink = null;
        DBInfoSink dbInfoSink = null;
        if (cmd.hasOption('n')) {
            osmAddressMatcher = new DummyAddressMatcher();
        } else {
            dburi = "jdbc:postgresql://" + cmd.getOptionValue('s') + "/" + cmd.getOptionValue('d');
            Connection con = DriverManager.getConnection(dburi, cmd.getOptionValue('u'),
                    cmd.getOptionValue('p'));
            osmAddressMatcher = new OsmAddressMatcher(con);
            dbSink = new DBSink(con);
            if (cmd.hasOption('i'))
                dbInfoSink = new DBInfoSink(con);
        }

        /* create resultsinks */
        SinkMultiplexor sm = SinkMultiplexor.newSinkMultiplexor();
        sm.addResultSink(csvResultSink);
        if (dbSink != null) {
            sm.addResultSink(dbSink);
            if (dbInfoSink != null)
                sm.addResultSink(dbInfoSink);
        }

        // create tableExtractor
        TableExtractor te = new TableExtractor(osmAddressMatcher, sm);

        // TODO: printout summary of options: processing date/time, host, directory of HTML files, jdbc uri, command line with parameters

        // iterate through files
        logger.info("Start processing " + html_files.size() + " files in " + dir);
        for (int i = 0; i < html_files.size(); i++) {
            System.err.println("Parsing #" + i + ": " + html_files.get(i));
            te.processHTMLfile(html_files.get(i));
        }

        System.err.println("Processed " + html_files.size() + " HTML files");
        logger.info("Finished processing " + html_files.size() + " files in " + dir);

    } catch (ParseException e1) {
        System.err.println("Failed to parse CLI: " + e1.getMessage());
        help_formatter.printHelp(info_msg, options);
        System.exit(1);
    } catch (IOException e) {
        System.err.println("I/O Exception: " + e.getMessage());
        e.printStackTrace();
        System.exit(1);
    } catch (SQLException e) {
        System.err.println("Database '" + dburi + "': " + e.getMessage());
        System.exit(1);
    } catch (ResultSinkException e) {
        System.err.println("Failed to initialize ResultSink: " + e.getMessage());
        System.exit(1);
    } catch (TableExtractorException e) {
        System.err.println("Failed to initialize Table Extractor: " + e.getMessage());
        System.exit(1);
    } catch (CloneNotSupportedException | IllegalAccessException | InstantiationException e) {
        System.err.println("Something really odd happened: " + e.getMessage());
        e.printStackTrace();
        System.exit(1);
    }
}

From source file:com.github.trohovsky.just.Main.java

public static void main(String[] args) throws IOException {

    // parsing of command line
    final CommandLineParser parser = new GnuParser();

    final Options options = new Options();
    options.addOption("ai", true, "prefixes of classes from artifacts that will be included");
    options.addOption("ae", true, "prefixes of classes from artifacts that will be excluded");
    options.addOption("di", true, "prefixes of classes from dependencies that will be included");
    options.addOption("de", true, "prefixes of classes from dependencies that will be excluded");
    options.addOption("f", "flatten", false, "flatten report, display only used classes");
    options.addOption("p", "packages", false, "display package names instead of class names");
    options.addOption("u", "unused", false, "display unused classes from dependencies");
    options.addOption("h", "help", false, "print this help");

    CommandLine cmdLine = null;//w  w  w . j a va  2s  .  co  m
    try {
        cmdLine = parser.parse(options, args);
        if (cmdLine.hasOption('h')) {
            final HelpFormatter formatter = new HelpFormatter();
            formatter.setOptionComparator(null);
            formatter.printHelp(HELP_CMDLINE, HELP_HEADER, options, HELP_FOOTER);
            return;
        }
        if (cmdLine.getArgs().length == 0) {
            throw new ParseException("Missing ARTIFACT and/or DEPENDENCY.");
        } else if (cmdLine.getArgs().length > 2) {
            throw new ParseException(
                    "More that two arquments found, multiple ARTIFACTs DEPENDENCies should be separated by ','"
                            + " without whitespaces.");
        }

    } catch (ParseException e) {
        System.err.println("Error parsing command line: " + e.getMessage());
        final HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(HELP_CMDLINE, HELP_HEADER, options, HELP_FOOTER);
        return;
    }

    // obtaining of values
    final String[] artifactPaths = cmdLine.getArgs()[0].split(",");
    final String[] dependencyPaths = cmdLine.getArgs().length == 2 ? cmdLine.getArgs()[1].split(",") : null;
    final String[] artifactIncludes = splitValues(cmdLine.getOptionValue("ai"));
    final String[] artifactExcludes = splitValues(cmdLine.getOptionValue("ae"));
    final String[] dependencyIncludes = splitValues(cmdLine.getOptionValue("di"));
    final String[] dependencyExcludes = splitValues(cmdLine.getOptionValue("de"));

    // validation of values
    if (dependencyPaths == null) {
        if (dependencyIncludes != null) {
            System.err.println("At least one dependency has to be specified to use option -di");
            return;
        }
        if (dependencyExcludes != null) {
            System.err.println("At least one dependency has to be specified to use option -de");
            return;
        }
        if (cmdLine.hasOption('u')) {
            System.err.println("At least one dependency has to be specified to use option -u");
            return;
        }
    }

    // execution
    Set<String> externalClasses = null;
    if (dependencyPaths != null) {
        externalClasses = Reader.from(dependencyPaths).includes(dependencyIncludes).excludes(dependencyExcludes)
                .listClasses();
    }

    if (cmdLine.hasOption('f') || cmdLine.hasOption('u')) {
        Set<String> dependencies = Reader.from(artifactPaths).includes(artifactIncludes)
                .excludes(artifactExcludes).readDependencies();
        if (externalClasses != null) {
            dependencies = DependencyUtils.intersection(dependencies, externalClasses);
            if (cmdLine.hasOption('u')) {
                dependencies = DependencyUtils.subtract(externalClasses, dependencies);
            }
        }
        if (cmdLine.hasOption('p')) {
            dependencies = DependencyUtils.toPackageNames(dependencies);
        }
        Reporter.report(dependencies);
    } else {
        Map<String, Set<String>> classesWithDependencies = Reader.from(artifactPaths).includes(artifactIncludes)
                .excludes(artifactExcludes).readClassesWithDependencies();
        if (externalClasses != null) {
            classesWithDependencies = DependencyUtils.intersection(classesWithDependencies, externalClasses);
        }
        if (cmdLine.hasOption('p')) {
            classesWithDependencies = DependencyUtils.toPackageNames(classesWithDependencies);
        }
        Reporter.report(classesWithDependencies);
    }
}

From source file:de.ncoder.studipsync.Starter.java

public static void main(String[] args) throws Exception {
    boolean displayHelp = false;
    CommandLineParser parser = new DefaultParser();
    try {/*w  w  w .j a v  a  2  s .c  o m*/
        CommandLine cmd = parser.parse(OPTIONS, args);
        if (cmd.hasOption(OPTION_HELP)) {
            displayHelp = true;
            return;
        }

        Syncer syncer = createSyncer(cmd);
        StorageLog storeLog = new StorageLog();
        syncer.getStorage().registerListener(storeLog);
        try {
            log.info("Started " + getImplementationTitle() + " " + getImplementationVersion());
            syncer.sync();
            log.info(storeLog.getStatusMessage(syncer.getStorage().getRoot()));
            log.info("Finished");
        } finally {
            syncer.close();
        }
    } catch (ParseException e) {
        System.out.println("Illegal arguments passed. " + e.getMessage());
        displayHelp = true;
    } finally {
        if (displayHelp) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("studip-sync", OPTIONS);
        }
    }
    //TODO AWT Event Queue blocks termination with modality level 1
    System.exit(0);
}

From source file:de.zib.chordsharp.Main.java

/**
 * Queries the command line options for an action to perform.
 * /*from w w  w.  j a  v a  2 s  .  c  o  m*/
 * <pre>
 * {@code
 * > java -jar chordsharp.jar -help
 * usage: chordsharp
 *  -getsubscribers <topic>   get subscribers of a topic
 *  -help                     print this message
 *  -publish <params>         publish a new message for a topic: <topic> <message>
 *  -read <key>               read an item
 *  -subscribe <params>       subscribe to a topic: <topic> <url>
 *  -unsubscribe <params>     unsubscribe from a topic: <topic> <url>
 *  -write <params>           write an item: <key> <value>
 *  -minibench                run mini benchmark
 * }
 * </pre>
 * 
 * @param args command line arguments
 */
public static void main(String[] args) {
    CommandLineParser parser = new GnuParser();
    CommandLine line = null;
    try {
        line = parser.parse(getOptions(), args);
    } catch (ParseException e) {
        System.err.println("Parsing failed. Reason: " + e.getMessage());
        System.exit(0);
    }

    if (line.hasOption("help")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("chordsharp", getOptions());
        System.exit(0);
    }

    if (line.hasOption("minibench")) {
        minibench();
        System.exit(0);
    }

    if (line.hasOption("read")) {
        try {
            System.out.println("read(" + line.getOptionValue("read") + ") == "
                    + ChordSharp.read(line.getOptionValue("read")));
        } catch (ConnectionException e) {
            System.err.println("read failed: " + e.getMessage());
        } catch (TimeoutException e) {
            System.err.println("read failed with timeout: " + e.getMessage());
        } catch (NotFoundException e) {
            System.err.println("read failed with not found: " + e.getMessage());
        } catch (UnknownException e) {
            System.err.println("read failed with unknown: " + e.getMessage());
        }
    }
    if (line.hasOption("write")) {
        try {
            System.out.println("write(" + line.getOptionValues("write")[0] + ", "
                    + line.getOptionValues("write")[1] + ")");
            ChordSharp.write(line.getOptionValues("write")[0], line.getOptionValues("write")[1]);
        } catch (ConnectionException e) {
            System.err.println("write failed with connection error: " + e.getMessage());
        } catch (TimeoutException e) {
            System.err.println("write failed with timeout: " + e.getMessage());
        } catch (UnknownException e) {
            System.err.println("write failed with unknown: " + e.getMessage());
        }
    }
    if (line.hasOption("publish")) {
        try {
            System.out.println("publish(" + line.getOptionValues("publish")[0] + ", "
                    + line.getOptionValues("publish")[1] + ")");
            ChordSharp.publish(line.getOptionValues("publish")[0], line.getOptionValues("publish")[1]);
        } catch (ConnectionException e) {
            System.err.println("publish failed with connection error: " + e.getMessage());
            //         } catch (TimeoutException e) {
            //            System.err.println("publish failed with timeout: "
            //                  + e.getMessage());
            //         } catch (UnknownException e) {
            //            System.err.println("publish failed with unknown: "
            //                  + e.getMessage());
        }
    }
    if (line.hasOption("subscribe")) {
        try {
            System.out.println("subscribe(" + line.getOptionValues("subscribe")[0] + ", "
                    + line.getOptionValues("subscribe")[1] + ")");
            ChordSharp.subscribe(line.getOptionValues("subscribe")[0], line.getOptionValues("subscribe")[1]);
        } catch (ConnectionException e) {
            System.err.println("subscribe failed with connection error: " + e.getMessage());
        } catch (TimeoutException e) {
            System.err.println("subscribe failed with timeout: " + e.getMessage());
        } catch (UnknownException e) {
            System.err.println("subscribe failed with unknown: " + e.getMessage());
        }
    }
    if (line.hasOption("unsubscribe")) {
        try {
            System.out.println("unsubscribe(" + line.getOptionValues("unsubscribe")[0] + ", "
                    + line.getOptionValues("unsubscribe")[1] + ")");
            ChordSharp.unsubscribe(line.getOptionValues("unsubscribe")[0],
                    line.getOptionValues("unsubscribe")[1]);
        } catch (ConnectionException e) {
            System.err.println("unsubscribe failed with connection error: " + e.getMessage());
        } catch (TimeoutException e) {
            System.err.println("unsubscribe failed with timeout: " + e.getMessage());
        } catch (NotFoundException e) {
            System.err.println("unsubscribe failed with not found: " + e.getMessage());
        } catch (UnknownException e) {
            System.err.println("unsubscribe failed with unknown: " + e.getMessage());
        }
    }
    if (line.hasOption("getsubscribers")) {
        try {
            System.out.println("getSubscribers(" + line.getOptionValues("getsubscribers")[0] + ") == "
                    + ChordSharp.getSubscribers(line.getOptionValues("getsubscribers")[0]));
        } catch (ConnectionException e) {
            System.err.println("getSubscribers failed with connection error: " + e.getMessage());
            //         } catch (TimeoutException e) {
            //            System.err.println("getSubscribers failed with timeout: "
            //                  + e.getMessage());
        } catch (UnknownException e) {
            System.err.println("getSubscribers failed with unknown error: " + e.getMessage());
        }
    }
}

From source file:fr.tpt.s3.mcdag.scheduling.Main.java

public static void main(String[] args) throws IOException, InterruptedException {

    /* Command line options */
    Options options = new Options();

    Option input = new Option("i", "input", true, "MC-DAG XML Models");
    input.setRequired(true);//from w ww  .ja v  a  2  s  . c om
    input.setArgs(Option.UNLIMITED_VALUES); // Sets maximum number of threads to be launched
    options.addOption(input);

    Option outSched = new Option("os", "out-scheduler", false, "Write the scheduling tables into a file.");
    outSched.setRequired(false);
    options.addOption(outSched);

    Option outPrism = new Option("op", "out-prism", false, "Write PRISM model into a file.");
    outPrism.setRequired(false);
    options.addOption(outPrism);

    Option jobs = new Option("j", "jobs", true, "Number of threads to be launched.");
    jobs.setRequired(false);
    options.addOption(jobs);

    Option debugOpt = new Option("d", "debug", false, "Enabling debug.");
    debugOpt.setRequired(false);
    options.addOption(debugOpt);

    Option preemptOpt = new Option("p", "preempt", false, "Count for preemptions.");
    preemptOpt.setRequired(false);
    options.addOption(preemptOpt);

    CommandLineParser parser = new DefaultParser();
    HelpFormatter formatter = new HelpFormatter();
    CommandLine cmd;

    try {
        cmd = parser.parse(options, args);
    } catch (ParseException e) {
        System.err.println(e.getMessage());
        formatter.printHelp("MC-DAG framework", options);

        System.exit(1);
        return;
    }

    String inputFilePath[] = cmd.getOptionValues("input");
    boolean bOutSched = cmd.hasOption("out-scheduler");
    boolean bOutPrism = cmd.hasOption("out-prism");
    boolean debug = cmd.hasOption("debug");
    boolean preempt = cmd.hasOption("preempt");
    boolean levels = cmd.hasOption("n-levels");
    int nbFiles = inputFilePath.length;

    int nbJobs = 1;
    if (cmd.hasOption("jobs"))
        nbJobs = Integer.parseInt(cmd.getOptionValue("jobs"));

    if (debug)
        System.out.println("[DEBUG] Launching " + inputFilePath.length + " thread(s).");

    int i_files = 0;
    ExecutorService executor = Executors.newFixedThreadPool(nbJobs);

    /* Launch threads to solve allocation */
    while (i_files != nbFiles) {
        SchedulingThread ft = new SchedulingThread(inputFilePath[i_files], bOutSched, bOutPrism, debug,
                preempt);

        ft.setLevels(levels);
        executor.execute(ft);
        i_files++;
    }

    executor.shutdown();
    executor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
    System.out.println("[FRAMEWORK Main] DONE");
}

From source file:com.ingby.socbox.bischeck.configuration.DocManager.java

/**
 * @param args/*from  w  w  w  .j  a va2  s .  c  om*/
 */
public static void main(String[] args) {
    CommandLineParser parser = new GnuParser();
    CommandLine line = null;
    // create the Options
    Options options = new Options();
    options.addOption("u", "usage", false, "show usage.");
    options.addOption("d", "directory", true, "output directory");
    options.addOption("t", "type", true, "type of out put - html or csv");

    try {
        // parse the command line arguments
        line = parser.parse(options, args);

    } catch (org.apache.commons.cli.ParseException e) {
        System.out.println("Command parse error:" + e.getMessage());
        Util.ShellExit(FAILED);
    }

    if (line.hasOption("usage")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("DocManager", options);
        Util.ShellExit(OKAY);
    }

    DocManager dmgmt = null;

    if (line.hasOption("directory")) {
        String dirname = line.getOptionValue("directory");
        try {
            dmgmt = new DocManager(dirname);
        } catch (IOException ioe) {
            System.out.println(ioe.getMessage());
            Util.ShellExit(FAILED);
        }
    } else {
        try {
            dmgmt = new DocManager();
        } catch (IOException ioe) {
            System.out.println(ioe.getMessage());
            Util.ShellExit(FAILED);
        }
    }

    try {
        if (line.hasOption("type")) {
            String type = line.getOptionValue("type");
            if ("html".equalsIgnoreCase(type)) {
                dmgmt.genHtml();
            } else if ("text".equalsIgnoreCase(type)) {
                dmgmt.genText();
            }
        } else {
            dmgmt.genHtml();
        }
    } catch (Exception e) {
        System.out.println(e.getMessage());
        Util.ShellExit(FAILED);
    }
}

From source file:fr.inria.edelweiss.kgdqp.core.FedQueryingCLI.java

@SuppressWarnings("unchecked")
public static void main(String args[]) throws ParseException, EngineException {

    List<String> endpoints = new ArrayList<String>();
    String queryPath = null;//from   w  w  w  . ja  v  a 2  s  .  co  m
    int slice = -1;

    Options options = new Options();
    Option helpOpt = new Option("h", "help", false, "print this message");
    Option queryOpt = new Option("q", "query", true, "specify the sparql query file");
    Option endpointOpt = new Option("e", "endpoints", true, "the list of federated sparql endpoint URLs");
    Option groupingOpt = new Option("g", "grouping", true, "triple pattern optimisation");
    Option slicingOpt = new Option("s", "slicing", true, "size of the slicing parameter");
    Option versionOpt = new Option("v", "version", false, "print the version information and exit");
    options.addOption(queryOpt);
    options.addOption(endpointOpt);
    options.addOption(helpOpt);
    options.addOption(versionOpt);
    options.addOption(groupingOpt);
    options.addOption(slicingOpt);

    String header = "Corese/KGRAM DQP command line interface";
    String footer = "\nPlease report any issue to alban.gaignard@cnrs.fr";

    CommandLineParser parser = new BasicParser();
    CommandLine cmd = parser.parse(options, args);
    if (cmd.hasOption("h")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("kgdqp", header, options, footer, true);
        System.exit(0);
    }
    if (!cmd.hasOption("e")) {
        logger.info("You must specify at least the URL of one sparql endpoint !");
        System.exit(0);
    } else {
        endpoints = new ArrayList<String>(Arrays.asList(cmd.getOptionValues("e")));
    }
    if (!cmd.hasOption("q")) {
        logger.info("You must specify a path for a sparql query !");
        System.exit(0);
    } else {
        queryPath = cmd.getOptionValue("q");
    }
    if (cmd.hasOption("s")) {
        try {
            slice = Integer.parseInt(cmd.getOptionValue("s"));
        } catch (NumberFormatException ex) {
            logger.warn(cmd.getOptionValue("s") + " is not formatted as number for the slicing parameter");
            logger.warn("Slicing disabled");
        }
    }
    if (cmd.hasOption("v")) {
        logger.info("version 3.0.4-SNAPSHOT");
        System.exit(0);
    }

    /////////////////
    Graph graph = Graph.create();
    QueryProcessDQP exec = QueryProcessDQP.create(graph);
    exec.setGroupingEnabled(cmd.hasOption("g"));
    if (slice > 0) {
        exec.setSlice(slice);
    }
    Provider sProv = ProviderImplCostMonitoring.create();
    exec.set(sProv);

    for (String url : endpoints) {
        try {
            exec.addRemote(new URL(url), WSImplem.REST);
        } catch (MalformedURLException ex) {
            logger.error(url + " is not a well-formed URL");
            System.exit(1);
        }
    }

    StringBuffer fileData = new StringBuffer(1000);
    BufferedReader reader = null;
    try {
        reader = new BufferedReader(new FileReader(queryPath));
    } catch (FileNotFoundException ex) {
        logger.error("Query file " + queryPath + " not found !");
        System.exit(1);
    }
    char[] buf = new char[1024];
    int numRead = 0;
    try {
        while ((numRead = reader.read(buf)) != -1) {
            String readData = String.valueOf(buf, 0, numRead);
            fileData.append(readData);
            buf = new char[1024];
        }
        reader.close();
    } catch (IOException ex) {
        logger.error("Error while reading query file " + queryPath);
        System.exit(1);
    }

    String sparqlQuery = fileData.toString();

    //        Query q = exec.compile(sparqlQuery, null);
    //        System.out.println(q);

    StopWatch sw = new StopWatch();
    sw.start();
    Mappings map = exec.query(sparqlQuery);
    int dqpSize = map.size();
    System.out.println("--------");
    long time = sw.getTime();
    System.out.println(time + " " + dqpSize);
}