Example usage for org.apache.commons.cli CommandLine iterator

List of usage examples for org.apache.commons.cli CommandLine iterator

Introduction

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

Prototype

public Iterator iterator() 

Source Link

Document

Returns an iterator over the Option members of CommandLine.

Usage

From source file:com.github.horrorho.liquiddonkey.settings.commandline.CommandLinePropertiesFactory.java

public Properties from(Properties parent, CommandLineOptions commandLineOptions, String[] args)
        throws ParseException {

    Properties properties = new Properties(parent);
    CommandLineParser parser = new DefaultParser();
    Options options = commandLineOptions.options();
    CommandLine cmd = parser.parse(options, args);

    switch (cmd.getArgList().size()) {
    case 0:/*from w  w w.  j a v  a2 s .  c  om*/
        // No authentication credentials
        break;
    case 1:
        // Authentication token
        properties.put(Property.AUTHENTICATION_TOKEN.name(), cmd.getArgList().get(0));
        break;
    case 2:
        // AppleId/ password pair
        properties.put(Property.AUTHENTICATION_APPLEID.name(), cmd.getArgList().get(0));
        properties.put(Property.AUTHENTICATION_PASSWORD.name(), cmd.getArgList().get(1));
        break;
    default:
        throw new ParseException(
                "Too many non-optional arguments, expected appleid/ password or authentication token only.");
    }

    Iterator<Option> it = cmd.iterator();

    while (it.hasNext()) {
        Option option = it.next();
        String opt = commandLineOptions.opt(option);
        String property = commandLineOptions.property(option).name();

        if (option.hasArgs()) {
            // String array
            properties.put(property, joined(cmd.getOptionValues(opt)));
        } else if (option.hasArg()) {
            // String value
            properties.put(property, cmd.getOptionValue(opt));
        } else {
            // String boolean
            properties.put(property, Boolean.toString(cmd.hasOption(opt)));
        }
    }
    return properties;
}

From source file:nl.imvertor.common.Configurator.java

/**
 * Create parameters from arguments passed to the java application. 
 * Arguments are parsed by CLI conventions. 
 * Existing argument parameters are replaced.
 * /* w ww.jav  a 2  s  .c  o  m*/
 * Parameters set from command line option are placed in /config/cli subelement and take the form 
 * /config/cli/parameter[@name]/text()  
 * 
 * @param options Command line options
 * @throws Exception 
 */
public void setParmsFromOptions(String[] args) throws Exception {
    CommandLine commandLine = null;
    File curFile = baseFolder;
    try {
        BasicParser parser = new BasicParser();
        commandLine = parser.parse(options, args);
        if (commandLine.hasOption("help"))
            dieOnCli(commandLine.getOptionValue("help"));
    } catch (ParseException e) {
        runner.error(logger, e.getMessage());
        dieOnCli("error");
    }

    @SuppressWarnings("unchecked")
    Iterator<Option> it = commandLine.iterator();
    while (it.hasNext()) {
        Option option = it.next();
        String optionName = option.getOpt();
        String[] v = commandLine.getOptionValues(optionName); // same option many times returns array of values.
        if (v.length > 1)
            throw new Exception("Duplicate argument -" + optionName + " on command line");
        if (optionName.equals("arguments"))
            loadFromPropertyFiles(curFile, v[0]);
        setParm(workConfiguration, "cli", optionName, v[0], true);
        setOptionIsReady(optionName, true);
    }

    String missing = checkOptionsAreReady();
    if (!missing.equals("")) {
        runner.error(logger, "Missing required parameters: " + missing);
        dieOnCli("program");
    }

    // record the metamodel used
    metamodel = getParm(workConfiguration, "cli", "metamodel", false);
    metamodel = (metamodel == null) ? DEFAULT_METAMODEL : metamodel;

    // schema rules used
    schemarules = getParm(workConfiguration, "cli", "schemarules", false);
    schemarules = (schemarules == null) ? DEFAULT_SCHEMARULES : schemarules;

    // set the task
    setParm(workConfiguration, "appinfo", "task", getParm(workConfiguration, "cli", "task", true), true);

    // If forced compilation, try all steps irrespective of any errors
    forceCompile = isTrue(getParm(workConfiguration, "cli", "forcecompile", true));

    // If documentation release, set the suffix for the application id
    String docReleaseString = getParm(workConfiguration, "cli", "docrelease", false);

    // if warnings should be signaled
    suppressWarnings = isTrue("cli", "suppresswarnings", false);

    docRelease = docReleaseString != null && !docReleaseString.equals("00000000");
    if (docRelease) {
        setParm("system", "documentation-release", "-" + docReleaseString);
    } else {
        setParm("system", "documentation-release", "");
    }

}

From source file:org.apache.commons.jci.examples.commandline.CommandlineCompiler.java

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

    final Options options = new Options();

    options.addOption(OptionBuilder.withArgName("a.jar:b.jar").hasArg().withValueSeparator(':')
            .withDescription("Specify where to find user class files").create("classpath"));

    options.addOption(OptionBuilder.withArgName("release").hasArg()
            .withDescription("Provide source compatibility with specified release").create("source"));

    options.addOption(OptionBuilder.withArgName("release").hasArg()
            .withDescription("Generate class files for specific VM version").create("target"));

    options.addOption(OptionBuilder.withArgName("path").hasArg()
            .withDescription("Specify where to find input source files").create("sourcepath"));

    options.addOption(OptionBuilder.withArgName("directory").hasArg()
            .withDescription("Specify where to place generated class files").create("d"));

    options.addOption(OptionBuilder.withArgName("num").hasArg()
            .withDescription("Stop compilation after these number of errors").create("Xmaxerrs"));

    options.addOption(OptionBuilder.withArgName("num").hasArg()
            .withDescription("Stop compilation after these number of warning").create("Xmaxwarns"));

    options.addOption(OptionBuilder.withDescription("Generate no warnings").create("nowarn"));

    //        final HelpFormatter formatter = new HelpFormatter();
    //        formatter.printHelp("jci", options);

    final CommandLineParser parser = new GnuParser();
    final CommandLine cmd = parser.parse(options, args, true);

    ClassLoader classloader = CommandlineCompiler.class.getClassLoader();
    File sourcepath = new File(".");
    File targetpath = new File(".");
    int maxerrs = 10;
    int maxwarns = 10;
    final boolean nowarn = cmd.hasOption("nowarn");

    final JavaCompiler compiler = new JavaCompilerFactory().createCompiler("eclipse");
    final JavaCompilerSettings settings = compiler.createDefaultSettings();

    for (Iterator it = cmd.iterator(); it.hasNext();) {
        final Option option = (Option) it.next();
        if ("classpath".equals(option.getOpt())) {
            final String[] values = option.getValues();
            final URL[] urls = new URL[values.length];
            for (int i = 0; i < urls.length; i++) {
                urls[i] = new File(values[i]).toURL();
            }/*  w w  w .  j  a  va 2 s . c  om*/
            classloader = new URLClassLoader(urls);
        } else if ("source".equals(option.getOpt())) {
            settings.setSourceVersion(option.getValue());
        } else if ("target".equals(option.getOpt())) {
            settings.setTargetVersion(option.getValue());
        } else if ("sourcepath".equals(option.getOpt())) {
            sourcepath = new File(option.getValue());
        } else if ("d".equals(option.getOpt())) {
            targetpath = new File(option.getValue());
        } else if ("Xmaxerrs".equals(option.getOpt())) {
            maxerrs = Integer.parseInt(option.getValue());
        } else if ("Xmaxwarns".equals(option.getOpt())) {
            maxwarns = Integer.parseInt(option.getValue());
        }
    }

    final ResourceReader reader = new FileResourceReader(sourcepath);
    final ResourceStore store = new FileResourceStore(targetpath);

    final int maxErrors = maxerrs;
    final int maxWarnings = maxwarns;
    compiler.setCompilationProblemHandler(new CompilationProblemHandler() {
        int errors = 0;
        int warnings = 0;

        public boolean handle(final CompilationProblem pProblem) {

            if (pProblem.isError()) {
                System.err.println(pProblem);

                errors++;

                if (errors >= maxErrors) {
                    return false;
                }
            } else {
                if (!nowarn) {
                    System.err.println(pProblem);
                }

                warnings++;

                if (warnings >= maxWarnings) {
                    return false;
                }
            }

            return true;
        }
    });

    final String[] resource = cmd.getArgs();

    for (int i = 0; i < resource.length; i++) {
        System.out.println("compiling " + resource[i]);
    }

    final CompilationResult result = compiler.compile(resource, reader, store, classloader);

    System.out.println(result.getErrors().length + " errors");
    System.out.println(result.getWarnings().length + " warnings");

}

From source file:org.apache.hadoop.hdfs.server.diskbalancer.command.Command.java

/**
 * Verifies if the command line options are sane.
 *
 * @param commandName - Name of the command
 * @param cmd         - Parsed Command Line
 *//*  www. j a  v  a2s . c om*/
protected void verifyCommandOptions(String commandName, CommandLine cmd) {
    @SuppressWarnings("unchecked")
    Iterator<Option> iter = cmd.iterator();
    while (iter.hasNext()) {
        Option opt = iter.next();

        if (!validArgs.containsKey(opt.getLongOpt())) {
            String errMessage = String.format("%nInvalid argument found for command %s : %s%n", commandName,
                    opt.getLongOpt());
            StringBuilder validArguments = new StringBuilder();
            validArguments.append(String.format("Valid arguments are : %n"));
            for (Map.Entry<String, String> args : validArgs.entrySet()) {
                String key = args.getKey();
                String desc = args.getValue();
                String s = String.format("\t %s : %s %n", key, desc);
                validArguments.append(s);
            }
            LOG.error(errMessage + validArguments.toString());
            throw new IllegalArgumentException("Invalid Arguments found.");
        }
    }
}

From source file:org.blue.star.plugins.check_base.java

/**
 * Handle the flow for processing command line arguments, as well as processing the common set.
 * TODO  if needed to move this to a in process, must remove the System.exit calls.
 * @param args Command line arguments//  www  .ja va  2s .  c o  m
 * @return  true/false depending on processing results.
 */
private final void process_arguments(String[] args) throws IllegalArgumentException {

    options = utils_h.getStandardOptions();

    // call super to add it's command arguments.
    add_command_arguments(options);

    CommandLine cmd = null;
    try {
        cmd = new PosixParser().parse(options, args);
    } catch (Exception e) {
        throw new IllegalArgumentException(programName + ": Could not parse arguments.");
    }

    java.util.Iterator iter = cmd.iterator();
    while (iter.hasNext()) {
        Option o = (Option) iter.next();
        String optarg = o.getValue();

        if (verbose > 0)
            System.out.println("processing " + o + "(" + o.getId() + ") " + o.getValue());

        /* Process the basic command line agruments, default sends this to child for processing */
        switch (o.getId()) {
        case 'h': /* help */
            print_help();
            System.exit(common_h.STATE_UNKNOWN);
            break;
        case 'V': /* version */
            utils.print_revision(programName, revision);
            System.exit(common_h.STATE_UNKNOWN);
            break;
        case 't': /* timeout period */
            utils_h.timeout_interval = Integer.parseInt(optarg);
            break;
        case 'v': /* verbose mode */
            verbose++;
            break;
        }
        /*  Allow extension to process all options, even if we already processed */
        process_command_option(o);
    }

    String[] argv = cmd.getArgs();
    if (argv != null && argv.length > 0)
        process_command_arguments(argv);

    validate_command_arguments();

}

From source file:org.obiba.bitwise.client.BitwiseClient.java

/**
 * Activates the command line client by providing a BitwiseStore object.
 * @param pStore is the BitwiseStore to be queried
 * @throws IOException/*from www . j a v a2  s.c  o m*/
 */
public void execute(BitwiseStore store) throws IOException {
    //Start command line client
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    BasicParser bp = new BasicParser();

    //Prepare ClientContext
    ClientContext context = new ClientContext();
    context.setStore(store);

    System.out.println("Type '-h' for help, '-q' to quit.");

    //Loop as long as there are no options asking to quit
    boolean quit = false;
    while (!quit) {
        store = context.getStore(); //Store might have been switched
        prompt(context);
        String str = br.readLine();
        CommandLine cl = null;
        try {
            cl = bp.parse(options, str.split(" "));
        } catch (ParseException e) {
            quit = help.execute(null, context);
        }

        if (cl != null) {
            Iterator<Option> commands = cl.iterator();
            while (commands.hasNext()) {
                Option o = commands.next();
                CliCommand c = commandMap.get(o.getOpt());
                if (c == null) {
                    System.err.println("Cannot find command for option [" + o + "]");
                    quit = help.execute(null, context);
                } else {
                    try {
                        quit = c.execute(o, context);
                    } catch (ParseException e) {
                        quit = help.execute(null, context);
                    }
                }
            }

            //The given command is a query, as there are no options specified
            if (cl.getOptions() == null || cl.getOptions().length == 0) {
                try {
                    QueryParser parser = new QueryParser();
                    String[] args = cl.getArgs();
                    String queryString = StringUtil.aggregate(args, " ");
                    if (StringUtil.isEmptyString(queryString) == false) {
                        long start = System.currentTimeMillis();
                        Query q = parser.parse(queryString);
                        QueryResult qr = q.execute(context.getStore());
                        context.setLastResult(qr);
                        long end = System.currentTimeMillis();

                        //Prepare result display on screen
                        List<String> fieldList = new Vector<String>();
                        //Filter out template fields
                        for (String field : store.getFieldList()) {
                            if (field.matches(".*_\\d+")) {
                                continue;
                            }
                            fieldList.add(field);
                        }
                        ResultDisplay rd = new ResultDisplay(fieldList);
                        //              rd.setDisplayType(ResultDisplay.DisplayType.PLAIN);
                        int hitIndex = qr.next(0);
                        while (hitIndex != -1) {
                            rd.putRecord(store, hitIndex);
                            hitIndex = qr.next(hitIndex + 1);
                        }

                        //Display results in console
                        System.out.println(rd.getOutput());
                        System.out.println(qr.count() + " results in " + (end - start) + " milliseconds.\n");
                    }
                } catch (org.obiba.bitwise.query.ParseException e) {
                    System.err.println(e.getMessage());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

From source file:org.obiba.genobyte.cli.BitwiseCli.java

/**
 * Starts the CLI shell./*ww  w  .  j  a v  a  2s  .c om*/
 * 
 * @throws IOException when an error occurs while reading user input.
 */
public void execute() throws IOException {
    CliContext context = new CliContext(this.output);
    BufferedReader br = new BufferedReader(new InputStreamReader(input));
    BasicParser bp = new BasicParser();
    output.println("Type '-h' for help, '-q' to quit.");
    while (true) {
        prompt(context);
        boolean quit = false;
        String str = br.readLine();
        CommandLine cl = null;
        try {
            if (context.getStore() == null) {
                cl = bp.parse(noStoreOptions, str.split(" "));
            } else {
                cl = bp.parse(options, str.split(" "));
            }
        } catch (ParseException e) {
            quit = help.execute(null, context);
        }

        if (cl != null) {
            Iterator<Option> commands = cl.iterator();
            // We don't iterate to make sure we execute only one command
            if (commands.hasNext()) {
                Option o = commands.next();
                CliCommand c = commandMap.get(o.getLongOpt());
                if (c == null) {
                    throw new IllegalStateException(
                            "No CliCommand associated with option [" + o.getOpt() + "]");
                } else {
                    try {
                        quit = c.execute(o, context);
                    } catch (ParseException e) {
                        quit = help.execute(null, context);
                    } catch (Exception e) {
                        output.println(
                                "An unexpected error occurred while executing the command: " + e.getMessage());
                    }
                }
            }

            // Not handled by any command: it should be a query.
            String queryString = str;
            if (context.getStore() != null && (cl.getOptions() == null || cl.getOptions().length == 0)) {
                try {
                    QueryParser parser = new QueryParser();
                    long start = System.currentTimeMillis();
                    if (StringUtil.isEmptyString(queryString) == false) {
                        Query q = parser.parse(queryString);
                        QueryResult qr = q.execute(context.getActiveRecordStore().getStore());
                        String reference = context.addQuery(queryString, qr);
                        long end = System.currentTimeMillis();
                        output.println(reference + ": " + qr.count() + " results in " + (end - start)
                                + " milliseconds.");
                    }
                } catch (org.obiba.bitwise.query.UnknownFieldException e) {
                    output.println(e.getMessage());
                } catch (org.obiba.bitwise.query.ParseException e) {
                    output.println("The query [" + queryString
                            + "] is invalid. Please refer to the query syntax for more information.");
                } catch (Exception e) {
                    output.println(
                            "An unexpected error occurred while executing the query. The following data may be helpful to debug the problem.");
                    e.printStackTrace(output);
                }
            }
        }
        if (quit)
            break;
    }
}