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

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

Introduction

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

Prototype

GnuParser

Source Link

Usage

From source file:com.dasasian.chok.tool.ZkTool.java

public static void main(String[] args) {
    final Options options = new Options();

    Option lsOption = new Option("ls", true, "list zp path contents");
    lsOption.setArgName("path");
    Option readOption = new Option("read", true, "read and print zp path contents");
    readOption.setArgName("path");
    Option rmOption = new Option("rm", true, "remove zk files");
    rmOption.setArgName("path");
    Option rmrOption = new Option("rmr", true, "remove zk directories");
    rmrOption.setArgName("path");

    OptionGroup actionGroup = new OptionGroup();
    actionGroup.setRequired(true);//  ww  w  .  j a  va 2  s  .c  o  m
    actionGroup.addOption(lsOption);
    actionGroup.addOption(readOption);
    actionGroup.addOption(rmOption);
    actionGroup.addOption(rmrOption);
    options.addOptionGroup(actionGroup);

    final CommandLineParser parser = new GnuParser();
    HelpFormatter formatter = new HelpFormatter();
    try {
        final CommandLine line = parser.parse(options, args);
        ZkTool zkTool = new ZkTool();
        if (line.hasOption(lsOption.getOpt())) {
            String path = line.getOptionValue(lsOption.getOpt());
            zkTool.ls(path);
        } else if (line.hasOption(readOption.getOpt())) {
            String path = line.getOptionValue(readOption.getOpt());
            zkTool.read(path);
        } else if (line.hasOption(rmOption.getOpt())) {
            String path = line.getOptionValue(rmOption.getOpt());
            zkTool.rm(path, false);
        } else if (line.hasOption(rmrOption.getOpt())) {
            String path = line.getOptionValue(rmrOption.getOpt());
            zkTool.rm(path, true);
        }
        zkTool.close();
    } catch (ParseException e) {
        System.out.println(e.getClass().getSimpleName() + ": " + e.getMessage());
        formatter.printHelp(ZkTool.class.getSimpleName(), options);
    }

}

From source file:cc.twittertools.util.ExtractSubcollection.java

@SuppressWarnings("static-access")
public static void main(String[] args) throws Exception {
    Options options = new Options();

    options.addOption(OptionBuilder.withArgName("dir").hasArg().withDescription("source collection directory")
            .create(COLLECTION_OPTION));
    options.addOption(// w ww  .j  a  v a2 s .  c o m
            OptionBuilder.withArgName("file").hasArg().withDescription("list of tweetids").create(ID_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(COLLECTION_OPTION) || !cmdline.hasOption(ID_OPTION)) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(ExtractSubcollection.class.getName(), options);
        System.exit(-1);
    }

    String collectionPath = cmdline.getOptionValue(COLLECTION_OPTION);

    LongOpenHashSet tweetids = new LongOpenHashSet();
    File tweetidsFile = new File(cmdline.getOptionValue(ID_OPTION));
    if (!tweetidsFile.exists()) {
        System.err.println("Error: " + tweetidsFile + " does not exist!");
        System.exit(-1);
    }
    LOG.info("Reading tweetids from " + tweetidsFile);

    FileInputStream fin = new FileInputStream(tweetidsFile);
    BufferedReader br = new BufferedReader(new InputStreamReader(fin));

    String s;
    while ((s = br.readLine()) != null) {
        tweetids.add(Long.parseLong(s));
    }
    br.close();
    fin.close();
    LOG.info("Read " + tweetids.size() + " tweetids.");

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

    PrintStream out = new PrintStream(System.out, true, "UTF-8");
    StatusStream stream = new JsonStatusCorpusReader(file);
    Status status;
    while ((status = stream.next()) != null) {
        if (tweetids.contains(status.getId())) {
            out.println(status.getJsonObject().toString());
        }
    }
    stream.close();
    out.close();
}

From source file:fr.ens.biologie.genomique.toullig.Main.java

/**
 * The main function parse the options of the command line
 *///from   ww  w . j a v  a 2  s  .  c o  m
public static void main(String[] args) {

    // make options
    final Options options = makeOptions();

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

    try {

        // parse the command line arguments
        final CommandLine line = parser.parse(options, args, true);

        // test if no arguments is given
        if (args.length == 0) {

            showErrorMessageAndExit(
                    "ERROR: Toullig need in the first argument the tool what you want use!\nSee the help with "
                            + Globals.APP_NAME_LOWER_CASE + ".sh -h, --help\n");

        }

        // display help
        if (line.hasOption("help")) {
            help();
        }

        // About option
        if (line.hasOption("about")) {
            Common.showMessageAndExit(Globals.ABOUT_TXT);
        }

        // Version option
        if (line.hasOption("version")) {
            Common.showMessageAndExit(Globals.WELCOME_MSG);
        }

        // Licence option
        if (line.hasOption("license")) {
            Common.showMessageAndExit(Globals.LICENSE_TXT);
        }

        String mode = args[0];

        switch (mode) {

        // process fast5tofastq module
        case "fast5tofastq":

            new Fast5tofastqAction().action(new ArrayList<>(Arrays.asList(args)).subList(1, args.length));

            break;

        // display help
        default:

            showMessageAndExit("ERROR: The name of the tool is not correct!\nSee the help with "
                    + Globals.APP_NAME_LOWER_CASE + ".sh -h, --help\n");

            break;

        // process trim module
        case "trim":

            new TrimAction().action(new ArrayList<>(Arrays.asList(args)).subList(1, args.length));

            break;

        // process gtftogpd module
        case "gtftogpd":

            new GtftogpdAction().action(new ArrayList<>(Arrays.asList(args)).subList(1, args.length));

            break;

        // // process test module
        // case "test":
        // new SamDiffAnnot();
        // break;

        }
    } catch (ParseException e) {
        e.printStackTrace();
    }
}

From source file:edu.gslis.ts.ThriftToTREC.java

public static void main(String[] args) {
    try {/* w  w w  . j  a va 2 s.  c o  m*/
        // Get the commandline options
        Options options = createOptions();
        CommandLineParser parser = new GnuParser();
        CommandLine cmd = parser.parse(options, args);

        String in = cmd.getOptionValue("i");
        String outfile = cmd.getOptionValue("o");
        String sentenceParser = cmd.getOptionValue("p");

        // Setup the filter
        ThriftToTREC f = new ThriftToTREC();

        if (in != null && outfile != null) {
            File infile = new File(in);
            if (infile.isDirectory()) {
                for (File file : infile.listFiles()) {
                    if (file.isDirectory()) {
                        for (File filefile : file.listFiles()) {
                            f.filter(filefile, new File(outfile), sentenceParser);
                        }
                    } else {
                        f.filter(file, new File(outfile), sentenceParser);
                    }
                }
            } else
                f.filter(infile, new File(outfile), sentenceParser);
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.subakva.formicid.Main.java

public static void main(final String[] args) {
    Options options = new Options();
    options.addOption("p", "projecthelp", false, "print project help information");
    options.addOption("f", "file", true, "use given buildfile");
    options.addOption("h", "help", false, "print this message");
    options.addOption("d", "debug", false, "print debugging information");
    options.addOption("v", "verbose", false, "be extra verbose");
    options.addOption("q", "quiet", false, "be extra quiet");

    CommandLine cli;//from  w ww  . ja v  a  2s .co m
    try {
        cli = new GnuParser().parse(options, args);
    } catch (ParseException e) {
        System.out.println("Error: " + e.getMessage());
        new HelpFormatter().printHelp(CLI_SYNTAX, options);
        return;
    }

    String scriptName = cli.getOptionValue("f", "build.js");
    if (cli.hasOption("h")) {
        new HelpFormatter().printHelp(CLI_SYNTAX, options);
        return;
    } else if (cli.hasOption("p")) {
        runScript(scriptName, "projecthelp", null);
    } else {
        runScript(scriptName, "build", cli);
    }
}

From source file:com.notifier.desktop.Main.java

public static void main(String[] args) {
    Options options = createCommandLineOptions();
    try {/*w ww .j av a 2s . co m*/
        CommandLineParser commandLineParser = new GnuParser();
        CommandLine line = commandLineParser.parse(options, args);

        if (line.getOptions().length > 1) {
            showMessage("Only one parameter may be specified");
        }
        if (line.getArgs().length > 0) {
            showMessage("Non-recognized parameters: " + Arrays.toString(line.getArgs()));
        }
        if (line.hasOption(HELP_SHORT)) {
            printHelp(options);
            return;
        }
        if (line.hasOption(IS_RUNNING_SHORT)) {
            ServiceClient client = new ServiceClientImpl();
            if (client.isRunning()) {
                showMessage(Application.NAME + " is running");
            } else {
                showMessage(Application.NAME + " is not running");
            }
            return;
        }
        if (line.hasOption(STOP_SHORT)) {
            ServiceClient client = new ServiceClientImpl();
            if (client.stop()) {
                showMessage("Sent stop signal to " + Application.NAME + " successfully");
            } else {
                showMessage(Application.NAME + " is not running or an error occurred, see log for details");
            }
            return;
        }

        boolean trayIcon = !line.hasOption(NO_TRAY_SHORT);
        boolean showPreferences = line.hasOption(SHOW_PREFERENCES_SHORT);

        if (!getExclusiveExecutionLock()) {
            showMessage("There can be only one instance of " + Application.NAME + " running at a time");
            return;
        }
        Injector injector = Guice.createInjector(Stage.PRODUCTION, new ApplicationModule());
        Application application = injector.getInstance(Application.class);
        application.start(trayIcon, showPreferences);
    } catch (Throwable t) {
        System.out.println(t.getMessage());
        logger.error("Error starting", t);
    }
}

From source file:com.rapleaf.hank.cli.AddRing.java

public static void main(String[] args) throws Exception {
    Options options = new Options();
    options.addOption("r", "ring-group", true, "the name of the ring group");
    options.addOption("n", "ring-number", true, "the number of the new ring you are creating");
    options.addOption("h", "hosts", true, "a comma-separated list of host:port pairs");
    options.addOption("c", "config", true,
            "path of a valid config file with coordinator connection information");
    try {//from  w ww  .j  av  a  2  s .  c o  m
        CommandLine line = new GnuParser().parse(options, args);
        CommandLineChecker.check(line, options, new String[] { "config", "ring-group", "ring-number" },
                AddRing.class);
        ClientConfigurator configurator = new YamlClientConfigurator(line.getOptionValue("config"));
        addRing(configurator, line.getOptionValue("ring-group"),
                Integer.parseInt(line.getOptionValue("ring-number")), line.getOptionValue("hosts"));
    } catch (ParseException e) {
        new HelpFormatter().printHelp("add_domain", options);
        throw e;
    }
}

From source file:com.ctriposs.rest4j.tools.data.FilterSchemaGenerator.java

public static void main(String[] args) {
    final CommandLineParser parser = new GnuParser();
    CommandLine cl = null;//from  w ww  . ja  v  a 2 s .  c o  m
    try {
        cl = parser.parse(_options, args);
    } catch (ParseException e) {
        _log.error("Invalid arguments: " + e.getMessage());
        reportInvalidArguments();
    }

    final String[] directoryArgs = cl.getArgs();
    if (directoryArgs.length != 2) {
        reportInvalidArguments();
    }

    final File sourceDirectory = new File(directoryArgs[0]);
    if (!sourceDirectory.exists()) {
        _log.error(sourceDirectory.getPath() + " does not exist");
        System.exit(1);
    }
    if (!sourceDirectory.isDirectory()) {
        _log.error(sourceDirectory.getPath() + " is not a directory");
        System.exit(1);
    }
    final URI sourceDirectoryURI = sourceDirectory.toURI();

    final File outputDirectory = new File(directoryArgs[1]);
    if (outputDirectory.exists() && !sourceDirectory.isDirectory()) {
        _log.error(outputDirectory.getPath() + " is not a directory");
        System.exit(1);
    }

    final boolean isAvroMode = cl.hasOption('a');
    final String predicateExpression = cl.getOptionValue('e');
    final Predicate predicate = PredicateExpressionParser.parse(predicateExpression);

    final Collection<File> sourceFiles = FileUtil.listFiles(sourceDirectory, null);
    int exitCode = 0;
    for (File sourceFile : sourceFiles) {
        try {
            final ValidationOptions val = new ValidationOptions();
            val.setAvroUnionMode(isAvroMode);

            final SchemaParser schemaParser = new SchemaParser();
            schemaParser.setValidationOptions(val);

            schemaParser.parse(new FileInputStream(sourceFile));
            if (schemaParser.hasError()) {
                _log.error("Error parsing " + sourceFile.getPath() + ": "
                        + schemaParser.errorMessageBuilder().toString());
                exitCode = 1;
                continue;
            }

            final DataSchema originalSchema = schemaParser.topLevelDataSchemas().get(0);
            if (!(originalSchema instanceof NamedDataSchema)) {
                _log.error(sourceFile.getPath() + " does not contain valid NamedDataSchema");
                exitCode = 1;
                continue;
            }

            final SchemaParser filterParser = new SchemaParser();
            filterParser.setValidationOptions(val);

            final NamedDataSchema filteredSchema = Filters.removeByPredicate((NamedDataSchema) originalSchema,
                    predicate, filterParser);
            if (filterParser.hasError()) {
                _log.error("Error applying predicate: " + filterParser.errorMessageBuilder().toString());
                exitCode = 1;
                continue;
            }

            final String relativePath = sourceDirectoryURI.relativize(sourceFile.toURI()).getPath();
            final String outputFilePath = outputDirectory.getPath() + File.separator + relativePath;
            final File outputFile = new File(outputFilePath);
            final File outputFileParent = outputFile.getParentFile();
            outputFileParent.mkdirs();
            if (!outputFileParent.exists()) {
                _log.error("Unable to write filtered schema to " + outputFileParent.getPath());
                exitCode = 1;
                continue;
            }

            FileOutputStream fout = new FileOutputStream(outputFile);
            fout.write(filteredSchema.toString().getBytes(RestConstants.DEFAULT_CHARSET));
            fout.close();
        } catch (IOException e) {
            _log.error(e.getMessage());
            exitCode = 1;
        }
    }

    System.exit(exitCode);
}

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

/**
 * @param args//from w w  w.  j  a v  a  2 s.  c  o  m
 */
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:net.anthonypoon.ngram.correlation.Main.java

public static void main(String[] args) throws Exception {
    Options options = new Options();
    options.addOption("a", "action", true, "Action");
    options.addOption("i", "input", true, "input");
    options.addOption("o", "output", true, "output");
    //options.addOption("f", "format", true, "Format");
    options.addOption("u", "upbound", true, "Year up bound");
    options.addOption("l", "lowbound", true, "Year low bound");
    options.addOption("t", "target", true, "Correlation Target URI"); // Can only take file from S# or HDFS
    options.addOption("L", "lag", true, "Lag factor");
    options.addOption("T", "threshold", true, "Correlation threshold");
    CommandLineParser parser = new GnuParser();
    CommandLine cmd = parser.parse(options, args);
    Configuration conf = new Configuration();
    if (cmd.hasOption("lag")) {
        conf.set("lag", cmd.getOptionValue("lag"));
    }//from   w ww . j  a  v a 2  s.  c o  m
    if (cmd.hasOption("threshold")) {
        conf.set("threshold", cmd.getOptionValue("threshold"));
    }
    if (cmd.hasOption("upbound")) {
        conf.set("upbound", cmd.getOptionValue("upbound"));
    } else {
        conf.set("upbound", "9999");
    }
    if (cmd.hasOption("lowbound")) {
        conf.set("lowbound", cmd.getOptionValue("lowbound"));
    } else {
        conf.set("lowbound", "0");
    }
    if (cmd.hasOption("target")) {
        conf.set("target", cmd.getOptionValue("target"));
    } else {
        throw new Exception("Missing correlation target file uri");
    }
    Job job = Job.getInstance(conf);
    /**
    if (cmd.hasOption("format")) {
    switch (cmd.getOptionValue("format")) {
        case "compressed":
            job.setInputFormatClass(SequenceFileAsTextInputFormat.class);
            break;
        case "text":
            job.setInputFormatClass(KeyValueTextInputFormat.class);
            break;
    }
            
    }**/
    job.setJarByClass(Main.class);
    switch (cmd.getOptionValue("action")) {
    case "get-correlation":
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(Text.class);
        for (String inputPath : cmd.getOptionValue("input").split(",")) {
            MultipleInputs.addInputPath(job, new Path(inputPath), KeyValueTextInputFormat.class,
                    CorrelationMapper.class);
        }
        job.setReducerClass(CorrelationReducer.class);
        break;
    default:
        throw new IllegalArgumentException("Missing action");
    }

    String timestamp = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss").format(new Date());

    //FileInputFormat.setInputPaths(job, new Path(cmd.getOptionValue("input")));
    FileOutputFormat.setOutputPath(job, new Path(cmd.getOptionValue("output") + "/" + timestamp));
    System.exit(job.waitForCompletion(true) ? 0 : 1);
}