Example usage for org.apache.commons.cli CommandLineParser parse

List of usage examples for org.apache.commons.cli CommandLineParser parse

Introduction

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

Prototype

CommandLine parse(Options options, String[] arguments) throws ParseException;

Source Link

Document

Parse the arguments according to the specified options.

Usage

From source file:com.msbmsb.genealogeo.ui.cli.GenealoGeoCLI.java

/**
 * Command-line interface/*from  w  w w .j  av a  2s. co  m*/
 */
public static void main(String[] args) throws Exception {
    GenealoGeoCLI cli = new GenealoGeoCLI();

    // parse command line
    String inputFileName = "";
    try {
        CommandLineParser parser = new GnuParser();
        CommandLine cl = parser.parse(cli.opts, args);
        inputFileName = cl.getOptionValue("file");
        if (cl.hasOption("help"))
            throw new ParseException(null);
    } catch (ParseException e) {
        cli.usage(e.getMessage());
    }

    // require an input file
    if (inputFileName == null) {
        cli.usage("Error: No input file given.");
    }

    // verify and load the input file
    File inputFile = new File(inputFileName);
    if (!inputFile.exists()) {
        cli.usage("Error: Could not open input file: " + inputFileName);
    }

    cli.load(inputFile);

    //  testing functions
    cli.genealoGeo.printFamilies();
    cli.genealoGeo.printLocations();
}

From source file:com.jbrisbin.vcloud.cache.Bootstrap.java

public static void main(String[] args) {

    CommandLineParser parser = new BasicParser();
    CommandLine cmdLine = null;/*from w  w w  . j a v a 2 s.  c om*/
    try {
        cmdLine = parser.parse(opts, args);
    } catch (ParseException e) {
        log.error(e.getMessage(), e);
    }

    String configFile = "/etc/cloud/async-cache.xml";
    if (null != cmdLine) {
        if (cmdLine.hasOption('c')) {
            configFile = cmdLine.getOptionValue('c');
        }
    }

    ApplicationContext context = new FileSystemXmlApplicationContext(configFile);
    RabbitMQAsyncCacheProvider cacheProvider = context.getBean(RabbitMQAsyncCacheProvider.class);
    while (cacheProvider.isActive()) {
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            log.error(e.getMessage(), e);
        }
    }

}

From source file:com.kylinolap.query.QueryCli.java

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

    Options options = new Options();
    options.addOption(OPTION_METADATA);/*from   w ww . java  2 s.co m*/
    options.addOption(OPTION_SQL);

    CommandLineParser parser = new GnuParser();
    CommandLine commandLine = parser.parse(options, args);
    KylinConfig config = KylinConfig
            .createInstanceFromUri(commandLine.getOptionValue(OPTION_METADATA.getOpt()));
    String sql = commandLine.getOptionValue(OPTION_SQL.getOpt());

    Class.forName("net.hydromatic.optiq.jdbc.Driver");
    File olapTmp = OLAPSchemaFactory.createTempOLAPJson(null, config);

    Connection conn = null;
    Statement stmt = null;
    ResultSet rs = null;
    try {
        conn = DriverManager.getConnection("jdbc:optiq:model=" + olapTmp.getAbsolutePath());

        stmt = conn.createStatement();
        rs = stmt.executeQuery(sql);
        int n = 0;
        ResultSetMetaData meta = rs.getMetaData();
        while (rs.next()) {
            n++;
            for (int i = 1; i <= meta.getColumnCount(); i++) {
                System.out.println(n + " - " + meta.getColumnLabel(i) + ":\t" + rs.getObject(i));
            }
        }
    } finally {
        if (rs != null) {
            rs.close();
        }
        if (stmt != null) {
            stmt.close();
        }
        if (conn != null) {
            conn.close();
        }
    }

}

From source file:com.sourcethought.simpledaemon.EchoTask.java

public static void main(String[] args) throws Exception {
    // setup command line options
    Options options = new Options();
    options.addOption("h", "help", false, "print this help screen");

    // read command line options
    CommandLineParser parser = new PosixParser();
    try {/* w w  w .j  a  v  a  2  s .  c o  m*/
        CommandLine cmdline = parser.parse(options, args);

        if (cmdline.hasOption("help") || cmdline.hasOption("h")) {
            System.out.println("SimpleDaemon Version " + Main.version);

            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp(
                    "java -cp lib/*:target/SimpleDaemon-1.0-SNAPSHOT.jar com.sourcethought.simpledaemon.Main",
                    options);
            return;
        }

        final SimpleDaemon daemon = new SimpleDaemon();
        daemon.start();

        Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
            @Override
            public void run() {
                if (daemon.isRunning()) {
                    try {
                        System.out.println("Shutting down daemon...");
                        daemon.stop();
                    } catch (Exception ex) {
                        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            }
        }));

    } catch (ParseException ex) {
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:net.librec.tool.driver.RecDriver.java

public static void main(String[] args) throws Exception {
    LibrecTool tool = new RecDriver();

    Options options = new Options();
    options.addOption("build", false, "build model");
    options.addOption("load", false, "load model");
    options.addOption("save", false, "save model");
    options.addOption("exec", false, "run job");
    options.addOption("conf", true, "the path of configuration file");
    options.addOption("jobconf", true, "a specified key-value pair for configuration");
    options.addOption("D", true, "a specified key-value pair for configuration");

    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = parser.parse(options, args);

    if (cmd.hasOption("build")) {
        ;/*from www . ja  v  a2 s  .c  o m*/
    } else if (cmd.hasOption("load")) {
        ;
    } else if (cmd.hasOption("save")) {
        ;
    } else if (cmd.hasOption("exec")) {
        tool.run(args);
    }
}

From source file:cc.wikitools.lucene.ScoreWikipediaArticle.java

@SuppressWarnings("static-access")
public static void main(String[] args) throws Exception {
    Options options = new Options();
    options.addOption(/*from   w  w w  .ja  v a2 s .c  o  m*/
            OptionBuilder.withArgName("path").hasArg().withDescription("index location").create(INDEX_OPTION));
    options.addOption(
            OptionBuilder.withArgName("num").hasArg().withDescription("article id").create(ID_OPTION));
    options.addOption(
            OptionBuilder.withArgName("string").hasArg().withDescription("article title").create(TITLE_OPTION));
    options.addOption(
            OptionBuilder.withArgName("string").hasArg().withDescription("query text").create(QUERY_OPTION));

    CommandLine cmdline = null;
    CommandLineParser parser = new GnuParser();
    try {
        cmdline = parser.parse(options, args);
    } catch (ParseException exp) {
        System.err.println("Error parsing command line: " + exp.getMessage());
        System.exit(-1);
    }

    if (!(cmdline.hasOption(ID_OPTION) || cmdline.hasOption(TITLE_OPTION)) || !cmdline.hasOption(INDEX_OPTION)
            || !cmdline.hasOption(QUERY_OPTION)) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(ScoreWikipediaArticle.class.getName(), options);
        System.exit(-1);
    }

    File indexLocation = new File(cmdline.getOptionValue(INDEX_OPTION));
    if (!indexLocation.exists()) {
        System.err.println("Error: " + indexLocation + " does not exist!");
        System.exit(-1);
    }

    String queryText = cmdline.getOptionValue(QUERY_OPTION);

    WikipediaSearcher searcher = new WikipediaSearcher(indexLocation);
    PrintStream out = new PrintStream(System.out, true, "UTF-8");

    if (cmdline.hasOption(ID_OPTION)) {
        out.println("score: "
                + searcher.scoreArticle(queryText, Integer.parseInt(cmdline.getOptionValue(ID_OPTION))));
    } else {
        out.println("score: " + searcher.scoreArticle(queryText, cmdline.getOptionValue(TITLE_OPTION)));
    }

    searcher.close();
    out.close();
}

From source file:com.bc.fiduceo.post.PostProcessingToolMain.java

public static void main(String[] args) throws ParseException {
    final CommandLineParser parser = new PosixParser();
    final CommandLine commandLine;
    try {/*ww w . j a v  a 2  s  . c o m*/
        commandLine = parser.parse(PostProcessingTool.getOptions(), args);
    } catch (ParseException e) {
        System.err.println(e.getMessage());
        System.err.println();
        PostProcessingTool.printUsageTo(System.err);
        return;
    }
    if (commandLine.hasOption("h") || commandLine.hasOption("--help")) {
        PostProcessingTool.printUsageTo(System.out);
        return;
    }

    try {
        final PostProcessingContext context = PostProcessingTool.initializeContext(commandLine);
        final PostProcessingTool tool = new PostProcessingTool(context);
        tool.runPostProcessing();
    } catch (Throwable e) {
        FiduceoLogger.getLogger().severe(e.getMessage());
        e.printStackTrace();
        System.exit(-1);
    }
}

From source file:com.github.zerkseez.codegen.wrappergenerator.Main.java

public static void main(final String[] args) throws Exception {
    final Options options = new Options();
    options.addOption(Option.builder().longOpt("outputDirectory").hasArg().required().build());
    options.addOption(Option.builder().longOpt("classMappings").hasArgs().required().build());

    final CommandLineParser parser = new DefaultParser();

    try {/*  ww w  . j a v  a2s  .  c o  m*/
        final CommandLine line = parser.parse(options, args);
        final String outputDirectory = line.getOptionValue("outputDirectory");
        final String[] classMappings = line.getOptionValues("classMappings");
        for (String classMapping : classMappings) {
            final String[] tokens = classMapping.split(":");
            if (tokens.length != 2) {
                throw new IllegalArgumentException(
                        String.format("Invalid class mapping format \"%s\"", classMapping));
            }
            final Class<?> wrappeeClass = Class.forName(tokens[0]);
            final String fullWrapperClassName = tokens[1];
            final int indexOfLastDot = fullWrapperClassName.lastIndexOf('.');
            final String wrapperPackageName = (indexOfLastDot == -1) ? ""
                    : fullWrapperClassName.substring(0, indexOfLastDot);
            final String simpleWrapperClassName = (indexOfLastDot == -1) ? fullWrapperClassName
                    : fullWrapperClassName.substring(indexOfLastDot + 1);

            System.out.println(String.format("Generating wrapper class for %s...", wrappeeClass));
            final WrapperGenerator generator = new WrapperGenerator(wrappeeClass, wrapperPackageName,
                    simpleWrapperClassName);
            generator.writeTo(outputDirectory, true);
        }
        System.out.println("Done");
    } catch (MissingOptionException e) {
        final HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(String.format("java -cp CLASSPATH %s", Main.class.getName()), options);
    }
}

From source file:com.cloudera.flume.handlers.debug.TextToCollector.java

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

    Options opts = new Options();
    opts.addOption("m", false, "Load events into memory");
    opts.addOption("t", false, "Simple text file format loader");
    opts.addOption("l", false, "Log4j text file format loader");

    try {//  w  w w .j  av a  2 s  .  co  m
        if (argv.length < 1) {
            HelpFormatter fmt = new HelpFormatter();
            fmt.printHelp("TextToCollector", opts, true);
            System.exit(-1);
        }

        CommandLineParser parser = new PosixParser();
        CommandLine cmd = parser.parse(opts, argv);

        core(cmd);
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:com.floragunn.searchguard.tools.Hasher.java

public static void main(final String[] args) {

    final Options options = new Options();
    final HelpFormatter formatter = new HelpFormatter();
    options.addOption(/*w w  w .j a v  a 2s .co  m*/
            Option.builder("p").argName("password").hasArg().desc("Cleartext password to hash").build());
    options.addOption(Option.builder("env").argName("name environment variable").hasArg()
            .desc("name environment variable to read password from").build());

    final CommandLineParser parser = new DefaultParser();
    try {
        final CommandLine line = parser.parse(options, args);

        if (line.hasOption("p")) {
            System.out.println(hash(line.getOptionValue("p").getBytes("UTF-8")));
        } else if (line.hasOption("env")) {
            final String pwd = System.getenv(line.getOptionValue("env"));
            if (pwd == null || pwd.isEmpty()) {
                throw new Exception("No environment variable '" + line.getOptionValue("env") + "' set");
            }
            System.out.println(hash(pwd.getBytes("UTF-8")));
        } else {
            final Console console = System.console();
            if (console == null) {
                throw new Exception("Cannot allocate a console");
            }
            final char[] passwd = console.readPassword("[%s]", "Password:");
            System.out.println(hash(new String(passwd).getBytes("UTF-8")));
        }
    } catch (final Exception exp) {
        System.err.println("Parsing failed.  Reason: " + exp.getMessage());
        formatter.printHelp("hasher.sh", options, true);
        System.exit(-1);
    }
}