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.retroduction.carma.application.util.CLIValidator.java

public CommandLine readCLI(String[] args) throws ParseException {

    return new GnuParser().parse(this.initOptions(), args);

}

From source file:es.tid.cosmos.platform.injection.server.ServerCommandLine.java

/**
 * Constructor.//from  ww  w .ja  va  2 s.  com
 */
public ServerCommandLine() {
    this.parser = new GnuParser();
    this.options = new Options().addOption(SHORT_CONFIG_FILE, LONG_CONFIG_FILE, true, "Configuration file");
}

From source file:com.google.oacurl.options.CommonOptions.java

public CommandLine parse(String[] args) throws ParseException {
    CommandLine line = new GnuParser().parse(options, args);

    loginFileName = line.getOptionValue("access-file",
            new File(System.getProperty("user.home"), DEFAULT_LOGIN_FILE_NAME).getAbsolutePath());
    help = line.hasOption("help");
    verbose = line.hasOption("verbose");
    insecure = line.hasOption("insecure");

    return line;// w ww  .  j a va2 s.c om
}

From source file:com.mozilla.fhr.consumer.FHRConsumer.java

public static void main(String[] args) {
    Options options = FHRConsumer.getOptions();
    CommandLineParser parser = new GnuParser();
    ShutdownHook sh = ShutdownHook.getInstance();
    try {/*w  ww  .  j a  v  a  2 s  . c  o m*/
        // Parse command line options
        CommandLine cmd = parser.parse(options, args);

        final FHRConsumer consumer = (FHRConsumer) FHRConsumer.fromOptions(cmd);
        sh.addFirst(consumer);

        // Set the sink for consumer storage
        SinkConfiguration sinkConfig = new SinkConfiguration();
        if (cmd.hasOption("numthreads")) {
            sinkConfig.setInt("hbasesink.hbase.numthreads", Integer.parseInt(cmd.getOptionValue("numthreads")));
        }
        if (cmd.hasOption("batchsize")) {
            sinkConfig.setInt("hbasesink.hbase.batchsize", Integer.parseInt(cmd.getOptionValue("batchsize")));
        }

        sinkConfig.setString("hbasesink.hbase.tablename", cmd.getOptionValue("table"));
        sinkConfig.setString("hbasesink.hbase.column.family", cmd.getOptionValue("family", "data"));
        sinkConfig.setString("hbasesink.hbase.column.qualifier", cmd.getOptionValue("qualifier", "json"));
        sinkConfig.setBoolean("hbasesink.hbase.rowkey.prefixdate",
                Boolean.parseBoolean(cmd.getOptionValue("prefixdate", "false")));
        KeyValueSinkFactory sinkFactory = KeyValueSinkFactory.getInstance(HBaseSink.class, sinkConfig);
        sh.addLast(sinkFactory);
        consumer.setSinkFactory(sinkFactory);

        // Initialize metrics collection, reporting, etc.
        final MetricsManager manager = MetricsManager.getDefaultMetricsManager();

        // Begin polling
        consumer.poll();
    } catch (ParseException e) {
        LOG.error("Error parsing command line options", e);
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(FHRConsumer.class.getName(), options);
    }
}

From source file:de.oth.keycloak.util.CheckParams.java

private static CommandLine checkCommandline(String[] args, PrintStream printStream) {
    Options options = getCommandLineOptions();
    CommandLineParser parser = new GnuParser();
    try {//from ww  w.  j a va  2s .c  om
        CommandLine ret = parser.parse(options, args);
        if (ret.getOptions().length == 0 || ret.hasOption(CONF_HELP)) {
            printCommandLineHelp(options);
            return null;
        }
        return ret;
    } catch (ParseException e) {
        printStream.println(e.getMessage());
        printCommandLineHelp(options);
        return null;
    }
}

From source file:com.aliyun.openservices.odps.console.commands.DescribeProjectCommand.java

public static AbstractCommand parse(String cmd, ExecutionContext ctx) throws ODPSConsoleException {
    if (cmd == null || ctx == null) {
        return null;
    }/*from  w  ww. ja v  a  2s.c  om*/

    String[] tokens = new AntlrObject(cmd).getTokenStringArray();

    if (tokens.length < 2) {
        return null;
    }

    if (!("DESC".equalsIgnoreCase(tokens[0]) || "DESCRIBE".equalsIgnoreCase(tokens[0]))) {
        return null;
    }

    if (!("PROJECT".equalsIgnoreCase(tokens[1]))) {
        return null;
    }

    CommandLine parser = null;
    try {
        parser = new GnuParser().parse(getOptions(), tokens);
    } catch (ParseException e) {
        throw new ODPSConsoleException(e.getMessage(), e);
    }
    boolean extended = parser.hasOption("extended");
    if (parser.getArgList().size() != 3) {
        throw new ODPSConsoleException(ODPSConsoleConstants.BAD_COMMAND);
    }

    String projectName = parser.getArgs()[2];

    return new DescribeProjectCommand(projectName, extended, cmd, ctx);
}

From source file:gov.nasa.jpl.mudrod.ontology.process.LocalOntology.java

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

    // boolean options
    Option helpOpt = new Option("h", "help", false, "show this help message");
    // argument options
    Option ontDirOpt = OptionBuilder.hasArg(true).withArgName(ONT_DIR)
            .withDescription("A directory containing .owl files.").isRequired(false).create();

    // create the options
    Options options = new Options();
    options.addOption(helpOpt);//from  w  ww .j  av  a  2 s.  c  o m
    options.addOption(ontDirOpt);

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

        if (line.hasOption(ONT_DIR)) {
            ontDir = line.getOptionValue(ONT_DIR).replace("\\", "/");
        } else {
            ontDir = LocalOntology.class.getClassLoader().getResource("ontology").getFile();
        }
        if (!ontDir.endsWith("/")) {
            ontDir += "/";
        }
    } catch (Exception e) {
        LOG.error("Error whilst processing main method of LocalOntology.", e);
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("LocalOntology: 'ontDir' argument is mandatory. ", options, true);
        return;
    }
    File fileDir = new File(ontDir);
    //Fail if the input is not a directory.
    if (fileDir.isDirectory()) {
        List<String> owlFiles = new ArrayList<>();
        for (File owlFile : fileDir.listFiles()) {
            owlFiles.add(owlFile.toString());
        }
        MudrodEngine mEngine = new MudrodEngine();
        Properties props = mEngine.loadConfig();
        Ontology ontology = new OntologyFactory(props).getOntology();
        //convert to correct iput for ontology loading.
        String[] owlArray = new String[owlFiles.size()];
        owlArray = owlFiles.toArray(owlArray);
        ontology.load(owlArray);

        String[] terms = new String[] { "Glacier ice" };
        //Demonstrate that we can do basic ontology heirarchy navigation and log output.
        for (Iterator<OntClass> i = getParser().rootClasses(getModel()); i.hasNext();) {

            //print Ontology Class Hierarchy
            OntClass c = i.next();
            renderHierarchy(System.out, c, new LinkedList<>(), 0);

            for (Iterator<OntClass> subClass = c.listSubClasses(true); subClass.hasNext();) {
                OntClass sub = subClass.next();
                //This means that the search term is present as an OntClass
                if (terms[0].equalsIgnoreCase(sub.getLabel(null))) {
                    //Add the search term(s) above to the term cache.
                    for (int j = 0; j < terms.length; j++) {
                        addSearchTerm(terms[j], sub);
                    }

                    //Query the ontology and return subclasses of the search term(s)
                    for (int k = 0; k < terms.length; k++) {
                        Iterator<String> iter = ontology.subclasses(terms[k]);
                        while (iter.hasNext()) {
                            LOG.info("Subclasses >> " + iter.next());
                        }
                    }

                    //print any synonymic relationships to demonstrate that we can 
                    //undertake synonym-based query expansion
                    for (int l = 0; l < terms.length; l++) {
                        Iterator<String> iter = ontology.synonyms(terms[l]);
                        while (iter.hasNext()) {
                            LOG.info("Synonym >> " + iter.next());
                        }
                    }
                }
            }
        }

        mEngine.end();
    }

}

From source file:com.aliyun.openservices.odps.console.resource.CreateResourceCommand.java

public static AddResourceCommand parse(String commandString, ExecutionContext sessionContext)
        throws ODPSConsoleException {

    String[] tokens = new AntlrObject(commandString).getTokenStringArray();

    if (tokens != null && tokens.length >= 2 && tokens[0].toUpperCase().equals("CREATE")
            && tokens[1].toUpperCase().equals("RESOURCE")) {

        GnuParser parser = new GnuParser();
        Options options = new Options();
        options.addOption("p", "project", true, null);
        options.addOption("c", "comment", true, null);
        options.addOption("f", "force", false, null);

        try {/* w w  w  .  jav a 2  s .  c  o m*/
            CommandLine cl = parser.parse(options, tokens);

            String refName = null;
            String alias = "";
            String comment = null;
            String type = null;
            String partitionSpec = "";
            boolean isUpdate = false;

            List<String> argList = cl.getArgList();
            int size = argList.size();

            if (size < 4) {
                throw new ODPSConsoleException(ODPSConsoleConstants.BAD_COMMAND + "Missing parameters");
            }

            ListIterator<String> iter = argList.listIterator();
            iter.next();
            iter.next();
            type = iter.next();
            refName = iter.next();
            if (iter.hasNext()) {
                String item = iter.next();
                if (item.equals("(")) {
                    boolean isParenPaired = false;

                    while (iter.hasNext()) {
                        String s = iter.next();
                        if (s.equals(")")) {
                            isParenPaired = true;
                            break;
                        }
                        partitionSpec += s;
                    }

                    if (!isParenPaired) {
                        throw new ODPSConsoleException(
                                ODPSConsoleConstants.BAD_COMMAND + "Unpaired parenthesis");
                    }

                    if (!iter.hasNext()) {
                        throw new ODPSConsoleException(
                                ODPSConsoleConstants.BAD_COMMAND + "Missing parameter: alias");
                    }
                    item = iter.next();
                }

                alias = item;
            }

            if (iter.hasNext()) {
                throw new ODPSConsoleException(
                        ODPSConsoleConstants.BAD_COMMAND + "Illegal parameter: " + iter.next());
            }

            String projectName = null;
            Option[] opts = cl.getOptions();
            for (Option opt : opts) {
                if ("f".equals(opt.getOpt())) {
                    isUpdate = true;
                } else if ("c".equals(opt.getOpt())) {
                    comment = opt.getValue();
                } else if ("p".equals(opt.getOpt())) {
                    projectName = opt.getValue();
                } else {
                    throw new ODPSConsoleException(
                            ODPSConsoleConstants.BAD_COMMAND + "Illegal option: " + opt.getOpt());
                }
            }

            return new AddResourceCommand(commandString, sessionContext, refName, alias, comment, type,
                    partitionSpec, isUpdate, projectName);
        } catch (ParseException e) {
            throw new ODPSConsoleException(ODPSConsoleConstants.BAD_COMMAND + "Invalid parameters");
        }
    } else {
        return null;
    }
}

From source file:com.collective.celos.ci.config.CiCommandLineParser.java

public CiCommandLine parse(final String[] commandLineArguments) throws Exception {

    final CommandLineParser cmdLineGnuParser = new GnuParser();
    final Options gnuOptions = constructOptionsForParsing();
    CommandLine commandLine = cmdLineGnuParser.parse(gnuOptions, commandLineArguments);

    if (!commandLine.hasOption(CLI_TARGET) || !commandLine.hasOption(CLI_MODE)
            || !commandLine.hasOption(CLI_WORKFLOW_NAME)) {
        printHelp(80, 5, 3, true, System.out);
        throw new RuntimeException("Wrong CelosCi configuration provided");
    }//from   w w w  .j a  va  2s .  c o m

    String deployDir = commandLine.getOptionValue(CLI_DEPLOY_DIR);
    String mode = commandLine.getOptionValue(CLI_MODE);
    String workflowName = commandLine.getOptionValue(CLI_WORKFLOW_NAME);
    String targetUri = commandLine.getOptionValue(CLI_TARGET);
    String testCasesDir = commandLine.getOptionValue(CLI_TEST_CASES_DIR, DEFAULT_TEST_CASES_DIR);
    String hdfsRoot = commandLine.getOptionValue(CLI_HDFS_ROOT, Constants.DEFAULT_HDFS_ROOT);
    String celosServerUri = commandLine.getOptionValue(CLI_CELOS_SERVER);

    boolean keepTempData = Boolean.parseBoolean(System.getenv(KEEP_TEMP_DATA));
    String userName = System.getenv(USERNAME_ENV_VAR);
    if (userName == null) {
        userName = System.getProperty("user.name");
    }
    return new CiCommandLine(targetUri, mode, deployDir, workflowName, testCasesDir, userName, keepTempData,
            celosServerUri, hdfsRoot);
}

From source file:com.zimbra.qa.unittest.prov.ldap.TestLdapReadTimeout.java

/**
 * /Users/pshao/dev/workspace/sandbox/sandbox/bin>/System/Library/Frameworks/JavaVM.framework/Versions/1.6/Home/bin/java  LdapReadTimeout
 * /System/Library/Frameworks/JavaVM.framework/Versions/1.6/Home/bin/java LdapReadTimeout
 * // w  w  w.  j a va 2s . c o  m
 * zmjava com.zimbra.qa.unittest.TestLdapReadTimeout -s 5
 * zmjava com.zimbra.qa.unittest.TestLdapReadTimeout -H ldap://localhost:389 -D uid=zimbra,cn=admins,cn=zimbra -w zimbra -s 5
 * 
 * @param args
 */
public static void main(String[] args) throws Exception {
    Options options = new Options();
    options.addOption(O_HELP, false, "print usage");
    options.addOption(O_SLEEP, true, "upon hitting an Exception, minutes to wait until exiting the program.  "
            + "If not specified, will exit immediately.");
    options.addOption(O_URI, true, "URI. e.g. ldap://localhost:389");
    options.addOption(O_BINDDN, true, "bind DN");
    options.addOption(O_PASSWORD, true, "password");

    CommandLine cl = null;
    try {
        CommandLineParser parser = new GnuParser();
        cl = parser.parse(options, args);
        if (cl == null) {
            throw new ParseException("");
        }
    } catch (ParseException e) {
        usage(options);
        e.printStackTrace();
        System.exit(1);
    }

    if (cl.hasOption(O_HELP)) {
        usage(options);
        System.exit(0);
    }

    String uri = null;
    String bindDN = null;
    String password = null;
    Integer minutesToWait = null;

    if (cl.hasOption(O_URI)) {
        uri = cl.getOptionValue(O_URI);
    } else {
        uri = "ldap://localhost:389";
    }

    if (cl.hasOption(O_BINDDN)) {
        bindDN = cl.getOptionValue(O_BINDDN);
    } else {
        bindDN = "uid=zimbra,cn=admins,cn=zimbra";
    }

    if (cl.hasOption(O_PASSWORD)) {
        password = cl.getOptionValue(O_PASSWORD);
    } else {
        password = "zimbra";
    }

    if (cl.hasOption(O_SLEEP)) {
        String wait = cl.getOptionValue(O_SLEEP);

        try {
            minutesToWait = Integer.valueOf(wait);
        } catch (NumberFormatException e) {
            usage(options);
            e.printStackTrace();
            System.exit(1);
        }
    }

    LdapReadTimeoutTester tester = null;

    try {
        // tester = new JNDITest(uri, bindDN, password);  // fails
        tester = new UnboundIDTest(uri, bindDN, password); // works

        System.out.println("=============");
        System.out.println(tester.getClass().getCanonicalName());
        System.out.println("LDAP server URI: " + uri);
        System.out.println("bind DN: " + bindDN);
        System.out.println("=============");
        System.out.println();

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

    long startTime = System.currentTimeMillis();
    test(tester);
    long endTime = System.currentTimeMillis();
    long elapsed = endTime - startTime;

    SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    System.out.println();
    System.out.println(tester.getClass().getCanonicalName());
    System.out.println("Started at: " + fmt.format(new Date(startTime)));
    System.out.println("Ended at: " + fmt.format(new Date(endTime)));
    System.out.println("Elapsed = " + (elapsed / 1000) + " seconds");
    System.out.println();

    if (minutesToWait != null) {
        System.out.println("Sleeping for " + minutesToWait + " minutes before exiting...");
        Thread.sleep(minutesToWait * 60 * 1000);
    }
}