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:cc.twittertools.search.api.SearchStatusesThrift.java

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

    options.addOption(new Option(HELP_OPTION, "show help"));
    options.addOption(OptionBuilder.withArgName("string").hasArg().withDescription("host").create(HOST_OPTION));
    options.addOption(OptionBuilder.withArgName("port").hasArg().withDescription("port").create(PORT_OPTION));
    options.addOption(//from   ww w .j  a v a 2s.  c  o m
            OptionBuilder.withArgName("string").hasArg().withDescription("query id").create(QID_OPTION));
    options.addOption(
            OptionBuilder.withArgName("string").hasArg().withDescription("query text").create(QUERY_OPTION));
    options.addOption(
            OptionBuilder.withArgName("string").hasArg().withDescription("runtag").create(RUNTAG_OPTION));
    options.addOption(OptionBuilder.withArgName("num").hasArg().withDescription("maxid").create(MAX_ID_OPTION));
    options.addOption(OptionBuilder.withArgName("num").hasArg().withDescription("number of results to return")
            .create(NUM_RESULTS_OPTION));
    options.addOption(
            OptionBuilder.withArgName("string").hasArg().withDescription("group id").create(GROUP_OPTION));
    options.addOption(
            OptionBuilder.withArgName("string").hasArg().withDescription("access token").create(TOKEN_OPTION));
    options.addOption(new Option(VERBOSE_OPTION, "print out complete document"));

    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(HELP_OPTION) || !cmdline.hasOption(HOST_OPTION) || !cmdline.hasOption(PORT_OPTION)) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(SearchStatusesThrift.class.getName(), options);
        System.exit(-1);
    }

    String qid = cmdline.hasOption(QID_OPTION) ? cmdline.getOptionValue(QID_OPTION) : DEFAULT_QID;
    String query = cmdline.hasOption(QUERY_OPTION) ? cmdline.getOptionValue(QUERY_OPTION) : DEFAULT_Q;
    String runtag = cmdline.hasOption(RUNTAG_OPTION) ? cmdline.getOptionValue(RUNTAG_OPTION) : DEFAULT_RUNTAG;
    long maxId = cmdline.hasOption(MAX_ID_OPTION) ? Long.parseLong(cmdline.getOptionValue(MAX_ID_OPTION))
            : DEFAULT_MAX_ID;
    int numResults = cmdline.hasOption(NUM_RESULTS_OPTION)
            ? Integer.parseInt(cmdline.getOptionValue(NUM_RESULTS_OPTION))
            : DEFAULT_NUM_RESULTS;
    boolean verbose = cmdline.hasOption(VERBOSE_OPTION);

    String group = cmdline.hasOption(GROUP_OPTION) ? cmdline.getOptionValue(GROUP_OPTION) : null;
    String token = cmdline.hasOption(TOKEN_OPTION) ? cmdline.getOptionValue(TOKEN_OPTION) : null;
    TrecSearchThriftClient client = new TrecSearchThriftClient(cmdline.getOptionValue(HOST_OPTION),
            Integer.parseInt(cmdline.getOptionValue(PORT_OPTION)), group, token);

    System.err.println("qid: " + qid);
    System.err.println("q: " + query);
    System.err.println("max_id: " + maxId);
    System.err.println("num_results: " + numResults);

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

    List<TResult> results = client.search(query, maxId, numResults);
    int i = 1;
    for (TResult result : results) {
        out.println(String.format("%s Q0 %d %d %f %s", qid, result.id, i, result.rsv, runtag));
        if (verbose) {
            System.out.println("# " + result.toString().replaceAll("[\\n\\r]+", " "));
        }
        i++;
    }
    out.close();
}

From source file:cc.twittertools.search.api.TrecSearchThriftServer.java

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

    options.addOption(new Option(HELP_OPTION, "show help"));
    options.addOption(OptionBuilder.withArgName("port").hasArg().withDescription("port").create(PORT_OPTION));
    options.addOption(/*  w ww . j a  v  a2s.  co  m*/
            OptionBuilder.withArgName("index").hasArg().withDescription("index location").create(INDEX_OPTION));
    options.addOption(OptionBuilder.withArgName("num").hasArg()
            .withDescription("max number of threads in thread pool").create(MAX_THREADS_OPTION));
    options.addOption(OptionBuilder.withArgName("file").hasArg()
            .withDescription("file containing access tokens").create(CREDENTIALS_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(HELP_OPTION) || !cmdline.hasOption(INDEX_OPTION)) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(TrecSearchThriftServer.class.getName(), options);
        System.exit(-1);
    }

    int port = cmdline.hasOption(PORT_OPTION) ? Integer.parseInt(cmdline.getOptionValue(PORT_OPTION))
            : DEFAULT_PORT;
    int maxThreads = cmdline.hasOption(MAX_THREADS_OPTION)
            ? Integer.parseInt(cmdline.getOptionValue(MAX_THREADS_OPTION))
            : DEFAULT_MAX_THREADS;
    File index = new File(cmdline.getOptionValue(INDEX_OPTION));

    Map<String, String> credentials = null;
    if (cmdline.hasOption(CREDENTIALS_OPTION)) {
        credentials = Maps.newHashMap();
        File cfile = new File(cmdline.getOptionValue(CREDENTIALS_OPTION));
        if (!cfile.exists()) {
            System.err.println("Error: " + cfile + " does not exist!");
            System.exit(-1);
        }
        for (String s : Files.readLines(cfile, Charsets.UTF_8)) {
            try {
                String[] arr = s.split(":");
                credentials.put(arr[0], arr[1]);
            } catch (Exception e) {
                // Catch any exceptions from parsing file contain access tokens
                System.err.println("Error reading access tokens from " + cfile + "!");
                System.exit(-1);
            }
        }
    }

    if (!index.exists()) {
        System.err.println("Error: " + index + " does not exist!");
        System.exit(-1);
    }

    TServerSocket serverSocket = new TServerSocket(port);
    TrecSearch.Processor<TrecSearch.Iface> searchProcessor = new TrecSearch.Processor<TrecSearch.Iface>(
            new TrecSearchHandler(index, credentials));

    TThreadPoolServer.Args serverArgs = new TThreadPoolServer.Args(serverSocket);
    serverArgs.maxWorkerThreads(maxThreads);
    TServer thriftServer = new TThreadPoolServer(
            serverArgs.processor(searchProcessor).protocolFactory(new TBinaryProtocol.Factory()));

    thriftServer.serve();
}

From source file:edu.cmu.tetrad.cli.data.sim.DiscreteTabularData.java

/**
 * @param args the command line arguments
 *//*from  w  ww.j  a  va 2 s. c  o m*/
public static void main(String[] args) {
    if (args == null || args.length == 0 || Args.hasLongOption(args, "help")) {
        Args.showHelp("simulate-discrete-data", MAIN_OPTIONS);
        return;
    }

    try {
        CommandLineParser cmdParser = new DefaultParser();
        CommandLine cmd = cmdParser.parse(MAIN_OPTIONS, args);

        numOfVars = Args.getIntegerMin(cmd.getOptionValue("variable"), 0);
        numOfCases = Args.getIntegerMin(cmd.getOptionValue("case"), 0);
        edgeFactor = Args.getDoubleMin(cmd.getOptionValue("edge"), 1.0);
    } catch (ParseException exception) {
        System.err.println(exception.getLocalizedMessage());
        Args.showHelp("simulate-discrete-data", MAIN_OPTIONS);
        System.exit(-127);
    }

    List<Node> vars = new ArrayList<>();
    for (int i = 0; i < numOfVars; i++) {
        vars.add(new ContinuousVariable("X" + i));
    }
    Graph graph = GraphUtils.randomGraphRandomForwardEdges(vars, 0, (int) (numOfVars * edgeFactor), 30, 12, 15,
            false, true);
    BayesPm pm = new BayesPm(graph, 3, 3);
    BayesIm im = new MlBayesIm(pm, MlBayesIm.RANDOM);
    DataSet data = im.simulateData(numOfCases, false);

    String[] variables = data.getVariableNames().toArray(new String[0]);
    int lastIndex = variables.length - 1;
    for (int i = 0; i < lastIndex; i++) {
        System.out.printf("%s,", variables[i]);
    }
    System.out.printf("%s%n", variables[lastIndex]);

    DataBox dataBox = ((BoxDataSet) data).getDataBox();
    VerticalIntDataBox box = (VerticalIntDataBox) dataBox;
    //        int[][] matrix = box.getVariableVectors();
    //        int numOfColumns = matrix.length;
    //        int numOfRows = matrix[0].length;
    //        int[][] dataset = new int[numOfRows][numOfColumns];
    //        for (int i = 0; i < matrix.length; i++) {
    //            for (int j = 0; j < matrix[i].length; j++) {
    //                dataset[j][i] = matrix[i][j];
    //            }
    //        }
    //        for (int[] rowData : dataset) {
    //            lastIndex = rowData.length - 1;
    //            for (int i = 0; i < lastIndex; i++) {
    //                System.out.printf("%d,", rowData[i]);
    //            }
    //            System.out.printf("%s%n", rowData[lastIndex]);
    //        }
}

From source file:gov.nih.nci.indexgen.IndexGenerator.java

/**
 * Main program./*from w ww .java2s  .  c o m*/
 * Two mutually exclusive command line options are possible:
 * -I include the following classes
 * -E exclude the following classes
 * The classes are passed as a space delimited list like:
 * -I Taxon Cytoband
 * @param args
 */
public static void main(String[] args) throws Exception {

    String[] classFilter = null;
    boolean isInclude = true;

    Options options = new Options();
    options.addOption(OptionBuilder.withLongOpt("include").withDescription("classes to include")
            .hasOptionalArgs().create("I"));

    options.addOption(OptionBuilder.withLongOpt("exclude").withDescription("classes to exclude")
            .hasOptionalArgs().create("E"));

    CommandLineParser parser = new PosixParser();
    CommandLine cmd = parser.parse(options, args);
    String[] include = cmd.getOptionValues("I");
    String[] exclude = cmd.getOptionValues("E");

    if (include != null) {
        if (exclude != null)
            argError();
        isInclude = true;
        classFilter = include;
    } else if (exclude != null) {
        isInclude = false;
        classFilter = exclude;
    }

    SearchAPIProperties properties = SearchAPIProperties.getInstance();
    String ormFileName = properties.getOrmFileName();
    ;
    int threadCount = properties.getThreadCount() > 0 ? properties.getThreadCount() : 1;

    IndexGenerator indexgen = null;
    try {
        indexgen = new IndexGenerator(ormFileName, threadCount, classFilter, isInclude);
        indexgen.generate();
    } finally {
        if (indexgen != null)
            indexgen.close();
    }
}

From source file:com.adobe.aem.demomachine.RegExp.java

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

    String fileName = null;/*  ww  w  .ja v  a 2 s .com*/
    String regExp = null;
    String position = null;
    String value = "n/a";
    List<String> allMatches = new ArrayList<String>();

    // Command line options for this tool
    Options options = new Options();
    options.addOption("f", true, "Filename");
    options.addOption("r", true, "RegExp");
    options.addOption("p", true, "Position");
    CommandLineParser parser = new BasicParser();
    try {
        CommandLine cmd = parser.parse(options, args);

        if (cmd.hasOption("f")) {
            fileName = cmd.getOptionValue("f");
        }

        if (cmd.hasOption("f")) {
            regExp = cmd.getOptionValue("r");
        }

        if (cmd.hasOption("p")) {
            position = cmd.getOptionValue("p");
        }

        if (fileName == null || regExp == null || position == null) {
            System.out.println("Command line parameters: -f fileName -r regExp -p position");
            System.exit(-1);
        }

    } catch (ParseException ex) {

        logger.error(ex.getMessage());

    }

    String content = readFile(fileName, Charset.defaultCharset());

    if (content != null) {
        Matcher m = Pattern.compile(regExp).matcher(content);
        while (m.find()) {
            String group = m.group();
            int pos = group.indexOf(".zip");
            if (pos > 0) {
                group = group.substring(0, pos);
            }
            logger.debug("RegExp: " + m.group() + " found returning " + group);
            allMatches.add(group);
        }

        if (allMatches.size() > 0) {

            if (position.equals("first")) {
                value = allMatches.get(0);
            }

            if (position.equals("last")) {
                value = allMatches.get(allMatches.size() - 1);
            }
        }
    }

    System.out.println(value);

}

From source file:de.tudarmstadt.ukp.teaching.uima.nounDecompounding.ranking.TotalFreqAmout.java

@SuppressWarnings("static-access")
public static void main(String[] args) throws IOException {
    Options options = new Options();
    options.addOption(OptionBuilder.withLongOpt("index").withDescription("The path to the web1t lucene index")
            .hasArg().isRequired().create());

    CommandLineParser parser = new PosixParser();
    CommandLine cmd;/*  w w  w  .ja v  a 2s.c o  m*/
    try {
        cmd = parser.parse(options, args);
    } catch (ParseException e) {
        System.err.println("Error: " + e.getMessage());

        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("countTotalFreq", options);
        return;
    }

    TotalFreqAmout amount = new TotalFreqAmout(new File(cmd.getOptionValue("index")));
    System.out.println("Total amount: " + amount.countFreq());
}

From source file:com.adobe.aem.demomachine.Updates.java

public static void main(String[] args) {

    String rootFolder = null;//w  w  w .  jav  a 2  s.  c  o  m

    // Command line options for this tool
    Options options = new Options();
    options.addOption("f", true, "Demo Machine root folder");
    CommandLineParser parser = new BasicParser();
    try {
        CommandLine cmd = parser.parse(options, args);

        if (cmd.hasOption("f")) {
            rootFolder = cmd.getOptionValue("f");
        }

    } catch (Exception e) {
        System.exit(-1);
    }

    Properties md5properties = new Properties();

    try {
        URL url = new URL(
                "https://raw.githubusercontent.com/Adobe-Marketing-Cloud/aem-demo-machine/master/conf/checksums.properties");
        InputStream in = url.openStream();
        Reader reader = new InputStreamReader(in, "UTF-8");
        md5properties.load(reader);
        reader.close();
    } catch (Exception e) {
        System.out.println("Error: Cannot connect to GitHub.com to check for updates");
        System.exit(-1);
    }

    System.out.println(AemDemoConstants.HR);

    int nbUpdateAvailable = 0;

    List<String[]> listPaths = Arrays.asList(AemDemoConstants.demoPaths);
    for (String[] path : listPaths) {
        if (path.length == 5) {
            logger.debug(path[1]);
            File pathFolder = new File(rootFolder + (path[1].length() > 0 ? (File.separator + path[1]) : ""));
            if (pathFolder.exists()) {
                String newMd5 = AemDemoUtils.calcMD5HashForDir(pathFolder, Boolean.parseBoolean(path[3]),
                        false);
                logger.debug("MD5 is: " + newMd5);
                String oldMd5 = md5properties.getProperty("demo.md5." + path[0]);
                if (oldMd5 == null || oldMd5.length() == 0) {
                    logger.error("Cannot find MD5 for " + path[0]);
                    System.out.println(path[2] + " : Cannot find M5 checksum");
                    continue;
                }
                if (newMd5.equals(oldMd5)) {
                    continue;
                } else {
                    System.out.println(path[2] + " : New update available"
                            + (path[0].equals("0") ? " (use 'git pull' to get the latest changes)" : ""));
                    nbUpdateAvailable++;
                }
            } else {
                System.out.println(path[2] + " : Not installed");
            }
        }
    }

    if (nbUpdateAvailable == 0) {
        System.out.println("Your AEM Demo Machine is up to date!");
    }

    System.out.println(AemDemoConstants.HR);

}

From source file:com.teradata.tempto.sql.SqlResultGenerator.java

/**
 * The easiest way to generate expected results is to use
 * the python front-end (generate_results.py).
 *
 * @param args//from  w ww.j  a  va 2s  . c  o m
 */
public static void main(String[] args) {
    Options options = configureCommandLineParser();
    try {
        CommandLineParser parser = new BasicParser();
        CommandLine commandLine = parser.parse(options, args);
        if (commandLine.hasOption(HELP)) {
            usage(options);
            return;
        }
        String propertiesFileName = commandLine.getOptionValue("p");
        String testFileName = commandLine.getOptionValue("s");
        SqlResultGenerator resultGenerator = new SqlResultGenerator(testFileName, propertiesFileName);
        resultGenerator.generateExpectedResults();
    } catch (ParseException e) {
        usage(options);
    } catch (Exception e) {
        LOGGER.error("Caught exception in main", e);
    }
    System.exit(99);
}

From source file:edu.upc.eetac.dsa.exercices.java.lang.exceptions.App.java

public static void main(String[] args) throws FileNotFoundException {
    String filename = null;/*from ww w. ja  v a  2s  . c  o m*/
    String maxInteger = null;

    Options options = new Options();
    Option optionFile = OptionBuilder.withArgName("file").hasArg().withDescription("file with integers")
            .withLongOpt("file").create("f");
    options.addOption(optionFile);
    Option optionMax = OptionBuilder.withArgName("max").hasArg()
            .withDescription("maximum integer allowed in the file").withLongOpt("max").create("M");
    options.addOption(optionFile);
    options.addOption(optionMax);

    options.addOption("h", "help", false, "prints this message");

    CommandLineParser parser = new GnuParser();
    CommandLine line = null;
    try {
        // parse the command line arguments
        line = parser.parse(options, args);
        if (line.hasOption("h")) { // No hace falta preguntar por el parmetro "help". Ambos son sinnimos
            new HelpFormatter().printHelp(App.class.getCanonicalName(), options);
            return;
        }
        filename = line.getOptionValue("f");
        if (filename == null) {
            throw new org.apache.commons.cli.ParseException(
                    "You must provide the path to the file with numbers.");
        }
        maxInteger = line.getOptionValue("M");
    } catch (ParseException exp) {
        System.err.println(exp.getMessage());
        new HelpFormatter().printHelp(App.class.getCanonicalName(), options);
        return;
    }

    try {
        int[] numbers = (maxInteger != null) ? FileNumberReader.readFile(filename, Integer.parseInt(maxInteger))
                : FileNumberReader.readFile(filename);
        for (int i = 0; i < numbers.length; i++) {
            System.out.println("Integer read: " + numbers[i]);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } catch (BigNumberException e) {
        e.printStackTrace();
    }
}

From source file:io.github.gsteckman.doorcontroller.INA219Util.java

/**
 * Reads the Current from the INA219 with an I2C address and for a duration specified on the command line.
 * //from   w w w  . j av a 2 s . c o m
 * @param args
 *            Command line arguments.
 * @throws IOException
 *             If an error occurs reading/writing to the INA219
 * @throws ParseException
 *             If the command line arguments could not be parsed.
 */
public static void main(String[] args) throws IOException, ParseException {
    Options options = new Options();
    options.addOption("addr", true, "I2C Address");
    options.addOption("d", true, "Acquisition duration, in seconds");
    options.addOption("bv", false, "Also read bus voltage");
    options.addOption("sv", false, "Also read shunt voltage");

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

    Address addr = Address.ADDR_40;
    if (cmd.hasOption("addr")) {
        int opt = Integer.parseInt(cmd.getOptionValue("addr"), 16);
        Address a = Address.getAddress(opt);
        if (a != null) {
            addr = a;
        } else {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("INA219Util", options);
            return;
        }
    }

    int duration = 0;
    if (cmd.hasOption("d")) {
        String opt = cmd.getOptionValue("d");
        duration = Integer.parseInt(opt);
    } else {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("INA219Util", options);
        return;

    }

    boolean readBusVoltage = false;
    if (cmd.hasOption("bv")) {
        readBusVoltage = true;
    }

    boolean readShuntVoltage = false;
    if (cmd.hasOption("sv")) {
        readShuntVoltage = true;
    }

    INA219 i219 = new INA219(addr, 0.1, 3.2, INA219.Brng.V16, INA219.Pga.GAIN_8, INA219.Adc.BITS_12,
            INA219.Adc.SAMPLES_128);

    System.out.printf("Time\tCurrent");
    if (readBusVoltage) {
        System.out.printf("\tBus");
    }
    if (readShuntVoltage) {
        System.out.printf("\tShunt");
    }
    System.out.printf("\n");
    long start = System.currentTimeMillis();
    do {
        try {
            System.out.printf("%d\t%f", System.currentTimeMillis() - start, i219.getCurrent());
            if (readBusVoltage) {
                System.out.printf("\t%f", i219.getBusVoltage());
            }
            if (readShuntVoltage) {
                System.out.printf("\t%f", i219.getShuntVoltage());
            }
            System.out.printf("\n");
            Thread.sleep(100);
        } catch (IOException e) {
            LOG.error("Exception while reading I2C bus", e);
        } catch (InterruptedException e) {
            break;
        }
    } while (System.currentTimeMillis() - start < duration * 1000);
}