Example usage for org.apache.commons.cli Options addOption

List of usage examples for org.apache.commons.cli Options addOption

Introduction

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

Prototype

public Options addOption(String opt, String longOpt, boolean hasArg, String description) 

Source Link

Document

Add an option that contains a short-name and a long-name.

Usage

From source file:edu.cmu.lti.oaqa.bio.index.medline.annotated.query.SimpleQueryApp.java

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

    options.addOption("u", null, true, "Solr URI");
    options.addOption("n", null, true, "Max # of results");

    CommandLineParser parser = new org.apache.commons.cli.GnuParser();

    try {//from  www .  j a  va  2 s .c o m
        CommandLine cmd = parser.parse(options, args);
        String solrURI = null;

        solrURI = cmd.getOptionValue("u");
        if (solrURI == null) {
            Usage("Specify Solr URI");
        }

        SolrServerWrapper solr = new SolrServerWrapper(solrURI);

        int numRet = 10;

        if (cmd.hasOption("n")) {
            numRet = Integer.parseInt(cmd.getOptionValue("n"));
        }

        List<String> fieldList = new ArrayList<String>();
        fieldList.add(UtilConstMedline.ID_FIELD);
        fieldList.add(UtilConstMedline.SCORE_FIELD);
        fieldList.add(UtilConstMedline.ARTICLE_TITLE_FIELD);
        fieldList.add(UtilConstMedline.ENTITIES_DESC_FIELD);
        fieldList.add(UtilConstMedline.ABSTRACT_TEXT_FIELD);

        BufferedReader sysInReader = new BufferedReader(new InputStreamReader(System.in));
        Joiner commaJoiner = Joiner.on(',');

        while (true) {
            System.out.println("Input query: ");
            String query = sysInReader.readLine();
            if (null == query)
                break;

            QueryTransformer qt = new QueryTransformer(query);

            String tranQuery = qt.getQuery();

            System.out.println("Translated query:");
            System.out.println(tranQuery);
            System.out.println("=========================");

            SolrDocumentList res = solr.runQuery(tranQuery, fieldList, numRet);

            System.out.println("Found " + res.getNumFound() + " entries");

            for (SolrDocument doc : res) {
                String id = (String) doc.getFieldValue(UtilConstMedline.ID_FIELD);
                float score = (Float) doc.getFieldValue(UtilConstMedline.SCORE_FIELD);
                String title = (String) doc.getFieldValue(UtilConstMedline.ARTICLE_TITLE_FIELD);
                String titleAbstract = (String) doc.getFieldValue(UtilConstMedline.ABSTRACT_TEXT_FIELD);

                System.out.println(score + " PMID=" + id + " " + titleAbstract);

                String entityDesc = (String) doc.getFieldValue(UtilConstMedline.ENTITIES_DESC_FIELD);
                System.out.println("Entities:");
                for (EntityEntry e : EntityEntry.parseEntityDesc(entityDesc)) {
                    System.out.println(String.format("[%d %d] concept=%s concept_ids=%s", e.mStart, e.mEnd,
                            e.mConcept, commaJoiner.join(e.mConceptIds)));
                }
            }
        }

        solr.close();

    } catch (ParseException e) {
        Usage("Cannot parse arguments");
    } catch (Exception e) {
        System.err.println("Terminating due to an exception: " + e);
        System.exit(1);
    }
}

From source file:com.thoughtworks.xstream.tools.benchmark.parsers.ParserBenchmark.java

public static void main(String[] args) {
    int counter = 1000;

    Options options = new Options();
    options.addOption("p", "product", true, "Class name of the product to use for benchmark");
    options.addOption("n", true, "Number of repetitions");

    Harness harness = new Harness();
    harness.addMetric(new DeserializationSpeedMetric(0, false) {
        public String toString() {
            return "Initial run deserialization";
        }//from w  w w .j  a  v a  2  s  .  com
    });

    Parser parser = new PosixParser();
    try {
        CommandLine commandLine = parser.parse(options, args);
        String name = null;
        if (commandLine.hasOption('p')) {
            name = commandLine.getOptionValue('p');
        }
        if (name == null || name.equals("DOM")) {
            harness.addProduct(new XStreamDom());
        }
        if (name == null || name.equals("JDOM")) {
            harness.addProduct(new XStreamJDom());
        }
        if (name == null || name.equals("DOM4J")) {
            harness.addProduct(new XStreamDom4J());
        }
        if (name == null || name.equals("XOM")) {
            harness.addProduct(new XStreamXom());
        }
        if (name == null || name.equals("BEAStAX")) {
            harness.addProduct(new XStreamBEAStax());
        }
        if (name == null || name.equals("Woodstox")) {
            harness.addProduct(new XStreamWoodstox());
        }
        if (JVM.is16() && (name == null || name.equals("SJSXP"))) {
            harness.addProduct(new XStreamSjsxp());
        }
        if (name == null || name.equals("Xpp3")) {
            harness.addProduct(new XStreamXpp3());
        }
        if (name == null || name.equals("kXML2")) {
            harness.addProduct(new XStreamKXml2());
        }
        if (name == null || name.equals("Xpp3DOM")) {
            harness.addProduct(new XStreamXpp3DOM());
        }
        if (name == null || name.equals("kXML2DOM")) {
            harness.addProduct(new XStreamKXml2DOM());
        }
        if (commandLine.hasOption('n')) {
            counter = Integer.parseInt(commandLine.getOptionValue('n'));
        }
    } catch (ParseException e) {
        e.printStackTrace();
    }

    harness.addMetric(new DeserializationSpeedMetric(counter, false));
    harness.addTarget(new BasicTarget());
    harness.addTarget(new ExtendedTarget());
    harness.addTarget(new ReflectionTarget());
    harness.addTarget(new SerializableTarget());
    harness.addTarget(new JavaBeanTarget());
    if (false) {
        harness.addTarget(new FieldReflection());
        harness.addTarget(new HierarchyLevelReflection());
        harness.addTarget(new InnerClassesReflection());
        harness.addTarget(new StaticInnerClassesReflection());
    }
    harness.run(new TextReporter(new PrintWriter(System.out, true)));
    System.out.println("Done.");
}

From source file:gr.demokritos.iit.demos.Demo.java

public static void main(String[] args) {
    try {//from  w w  w . j  a  v a2 s  .c  o  m
        Options options = new Options();
        options.addOption("h", HELP, false, "show help.");
        options.addOption("i", INPUT, true,
                "The file containing JSON " + " representations of tweets or SAG posts - 1 per line"
                        + " default file looked for is " + DEFAULT_INFILE);
        options.addOption("o", OUTPUT, true,
                "Where to write the output " + " default file looked for is " + DEFAULT_OUTFILE);
        options.addOption("p", PROCESS, true, "Type of processing to do "
                + " ner for Named Entity Recognition re for Relation Extraction" + " default is NER");
        options.addOption("s", SAG, false,
                "Whether to process as SAG posts" + " default is off - if passed means process as SAG posts");

        CommandLineParser parser = new BasicParser();
        CommandLine cmd = parser.parse(options, args);
        // DEFAULTS
        String filename = DEFAULT_INFILE;
        String outfilename = DEFAULT_OUTFILE;
        String process = NER;
        boolean isSAG = false;

        if (cmd.hasOption(HELP)) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("NER + RE extraction module", options);
            System.exit(0);
        }
        if (cmd.hasOption(INPUT)) {
            filename = cmd.getOptionValue(INPUT);
        }
        if (cmd.hasOption(OUTPUT)) {
            outfilename = cmd.getOptionValue(OUTPUT);
        }
        if (cmd.hasOption(SAG)) {
            isSAG = true;
        }
        if (cmd.hasOption(PROCESS)) {
            process = cmd.getOptionValue(PROCESS);
        }
        System.out.println();
        System.out.println("Reading from file: " + filename);
        System.out.println("Process type: " + process);
        System.out.println("Processing SAG: " + isSAG);
        System.out.println("Writing to file: " + outfilename);
        System.out.println();

        List<String> jsoni = new ArrayList();
        Scanner in = new Scanner(new FileReader(filename));
        while (in.hasNextLine()) {
            String json = in.nextLine();
            jsoni.add(json);
        }
        PrintWriter writer = new PrintWriter(outfilename, "UTF-8");
        System.out.println("Read " + jsoni.size() + " lines from " + filename);
        if (process.equalsIgnoreCase(RE)) {
            System.out.println("Running Relation Extraction");
            System.out.println();
            String json = API.RE(jsoni, isSAG);
            System.out.println(json);
            writer.print(json);
        } else {
            System.out.println("Running Named Entity Recognition");
            System.out.println();
            jsoni = API.NER(jsoni, isSAG);
            /*
            for(String json: jsoni){
               NamedEntityList nel = NamedEntityList.fromJSON(json);
               nel.prettyPrint();
            }
            */
            for (String json : jsoni) {
                System.out.println(json);
                writer.print(json);
            }
        }
        writer.close();
    } catch (ParseException | UnsupportedEncodingException | FileNotFoundException ex) {
        Logger.getLogger(Demo.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:it.tizianofagni.sparkboost.AdaBoostMHLearnerExe.java

public static void main(String[] args) {
    Options options = new Options();
    options.addOption("b", "binaryProblem", false,
            "Indicate if the input dataset contains a binary problem and not a multilabel one");
    options.addOption("z", "labels0based", false,
            "Indicate if the labels IDs in the dataset to classifyLibSvmWithResults are already assigned in the range [0, numLabels-1] included");
    options.addOption("l", "enableSparkLogging", false, "Enable logging messages of Spark");
    options.addOption("w", "windowsLocalModeFix", true,
            "Set the directory containing the winutils.exe command");
    options.addOption("dp", "documentPartitions", true, "The number of document partitions");
    options.addOption("fp", "featurePartitions", true, "The number of feature partitions");
    options.addOption("lp", "labelPartitions", true, "The number of label partitions");

    CommandLineParser parser = new BasicParser();
    CommandLine cmd = null;/*from w w w . j  a va 2 s .  co m*/
    String[] remainingArgs = null;
    try {
        cmd = parser.parse(options, args);
        remainingArgs = cmd.getArgs();
        if (remainingArgs.length != 5)
            throw new ParseException("You need to specify all mandatory parameters");
    } catch (ParseException e) {
        System.out.println("Parsing failed.  Reason: " + e.getMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(AdaBoostMHLearnerExe.class.getSimpleName()
                + " [OPTIONS] <inputFile> <outputFile> <numIterations> <sparkMaster> <parallelismDegree>",
                options);
        System.exit(-1);
    }

    boolean binaryProblem = false;
    if (cmd.hasOption("b"))
        binaryProblem = true;
    boolean labels0Based = false;
    if (cmd.hasOption("z"))
        labels0Based = true;
    boolean enablingSparkLogging = false;
    if (cmd.hasOption("l"))
        enablingSparkLogging = true;

    if (cmd.hasOption("w")) {
        System.setProperty("hadoop.home.dir", cmd.getOptionValue("w"));
    }

    String inputFile = remainingArgs[0];
    String outputFile = remainingArgs[1];
    int numIterations = Integer.parseInt(remainingArgs[2]);
    String sparkMaster = remainingArgs[3];
    int parallelismDegree = Integer.parseInt(remainingArgs[4]);

    long startTime = System.currentTimeMillis();

    // Disable Spark logging.
    if (!enablingSparkLogging) {
        Logger.getLogger("org").setLevel(Level.OFF);
        Logger.getLogger("akka").setLevel(Level.OFF);
    }

    // Create and configure Spark context.
    SparkConf conf = new SparkConf().setAppName("Spark AdaBoost.MH learner");
    JavaSparkContext sc = new JavaSparkContext(conf);

    // Create and configure learner.
    AdaBoostMHLearner learner = new AdaBoostMHLearner(sc);
    learner.setNumIterations(numIterations);

    if (cmd.hasOption("dp")) {
        learner.setNumDocumentsPartitions(Integer.parseInt(cmd.getOptionValue("dp")));
    }
    if (cmd.hasOption("fp")) {
        learner.setNumFeaturesPartitions(Integer.parseInt(cmd.getOptionValue("fp")));
    }
    if (cmd.hasOption("lp")) {
        learner.setNumLabelsPartitions(Integer.parseInt(cmd.getOptionValue("lp")));
    }

    // Build classifier with MPBoost learner.
    BoostClassifier classifier = learner.buildModel(inputFile, labels0Based, binaryProblem);

    // Save classifier to disk.
    DataUtils.saveModel(sc, classifier, outputFile);

    long endTime = System.currentTimeMillis();
    System.out.println("Execution time: " + (endTime - startTime) + " milliseconds.");
}

From source file:cnxchecker.Server.java

public static void main(String[] args) {
    Options options = new Options();
    options.addOption("p", "port", true, "TCP port to bind to (random by default)");
    options.addOption("h", "help", false, "Print help");

    CommandLineParser parser = new GnuParser();
    try {/* w w w  . j  av  a  2 s .  co  m*/
        CommandLine cmd = parser.parse(options, args);

        if (cmd.hasOption("h")) {
            HelpFormatter hf = new HelpFormatter();
            hf.printHelp("server", options);
            System.exit(0);
        }

        int port = 0;
        if (cmd.hasOption("p")) {
            try {
                port = Integer.parseInt(cmd.getOptionValue("p"));
            } catch (NumberFormatException e) {
                printAndExit("Invalid port number " + cmd.getOptionValue("p"));
            }

            if (port < 0 || port > 65535) {
                printAndExit("Invalid port number " + port);
            }
        }

        Server server = new Server(port);
        server.doit();
    } catch (ParseException e) {
        printAndExit("Failed to parse options: " + e.getMessage());
    }
}

From source file:dhtaccess.tools.Remove.java

public static void main(String[] args) {
    int ttl = 3600;

    // parse properties
    Properties prop = System.getProperties();
    String gateway = prop.getProperty("dhtaccess.gateway");
    if (gateway == null || gateway.length() <= 0) {
        gateway = DEFAULT_GATEWAY;//from  www .  j  a va 2s  . c o  m
    }

    // parse options
    Options options = new Options();
    options.addOption("h", "help", false, "print help");
    options.addOption("g", "gateway", true, "gateway URI, list at http://opendht.org/servers.txt");
    options.addOption("t", "ttl", true, "how long (in seconds) to store the value");

    CommandLineParser parser = new PosixParser();
    CommandLine cmd = null;
    try {
        cmd = parser.parse(options, args);
    } catch (ParseException e) {
        System.out.println("There is an invalid option.");
        e.printStackTrace();
        System.exit(1);
    }

    String optVal;
    if (cmd.hasOption('h')) {
        usage(COMMAND);
        System.exit(1);
    }
    optVal = cmd.getOptionValue('g');
    if (optVal != null) {
        gateway = optVal;
    }
    optVal = cmd.getOptionValue('t');
    if (optVal != null) {
        ttl = Integer.parseInt(optVal);
    }

    args = cmd.getArgs();

    // parse arguments
    if (args.length < 3) {
        usage(COMMAND);
        System.exit(1);
    }

    byte[] key = null, value = null, secret = null;
    try {
        key = args[0].getBytes(ENCODE);
        value = args[1].getBytes(ENCODE);
        secret = args[2].getBytes(ENCODE);
    } catch (UnsupportedEncodingException e1) {
        // NOTREACHED
    }

    // prepare for RPC
    DHTAccessor accessor = null;
    try {
        accessor = new DHTAccessor(gateway);
    } catch (MalformedURLException e) {
        e.printStackTrace();
        System.exit(1);
    }

    // RPC
    int res = accessor.remove(key, value, ttl, secret);

    String resultString;
    switch (res) {
    case 0:
        resultString = "Success";
        break;
    case 1:
        resultString = "Capacity";
        break;
    case 2:
        resultString = "Again";
        break;
    default:
        resultString = "???";
    }
    System.out.println(resultString);
}

From source file:com.spotify.cassandra.opstools.autobalance.Main.java

public static void main(String[] args) throws IOException, InterruptedException, ParseException {
    final Options options = new Options();
    options.addOption("f", "force", false, "Force auto balance");
    options.addOption("d", "dryrun", false, "Dry run");
    options.addOption("r", "noresolve", false, "Don't resolve host names");
    options.addOption("h", "host", true, "Host to connect to (default: localhost)");
    options.addOption("p", "port", true, "Port to connect to (default: 7199)");

    CommandLineParser parser = new BasicParser();
    CommandLine cmd = parser.parse(options, args);
    new Main().run(cmd);
}

From source file:com.zimbra.common.util.RandomPassword.java

public static void main(String args[]) {
    CommandLineParser parser = new GnuParser();
    Options options = new Options();
    options.addOption("l", "localpart", false, "generated string does not contain dot(.)");

    CommandLine cl = null;/*from   w  w  w.jav  a 2 s .  com*/
    boolean err = false;

    try {
        cl = parser.parse(options, args, true);
    } catch (ParseException pe) {
        System.err.println("error: " + pe.getMessage());
        err = true;
    }

    if (err || cl.hasOption('h')) {
        usage();
    }

    boolean localpart = false;
    int minLength = DEFAULT_MIN_LENGTH;
    int maxLength = DEFAULT_MAX_LENGTH;

    if (cl.hasOption('l'))
        localpart = true;

    args = cl.getArgs();

    if (args.length != 0) {
        if (args.length != 2) {
            usage();
        }
        try {
            minLength = Integer.valueOf(args[0]).intValue();
            maxLength = Integer.valueOf(args[1]).intValue();
        } catch (Exception e) {
            System.err.println(e);
            e.printStackTrace();
        }
    }

    System.out.println(generate(minLength, maxLength, localpart));
}

From source file:de.peregrinus.autocopyreport.AutoCopyReport.java

public static void main(String[] args) {
    SongInfo si;/*  w w w  .  ja  va 2s.c om*/

    String openlpPath = "";
    String crPath = "";
    String crDataPath = "";
    String crPassword = "";

    System.out.println("AutoCopyReport v.1.00.00");
    System.out.println("(c) 2014 Volksmission Freudenstadt");
    System.out.println("Author: Christoph Fischer <christoph.fischer@volksmission.de>");
    //System.out.println("Available under the General Public License (GPL) v2");
    System.out.println();

    // get options
    Options options = new Options();
    options.addOption("h", "help", false, "display a list of available options");
    options.addOption(OptionBuilder.withLongOpt("openlp-path").withDescription("path to OpenLP data directory")
            .hasArg().withArgName("PATH").create());
    options.addOption(OptionBuilder.withLongOpt("copyreport-path")
            .withDescription("path to the CopyReport program directory").hasArg().withArgName("PATH").create());
    options.addOption(OptionBuilder.withLongOpt("copyreport-data-path")
            .withDescription("path to the CopyReport data directory").hasArg().withArgName("PATH").create());
    options.addOption(OptionBuilder.withLongOpt("password")
            .withDescription("internal password for the CopyReport database").hasArg().withArgName("PASSWORD")
            .create());

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

        // validate that block-size has been set
        if (line.hasOption("help")) {
            // automatically generate the help statement
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("AutoCopyReport", options);
            System.exit(0);
        } else {
            if (line.hasOption("openlp-path")) {
                openlpPath = line.getOptionValue("openlp-path") + "/songs/songs.sqlite";
                System.out.println("OpenLP data path: " + openlpPath);
            } else {
                System.out.println(
                        "ERROR: Please supply the path to your OpenLP data folder by using the --openlp-path parameter.");
                System.exit(0);
            }
            if (line.hasOption("copyreport-path")) {
                crPath = line.getOptionValue("copyreport-path");
                System.out.println("Copyreport application database: " + crPath + "/ccldata.h2.db");
            } else {
                System.out.println(
                        "ERROR: Please supply the path to your CopyReport program folder by using the --copyreport-path parameter.");
                System.exit(0);
            }
            if (line.hasOption("copyreport-data-path")) {
                crDataPath = line.getOptionValue("copyreport-data-path");
                System.out.println("Copyreport user database: " + crDataPath + "/userdata.h2.db");
            } else {
                System.out.println(
                        "ERROR: Please supply the path to your CopyReport data folder by using the --copyreport-data-path parameter.");
                System.exit(0);
            }
            if (line.hasOption("password")) {
                crPassword = line.getOptionValue("password");
            } else {
                System.out.println(
                        "ERROR: Please supply the internal password for the CopyReport database by using the --password parameter.");
                System.exit(0);
            }
        }
    } catch (ParseException exp) {
        System.out.println("Unexpected exception:" + exp.getMessage());
        System.exit(0);
    }

    SongDatabaseConnector sdb = new SongDatabaseConnector(openlpPath);
    SongRepository cdb = new SongRepository(crPath + "/ccldata", "sa", crPassword);

    CopyReport rpt = new CopyReport(crDataPath + "/userdata", "sa", crPassword);
    //rpt.createPeriod("2014");

    List<Song> songs = sdb.findLicensedSongs();
    for (Song song : songs) {
        System.out.println(song.title + ": " + song.ccliNumber);
        if (song.ccliNumber.matches("-?\\d+(\\.\\d+)?")) {
            si = cdb.findById(song.ccliNumber);
            if (si != null)
                rpt.reportSong(si);
        } else {
            System.out.println("Format error: '" + song.ccliNumber + "' is not numeric.");
        }
    }

    // wrap up: close the databases
    cdb.close();
    rpt.close();
    sdb.close();

}

From source file:metaTile.Main.java

/**
 * @param args//ww w . j  a va  2s  .c  o  m
 * @throws IOException 
 */
public static void main(String[] args) throws IOException {
    try {
        /* parse the command line arguments */
        // create the command line parser
        CommandLineParser parser = new PosixParser();

        // create the Options
        Options options = new Options();
        options.addOption("i", "input", true, "File to read original tile list from.");
        options.addOption("o", "output", true, "File to write shorter meta-tile list to.");
        options.addOption("m", "metatiles", true,
                "Number of tiles in x and y direction to group into one meta-tile.");

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

        if (!commandLine.hasOption("input") || !commandLine.hasOption("output")
                || !commandLine.hasOption("metatiles"))
            printUsage(options);

        String inputFileName = commandLine.getOptionValue("input");
        String outputFileName = commandLine.getOptionValue("output");
        int metaTileSize = Integer.parseInt(commandLine.getOptionValue("metatiles"));

        ArrayList<RenderingTile> tiles = new ArrayList<RenderingTile>();

        BufferedReader tileListReader = new BufferedReader(new FileReader(new File(inputFileName)));

        BufferedWriter renderMetatileListWriter = new BufferedWriter(new FileWriter(new File(outputFileName)));

        String line = tileListReader.readLine();
        while (line != null) {
            String[] columns = line.split("/");

            if (columns.length == 3)
                tiles.add(new RenderingTile(Integer.parseInt(columns[0]), Integer.parseInt(columns[1]),
                        Integer.parseInt(columns[2])));

            line = tileListReader.readLine();
        }

        tileListReader.close();

        int hits = 0;

        // tiles which we are already rendering as the top left corner of 4x4 metatiles
        HashSet<RenderingTile> whitelist = new HashSet<RenderingTile>();

        // for each tile in the list see if it has a meta-tile in the whitelist already
        for (int i = 0; i < tiles.size(); i++) {
            boolean hit = false; // by default we aren't already rendering this tile as part of another metatile
            for (int dx = 0; dx < metaTileSize; dx++) {
                for (int dy = 0; dy < metaTileSize; dy++) {
                    RenderingTile candidate = new RenderingTile(tiles.get(i).z, tiles.get(i).x - dx,
                            tiles.get(i).y - dy);
                    if (whitelist.contains(candidate)) {
                        hit = true;
                        // now exit the two for loops iterating over tiles inside a meta-tile
                        dx = metaTileSize;
                        dy = metaTileSize;
                    }
                }
            }

            // if this tile doesn't already have a meta-tile in the whitelist, add it
            if (hit == false) {
                hits++;
                renderMetatileListWriter.write(tiles.get(i).toString() + "/" + metaTileSize + "\n");
                whitelist.add(tiles.get(i));
            }
        }
        renderMetatileListWriter.close();
        System.out.println(
                "Reduced " + tiles.size() + " tiles into " + hits + " metatiles of size " + metaTileSize);
    } catch (Exception e) {
        e.printStackTrace();
    }
}