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

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

Introduction

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

Prototype

public List getArgList() 

Source Link

Document

Retrieve any left-over non-recognized options and arguments

Usage

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 {/*from  w  ww .  j a v  a2 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:lanchon.dexpatcher.Parser.java

public static Configuration parseCommandLine(String[] args) throws ParseException {

    Configuration config = new Configuration();

    Options options = getOptions();/* ww  w.j a va 2  s  .  co  m*/
    CommandLine cl = new PosixParser().parse(options, args);

    if (cl.hasOption("help")) {
        printUsage();
        return null;
    }

    if (cl.hasOption("version")) {
        System.out.println(Main.getVersion());
        return null;
    }

    @SuppressWarnings("unchecked")
    List<String> files = cl.getArgList();
    if (files.isEmpty())
        throw new ParseException("Missing argument: <source-dex-apk-or-dir>");
    config.sourceFile = files.remove(0);
    config.patchFiles = files;
    config.patchedFile = cl.getOptionValue("output");

    Number apiLevel = (Number) cl.getParsedOptionValue("api-level");
    if (apiLevel != null)
        config.apiLevel = apiLevel.intValue();

    config.multiDex = cl.hasOption("multi-dex");
    if (cl.hasOption("multi-dex-threaded")) {
        config.multiDex = true;
        config.multiDexJobs = 0;
    }
    Number multiDexJobs = (Number) cl.getParsedOptionValue("multi-dex-jobs");
    if (multiDexJobs != null) {
        config.multiDex = true;
        config.multiDexJobs = multiDexJobs.intValue();
    }

    Number maxDexPoolSize = (Number) cl.getParsedOptionValue("max-dex-pool-size");
    if (maxDexPoolSize != null)
        config.maxDexPoolSize = maxDexPoolSize.intValue();

    config.annotationPackage = cl.getOptionValue("annotations", Context.DEFAULT_ANNOTATION_PACKAGE);
    config.dexTagSupported = cl.hasOption("compat-dextag");

    config.logLevel = WARN;
    if (cl.hasOption("quiet"))
        config.logLevel = ERROR;
    if (cl.hasOption("verbose"))
        config.logLevel = INFO;
    if (cl.hasOption("debug"))
        config.logLevel = DEBUG;

    if (cl.hasOption("path"))
        config.sourceCodeRoot = "";
    config.sourceCodeRoot = cl.getOptionValue("path-root", config.sourceCodeRoot);
    config.timingStats = cl.hasOption("stats");

    config.dryRun = cl.hasOption("dry-run");

    return config;

}

From source file:com.github.cereda.arara.langchecker.LanguageUtils.java

/**
 * Parses the command line arguments.//from   ww w  .j a  va 2s.c  o m
 * @param arguments An array containing the command line arguments.
 * @return A pair containing a boolean value and the file reference.
 */
public static File parse(String[] arguments) {

    // command line options
    Options options = new Options();

    try {

        // create the parse
        DefaultParser parser = new DefaultParser();
        CommandLine line = parser.parse(options, arguments);

        // check if there is a
        // file for reference
        if (line.getArgList().size() != 1) {
            throw new ParseException("Quack");
        }

        // return the file
        return new File(line.getArgList().get(0));

    } catch (ParseException exception) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("langchecker file", options);
        System.exit(1);
    }

    // never reach it
    return null;

}

From source file:com.xafero.vee.cmd.MainApp.java

private static void process(CommandLine line, Options options) throws ScriptException, IOException {
    if (line.hasOption('?')) {
        printHelp(options);/*  w w  w  .  ja v a  2s  .  c  o  m*/
        return;
    }
    if (line.hasOption('v')) {
        printVersion();
        return;
    }
    if (line.hasOption('l')) {
        printLanguages();
        return;
    }
    if (line.hasOption('e')) {
        execute(line.getOptionValue('e'));
        return;
    }
    throw new UnsupportedOperationException("Unrecognized option: " + line.getArgList());
}

From source file:brut.apktool.Main.java

private static void cmdDecode(CommandLine cli) throws AndrolibException {
    ApkDecoder decoder = new ApkDecoder();

    int paraCount = cli.getArgList().size();
    String apkName = (String) cli.getArgList().get(paraCount - 1);
    File outDir = null;//  w w  w  .  j  a v a2 s . c  o m

    // check for options
    if (cli.hasOption("s") || cli.hasOption("no-src")) {
        decoder.setDecodeSources(ApkDecoder.DECODE_SOURCES_NONE);
    }
    if (cli.hasOption("d") || cli.hasOption("debug")) {
        decoder.setDebugMode(true);
    }
    if (cli.hasOption("debug-line-prefix")) {
        decoder.setDebugLinePrefix(cli.getOptionValue("debug-line-prefix"));
    }
    if (cli.hasOption("b") || cli.hasOption("no-debug-info")) {
        decoder.setBaksmaliDebugMode(false);
    }
    if (cli.hasOption("t") || cli.hasOption("frame-tag")) {
        decoder.setFrameworkTag(cli.getOptionValue("t"));
    }
    if (cli.hasOption("f") || cli.hasOption("force")) {
        decoder.setForceDelete(true);
    }
    if (cli.hasOption("r") || cli.hasOption("no-res")) {
        decoder.setDecodeResources(ApkDecoder.DECODE_RESOURCES_NONE);
    }
    if (cli.hasOption("k") || cli.hasOption("keep-broken-res")) {
        decoder.setKeepBrokenResources(true);
    }
    if (cli.hasOption("p") || cli.hasOption("frame-path")) {
        decoder.setFrameworkDir(cli.getOptionValue("p"));
    }
    if (cli.hasOption("m") || cli.hasOption("match-original")) {
        decoder.setAnalysisMode(true, false);
    }
    if (cli.hasOption("api")) {
        decoder.setApi(Integer.parseInt(cli.getOptionValue("api")));
    }
    if (cli.hasOption("o") || cli.hasOption("output")) {
        outDir = new File(cli.getOptionValue("o"));
        decoder.setOutDir(outDir);
    } else {

        // make out folder manually using name of apk
        String outName = apkName;
        outName = outName.endsWith(".apk") ? outName.substring(0, outName.length() - 4) : outName + ".out";

        // make file from path
        outName = new File(outName).getName();
        outDir = new File(outName);
        decoder.setOutDir(outDir);
    }

    decoder.setApkFile(new File(apkName));

    try {
        decoder.decode();
    } catch (OutDirExistsException ex) {
        System.err.println("Destination directory (" + outDir.getAbsolutePath() + ") "
                + "already exists. Use -f switch if you want to overwrite it.");
        System.exit(1);
    } catch (InFileNotFoundException ex) {
        System.err.println("Input file (" + apkName + ") " + "was not found or was not readable.");
        System.exit(1);
    } catch (CantFindFrameworkResException ex) {
        System.err.println("Can't find framework resources for package of id: " + String.valueOf(ex.getPkgId())
                + ". You must install proper " + "framework files, see project website for more info.");
        System.exit(1);
    } catch (IOException ex) {
        System.err.println("Could not modify file. Please ensure you have permission.");
        System.exit(1);
    } catch (DirectoryException ex) {
        System.err.println("Could not modify internal dex files. Please ensure you have permission.");
        System.exit(1);
    }

}

From source file:com.github.cereda.arara.rulechecker.RuleUtils.java

/**
 * Parses the command line arguments.//ww  w  .j av  a 2 s.  com
 * @param arguments An array containing the command line arguments.
 * @return A pair containing a boolean value and the file reference.
 */
public static Pair<Boolean, File> parse(String[] arguments) {

    // command line options
    Options options = new Options();
    options.addOption("r", "release", false, "update rules for release");

    try {

        // create the parse
        DefaultParser parser = new DefaultParser();
        CommandLine line = parser.parse(options, arguments);

        // check if it is a release
        boolean release = line.hasOption("release");

        // check if there is a
        // file for reference
        if (line.getArgList().size() != 1) {
            throw new ParseException("Quack");
        }

        // provide the resulting pair
        Pair<Boolean, File> result = new Pair<>();
        result.setFirst(release);
        result.setSecond(new File(line.getArgList().get(0)));
        return result;

    } catch (ParseException exception) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("rulechecker [ --release ] file", options);
        System.exit(1);
    }

    // never reach it
    return null;
}

From source file:com.apkTool.Main.java

private static void cmdDecode(CommandLine cli) throws AndrolibException {
    // ??/*  www .j  a  v  a  2s .  c om*/
    ApkDecoder decoder = new ApkDecoder();

    int paraCount = cli.getArgList().size();
    String apkName = (String) cli.getArgList().get(paraCount - 1);
    File outDir;

    // check for options
    if (cli.hasOption("s") || cli.hasOption("no-src")) {
        decoder.setDecodeSources(ApkDecoder.DECODE_SOURCES_NONE);
    }
    if (cli.hasOption("d") || cli.hasOption("debug")) {
        System.err.println(
                "SmaliDebugging has been removed in 2.1.0 onward. Please see: https://github.com/iBotPeaches/Apktool/issues/1061");
        System.exit(1);
    }
    if (cli.hasOption("b") || cli.hasOption("no-debug-info")) {
        decoder.setBaksmaliDebugMode(false);
    }
    if (cli.hasOption("t") || cli.hasOption("frame-tag")) {
        decoder.setFrameworkTag(cli.getOptionValue("t"));
    }
    if (cli.hasOption("f") || cli.hasOption("force")) {
        decoder.setForceDelete(true);
    }
    if (cli.hasOption("r") || cli.hasOption("no-res")) {
        decoder.setDecodeResources(ApkDecoder.DECODE_RESOURCES_NONE);
    }
    if (cli.hasOption("k") || cli.hasOption("keep-broken-res")) {
        decoder.setKeepBrokenResources(true);
    }
    if (cli.hasOption("p") || cli.hasOption("frame-path")) {
        decoder.setFrameworkDir(cli.getOptionValue("p"));
    }
    if (cli.hasOption("m") || cli.hasOption("match-original")) {
        decoder.setAnalysisMode(true, false);
    }
    if (cli.hasOption("api")) {
        decoder.setApi(Integer.parseInt(cli.getOptionValue("api")));
    }
    if (cli.hasOption("o") || cli.hasOption("output")) {
        outDir = new File(cli.getOptionValue("o"));
        decoder.setOutDir(outDir);
    } else {

        // make out folder manually using name of apk
        String outName = apkName;
        outName = outName.endsWith(".apk") ? outName.substring(0, outName.length() - 4).trim()
                : outName + ".out";

        // make file from path
        outName = new File(outName).getName();
        outDir = new File(outName);
        decoder.setOutDir(outDir);
    }

    decoder.setApkFile(new File(apkName));

    try {
        decoder.decode();
    } catch (OutDirExistsException ex) {
        System.err.println("Destination directory (" + outDir.getAbsolutePath() + ") "
                + "already exists. Use -f switch if you want to overwrite it.");
        System.exit(1);
    } catch (InFileNotFoundException ex) {
        System.err.println("Input file (" + apkName + ") " + "was not found or was not readable.");
        System.exit(1);
    } catch (CantFindFrameworkResException ex) {
        System.err.println("Can't find framework resources for package of id: " + String.valueOf(ex.getPkgId())
                + ". You must install proper " + "framework files, see project website for more info.");
        System.exit(1);
    } catch (IOException ex) {
        System.err.println("Could not modify file. Please ensure you have permission.");
        System.exit(1);
    } catch (DirectoryException ex) {
        System.err.println("Could not modify internal dex files. Please ensure you have permission.");
        System.exit(1);
    }
}

From source file:groovy.ui.GroovyMain.java

/**
 * Process the users request./*ww w  . ja  va2  s . com*/
 *
 * @param line the parsed command line.
 * @throws ParseException if invalid options are chosen
 */
private static boolean process(CommandLine line) throws ParseException, IOException {
    List args = line.getArgList();

    if (line.hasOption('D')) {
        String[] values = line.getOptionValues('D');

        for (int i = 0; i < values.length; i++) {
            setSystemPropertyFrom(values[i]);
        }
    }

    GroovyMain main = new GroovyMain();

    // add the ability to parse scripts with a specified encoding
    main.conf.setSourceEncoding(line.getOptionValue('c', main.conf.getSourceEncoding()));

    main.isScriptFile = !line.hasOption('e');
    main.debug = line.hasOption('d');
    main.conf.setDebug(main.debug);
    main.processFiles = line.hasOption('p') || line.hasOption('n');
    main.autoOutput = line.hasOption('p');
    main.editFiles = line.hasOption('i');
    if (main.editFiles) {
        main.backupExtension = line.getOptionValue('i');
    }
    main.autoSplit = line.hasOption('a');
    String sp = line.getOptionValue('a');
    if (sp != null)
        main.splitPattern = sp;

    if (main.isScriptFile) {
        if (args.isEmpty())
            throw new ParseException("neither -e or filename provided");

        main.script = (String) args.remove(0);
        if (main.script.endsWith(".java"))
            throw new ParseException("error: cannot compile file with .java extension: " + main.script);
    } else {
        main.script = line.getOptionValue('e');
    }

    main.processSockets = line.hasOption('l');
    if (main.processSockets) {
        String p = line.getOptionValue('l', "1960"); // default port to listen to
        main.port = Integer.parseInt(p);
    }

    // we use "," as default, because then split will create
    // an empty array if no option is set
    String disabled = line.getOptionValue("disableopt", ",");
    String[] deopts = disabled.split(",");
    for (String deopt_i : deopts) {
        main.conf.getOptimizationOptions().put(deopt_i, false);
    }

    if (line.hasOption("indy")) {
        CompilerConfiguration.DEFAULT.getOptimizationOptions().put("indy", true);
        main.conf.getOptimizationOptions().put("indy", true);
    }

    if (line.hasOption("basescript")) {
        main.conf.setScriptBaseClass(line.getOptionValue("basescript"));
    }

    if (line.hasOption("configscript")) {
        String path = line.getOptionValue("configscript");
        File groovyConfigurator = new File(path);
        Binding binding = new Binding();
        binding.setVariable("configuration", main.conf);

        CompilerConfiguration configuratorConfig = new CompilerConfiguration();
        ImportCustomizer customizer = new ImportCustomizer();
        customizer
                .addStaticStars("org.codehaus.groovy.control.customizers.builder.CompilerCustomizationBuilder");
        configuratorConfig.addCompilationCustomizers(customizer);

        GroovyShell shell = new GroovyShell(binding, configuratorConfig);
        shell.evaluate(groovyConfigurator);
    }

    main.args = args;

    return main.run();
}

From source file:groovyx.groovyserv.GroovyMain2.java

/**
 * Process the users request.//  w  w w  .  j ava  2  s.  c o m
 *
 * @param line the parsed command line.
 * @throws ParseException if invalid options are chosen
 */
private static boolean process(CommandLine line, String classpath) throws ParseException, IOException { // for GroovyServ
    List args = line.getArgList();

    if (line.hasOption('D')) {
        String[] values = line.getOptionValues('D');

        for (int i = 0; i < values.length; i++) {
            setSystemPropertyFrom(values[i]);
        }
    }

    GroovyMain2 main = new GroovyMain2();

    // add the ability to parse scripts with a specified encoding
    main.conf.setSourceEncoding(line.getOptionValue('c', main.conf.getSourceEncoding()));

    main.isScriptFile = !line.hasOption('e');
    main.debug = line.hasOption('d');
    main.conf.setDebug(main.debug);
    main.processFiles = line.hasOption('p') || line.hasOption('n');
    main.autoOutput = line.hasOption('p');
    main.editFiles = line.hasOption('i');
    if (main.editFiles) {
        main.backupExtension = line.getOptionValue('i');
    }
    main.autoSplit = line.hasOption('a');
    String sp = line.getOptionValue('a');
    if (sp != null)
        main.splitPattern = sp;

    if (main.isScriptFile) {
        if (args.isEmpty())
            throw new ParseException("neither -e or filename provided");

        main.script = (String) args.remove(0);
        if (main.script.endsWith(".java"))
            throw new ParseException("error: cannot compile file with .java extension: " + main.script);
    } else {
        main.script = line.getOptionValue('e');
    }

    main.processSockets = line.hasOption('l');
    if (main.processSockets) {
        String p = line.getOptionValue('l', "1960"); // default port to listen to
        main.port = Integer.parseInt(p);
    }

    // we use "," as default, because then split will create
    // an empty array if no option is set
    String disabled = line.getOptionValue("disableopt", ",");
    String[] deopts = disabled.split(",");
    for (String deopt_i : deopts) {
        main.conf.getOptimizationOptions().put(deopt_i, false);
    }

    if (line.hasOption("indy")) {
        CompilerConfiguration.DEFAULT.getOptimizationOptions().put("indy", true);
        main.conf.getOptimizationOptions().put("indy", true);
    }

    if (line.hasOption("basescript")) {
        main.conf.setScriptBaseClass(line.getOptionValue("basescript"));
    }

    if (line.hasOption("configscript")) {
        String path = line.getOptionValue("configscript");
        File groovyConfigurator = new File(path);
        Binding binding = new Binding();
        binding.setVariable("configuration", main.conf);

        CompilerConfiguration configuratorConfig = new CompilerConfiguration();
        ImportCustomizer customizer = new ImportCustomizer();
        customizer
                .addStaticStars("org.codehaus.groovy.control.customizers.builder.CompilerCustomizationBuilder");
        configuratorConfig.addCompilationCustomizers(customizer);

        GroovyShell shell = new GroovyShell(binding, configuratorConfig);
        shell.evaluate(groovyConfigurator);
    }

    main.args = args;

    // for GroovyServ: classpath is given by GroovyInvokeHandler
    if (classpath != null) {
        main.conf.setClasspath(classpath);
    }

    return main.run();
}

From source file:Dcm2Txt.java

private static CommandLine parse(String[] args) {
    Options opts = new Options();
    Option width = new Option("w", "width", true, "maximal number of characters per line, by default: 80");
    width.setArgName("max");
    opts.addOption(width);//  w  w w  .j ava 2  s. com
    Option vallen = new Option("l", "vallen", true,
            "limit value prompt to <maxlen> characters, by default: 64");
    vallen.setArgName("max");
    opts.addOption(vallen);
    opts.addOption("c", "compact", false, "dump without attribute names");
    opts.addOption("h", "help", false, "print this message");
    opts.addOption("V", "version", false, "print the version information and exit");
    CommandLine cl = null;
    try {
        cl = new PosixParser().parse(opts, args);
    } catch (ParseException e) {
        exit("dcm2txt: " + e.getMessage());
        throw new RuntimeException("unreachable");
    }
    if (cl.hasOption('V')) {
        Package p = Dcm2Txt.class.getPackage();
        System.out.println("dcm2txt v" + p.getImplementationVersion());
        System.exit(0);
    }
    if (cl.hasOption('h') || cl.getArgList().isEmpty()) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(USAGE, DESCRIPTION, opts, EXAMPLE);
        System.exit(0);
    }
    return cl;
}