Example usage for org.apache.commons.cli Option getOpt

List of usage examples for org.apache.commons.cli Option getOpt

Introduction

In this page you can find the example usage for org.apache.commons.cli Option getOpt.

Prototype

public String getOpt() 

Source Link

Document

Retrieve the name of this Option.

Usage

From source file:org.jax.haplotype.analysis.EMMAAssociationTest.java

/**
 * the main entry point/*from   w ww .  j  a  v a 2  s  .com*/
 * @param args  command line args
 * @throws IOException
 * @throws IllegalFormatException
 */
public static void main(String[] args) throws IllegalFormatException, IOException {
    // Deal with the options.
    CommandLineParser parser = new GnuParser();
    Options options = new Options();
    CommandLine commandLine = null;

    final Option helpOption;
    {
        helpOption = new Option("help", "Print this help and exit");
        helpOption.setRequired(false);
        options.addOption(helpOption);
    }

    final Option genoFileOption;
    {
        genoFileOption = new Option("genofile", "the genotype file");
        genoFileOption.setRequired(true);
        genoFileOption.setArgs(1);
        genoFileOption.setArgName("file name");
        options.addOption(genoFileOption);
    }

    final Option aAlleleOption;
    {
        aAlleleOption = new Option("aallelecol", "the A allele column # (one-based index)");
        aAlleleOption.setRequired(true);
        aAlleleOption.setArgs(1);
        aAlleleOption.setArgName("column number");
        options.addOption(aAlleleOption);
    }

    final Option bAlleleOption;
    {
        bAlleleOption = new Option("ballelecol", "the B allele column # (one-based index)");
        bAlleleOption.setRequired(true);
        bAlleleOption.setArgs(1);
        bAlleleOption.setArgName("column number");
        options.addOption(bAlleleOption);
    }

    final Option firstGenoColumnOption;
    {
        firstGenoColumnOption = new Option("firstgenocol", "the first genotype column # (one-based index)");
        firstGenoColumnOption.setRequired(true);
        firstGenoColumnOption.setArgs(1);
        firstGenoColumnOption.setArgName("column #");
        options.addOption(firstGenoColumnOption);
    }

    final Option lastGenoColumnOption;
    {
        lastGenoColumnOption = new Option("lastgenocol",
                "[optional] the last genotype column # (one-based index). "
                        + "The default behavior is to assume that all columns after "
                        + "the first genotype column are genotype columns.");
        lastGenoColumnOption.setRequired(false);
        lastGenoColumnOption.setArgs(1);
        lastGenoColumnOption.setArgName("column #");
        options.addOption(lastGenoColumnOption);
    }

    final Option phenoFileOption;
    {
        phenoFileOption = new Option("phenofile", "the phenotype file");
        phenoFileOption.setRequired(true);
        phenoFileOption.setArgs(1);
        phenoFileOption.setArgName("file name");
        options.addOption(phenoFileOption);
    }

    final Option phenoNameOption;
    {
        phenoNameOption = new Option("phenoname", "[optional] the name of the phenotype to scan");
        phenoNameOption.setRequired(false);
        phenoNameOption.setArgs(1);
        phenoNameOption.setArgName("name");
        options.addOption(phenoNameOption);
    }

    final Option sexOption;
    {
        sexOption = new Option("sex",
                "[optional] filter phenotypes by sex. " + "agnostic is the default value.");
        sexOption.setRequired(false);
        sexOption.setArgs(1);
        sexOption.setArgName("agnostic/female/male");
        options.addOption(sexOption);
    }

    final Option outputFileOption;
    {
        outputFileOption = new Option("out", "the file to write scan output to");
        outputFileOption.setRequired(true);
        outputFileOption.setArgs(1);
        outputFileOption.setArgName("file name");
        options.addOption(outputFileOption);
    }

    try {
        commandLine = parser.parse(options, args);

        // See if we just need to print the help options.
        if (commandLine.hasOption(helpOption.getOpt())) {
            HelpFormatter helpFormatter = new HelpFormatter();
            helpFormatter.printHelp("emmascan", options);
        } else {
            final String genoFileName = commandLine.getOptionValue(genoFileOption.getOpt());
            final String aColStr = commandLine.getOptionValue(aAlleleOption.getOpt());
            final String bColStr = commandLine.getOptionValue(bAlleleOption.getOpt());
            final String fstGenoColStr = commandLine.getOptionValue(firstGenoColumnOption.getOpt());
            final String lstGenoColStr = commandLine.getOptionValue(lastGenoColumnOption.getOpt());
            final String phenoFileName = commandLine.getOptionValue(phenoFileOption.getOpt());
            final String phenotype = commandLine.getOptionValue(phenoNameOption.getOpt());
            final String sexStr = commandLine.getOptionValue(sexOption.getOpt());
            final String outFileName = commandLine.getOptionValue(outputFileOption.getOpt());

            final SexFilter sexToScan;
            if (sexStr == null || sexStr.toLowerCase().equals("agnostic")) {
                sexToScan = SexFilter.AGNOSTIC;
            } else if (sexStr.toLowerCase().equals("female")) {
                sexToScan = SexFilter.ALLOW_FEMALE;
            } else if (sexStr.toLowerCase().equals("male")) {
                sexToScan = SexFilter.ALLOW_MALE;
            } else {
                throw new ParseException("sex option cannot be: " + sexStr);
            }

            EMMAAssociationTest emmaTest = new EMMAAssociationTest();
            double[] scanResults = emmaTest.emmaScan(genoFileName, Integer.parseInt(aColStr.trim()) - 1,
                    Integer.parseInt(bColStr.trim()) - 1, Integer.parseInt(fstGenoColStr.trim()) - 1,
                    lstGenoColStr == null ? -1 : Integer.parseInt(lstGenoColStr.trim()), phenoFileName,
                    phenotype, sexToScan);

            PrintStream out = new PrintStream(outFileName);
            out.println("pValue");
            for (int i = 0; i < scanResults.length; i++) {
                out.println(scanResults[i]);
            }
            out.close();
        }
    } catch (ParseException ex) {
        HelpFormatter helpFormatter = new HelpFormatter();
        helpFormatter.printHelp("emmascan", options);

        System.exit(-1);
    }
}

From source file:org.jax.haplotype.analysis.HaplotypeAssociationMappingMain.java

/**
 * the main application function for haplotype association mapping
 * @param args//  ww  w  .  ja v a  2  s.  c o  m
 *          command line arguments
 */
public static void main(String[] args) {
    // Deal with the options.
    CommandLineParser parser = new GnuParser();
    Options options = new Options();
    CommandLine commandLine = null;

    final Option helpOption;
    {
        helpOption = new Option("help", "Print this help and exit");
        helpOption.setRequired(false);
        options.addOption(helpOption);
    }

    final Option designfileOption;
    {
        designfileOption = new Option("designfile", "the analysis design file");
        designfileOption.setRequired(false);
        designfileOption.setArgs(1);
        designfileOption.setArgName("file name");
        options.addOption(designfileOption);
    }

    try {
        commandLine = parser.parse(options, args);

        // See if we just need to print the help options.
        if (commandLine.hasOption(helpOption.getOpt())) {
            HelpFormatter helpFormatter = new HelpFormatter();
            helpFormatter.printHelp("ham-analysis", options);
        } else {
            if (commandLine.hasOption(designfileOption.getOpt())) {
                String fileName = commandLine.getOptionValue(designfileOption.getOpt());

                HaplotypeAssociationMappingMain mainInstance = new HaplotypeAssociationMappingMain();
                mainInstance.setAnalysisDesignFile(fileName);
                mainInstance.performAnalysis();
            } else {
                System.out.println("initialization failed");
                HelpFormatter helpFormatter = new HelpFormatter();
                helpFormatter.printHelp("ham-analysis", options);
            }
        }
    } catch (ParseException ex) {
        LOG.log(Level.SEVERE, "initialization failed", ex);
        HelpFormatter helpFormatter = new HelpFormatter();
        helpFormatter.printHelp("ham-analysis", options);
    }
}

From source file:org.jcryptool.commands.core.HelpCommand.java

/**
 * Recovers the command line form of which a CommandLine object could've originated from. Assumes, that all options
 * have been stated in short form./*from w w w. j  a va2s .c  o m*/
 *
 * @param commandName the name of the command
 * @param cmdLine the CommandLine object to parse
 * @return a command line, which would parse to a CommandLine object equal to the given one.
 */
public static String reverseCommandline(String commandName, CommandLine cmdLine) {
    StringBuilder builder = new StringBuilder();
    builder.append(commandName);
    for (String arg : cmdLine.getArgs()) {
        builder.append(" " + arg); //$NON-NLS-1$
    }

    for (Option option : cmdLine.getOptions()) {
        builder.append(" -" + option.getOpt()); //$NON-NLS-1$
        for (int i = 0; i < option.getArgs(); i++) {
            builder.append(" " + (option.getValue(i).contains(" ") ? "\"" + option.getValue(i) + "\"" //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$//$NON-NLS-4$
                    : option.getValue(i)));
        }
    }

    return builder.toString();
}

From source file:org.jf.baksmali.main.java

/**
 * Run!//from w w w . java  2 s .c  om
 */
public static void main(String[] args) throws IOException {
    Locale locale = new Locale("en", "US");
    Locale.setDefault(locale);

    CommandLineParser parser = new PosixParser();
    CommandLine commandLine;

    try {
        commandLine = parser.parse(options, args);
    } catch (ParseException ex) {
        usage();
        return;
    }

    baksmaliOptions options = new baksmaliOptions();

    boolean disassemble = true;
    boolean doDump = false;
    String dumpFileName = null;
    boolean setBootClassPath = false;

    String[] remainingArgs = commandLine.getArgs();
    Option[] clOptions = commandLine.getOptions();

    for (int i = 0; i < clOptions.length; i++) {
        Option option = clOptions[i];
        String opt = option.getOpt();

        switch (opt.charAt(0)) {
        case 'v':
            version();
            return;
        case '?':
            while (++i < clOptions.length) {
                if (clOptions[i].getOpt().charAt(0) == '?') {
                    usage(true);
                    return;
                }
            }
            usage(false);
            return;
        case 'o':
            options.outputDirectory = commandLine.getOptionValue("o");
            break;
        case 'p':
            options.noParameterRegisters = true;
            break;
        case 'l':
            options.useLocalsDirective = true;
            break;
        case 's':
            options.useSequentialLabels = true;
            break;
        case 'b':
            options.outputDebugInfo = false;
            break;
        case 'd':
            options.bootClassPathDirs.add(option.getValue());
            break;
        case 'f':
            options.addCodeOffsets = true;
            break;
        case 'r':
            String[] values = commandLine.getOptionValues('r');
            int registerInfo = 0;

            if (values == null || values.length == 0) {
                registerInfo = baksmaliOptions.ARGS | baksmaliOptions.DEST;
            } else {
                for (String value : values) {
                    if (value.equalsIgnoreCase("ALL")) {
                        registerInfo |= baksmaliOptions.ALL;
                    } else if (value.equalsIgnoreCase("ALLPRE")) {
                        registerInfo |= baksmaliOptions.ALLPRE;
                    } else if (value.equalsIgnoreCase("ALLPOST")) {
                        registerInfo |= baksmaliOptions.ALLPOST;
                    } else if (value.equalsIgnoreCase("ARGS")) {
                        registerInfo |= baksmaliOptions.ARGS;
                    } else if (value.equalsIgnoreCase("DEST")) {
                        registerInfo |= baksmaliOptions.DEST;
                    } else if (value.equalsIgnoreCase("MERGE")) {
                        registerInfo |= baksmaliOptions.MERGE;
                    } else if (value.equalsIgnoreCase("FULLMERGE")) {
                        registerInfo |= baksmaliOptions.FULLMERGE;
                    } else {
                        usage();
                        return;
                    }
                }

                if ((registerInfo & baksmaliOptions.FULLMERGE) != 0) {
                    registerInfo &= ~baksmaliOptions.MERGE;
                }
            }
            options.registerInfo = registerInfo;
            break;
        case 'c':
            String bcp = commandLine.getOptionValue("c");
            if (bcp != null && bcp.charAt(0) == ':') {
                options.addExtraClassPath(bcp);
            } else {
                setBootClassPath = true;
                options.setBootClassPath(bcp);
            }
            break;
        case 'x':
            options.deodex = true;
            break;
        case 'm':
            options.noAccessorComments = true;
            break;
        case 'a':
            options.apiLevel = Integer.parseInt(commandLine.getOptionValue("a"));
            break;
        case 'j':
            options.jobs = Integer.parseInt(commandLine.getOptionValue("j"));
            break;
        case 'i':
            String rif = commandLine.getOptionValue("i");
            options.setResourceIdFiles(rif);
            break;
        case 'N':
            disassemble = false;
            break;
        case 'D':
            doDump = true;
            dumpFileName = commandLine.getOptionValue("D");
            break;
        case 'I':
            options.ignoreErrors = true;
            break;
        case 'T':
            options.inlineResolver = new CustomInlineMethodResolver(options.classPath,
                    new File(commandLine.getOptionValue("T")));
            break;
        default:
            assert false;
        }
    }

    if (remainingArgs.length != 1) {
        usage();
        return;
    }

    if (options.jobs <= 0) {
        options.jobs = Runtime.getRuntime().availableProcessors();
        if (options.jobs > 6) {
            options.jobs = 6;
        }
    }

    if (options.apiLevel >= 17) {
        options.checkPackagePrivateAccess = true;
    }

    String inputDexFileName = remainingArgs[0];

    File dexFileFile = new File(inputDexFileName);
    if (!dexFileFile.exists()) {
        System.err.println("Can't find the file " + inputDexFileName);
        System.exit(1);
    }

    //Read in and parse the dex file
    DexBackedDexFile dexFile = DexFileFactory.loadDexFile(dexFileFile, options.apiLevel);

    if (dexFile.isOdexFile()) {
        if (!options.deodex) {
            System.err.println("Warning: You are disassembling an odex file without deodexing it. You");
            System.err.println("won't be able to re-assemble the results unless you deodex it with the -x");
            System.err.println("option");
            options.allowOdex = true;
        }
    } else {
        options.deodex = false;
    }

    if (!setBootClassPath && (options.deodex || options.registerInfo != 0)) {
        if (dexFile instanceof DexBackedOdexFile) {
            options.bootClassPathEntries = ((DexBackedOdexFile) dexFile).getDependencies();
        } else {
            options.bootClassPathEntries = getDefaultBootClassPathForApi(options.apiLevel);
        }
    }

    if (options.inlineResolver == null && dexFile instanceof DexBackedOdexFile) {
        options.inlineResolver = InlineMethodResolver
                .createInlineMethodResolver(((DexBackedOdexFile) dexFile).getOdexVersion());
    }

    boolean errorOccurred = false;
    if (disassemble) {
        errorOccurred = !baksmali.disassembleDexFile(dexFile, options);
    }

    if (doDump) {
        if (dumpFileName == null) {
            dumpFileName = commandLine.getOptionValue(inputDexFileName + ".dump");
        }
        dump.dump(dexFile, dumpFileName, options.apiLevel);
    }

    if (errorOccurred) {
        System.exit(1);
    }
}

From source file:org.jf.smali.main.java

/**
 * Run!/*from ww  w.ja v a  2  s . c  o  m*/
 */
public static void main(String[] args) {
    Locale locale = new Locale("en", "US");
    Locale.setDefault(locale);

    CommandLineParser parser = new PosixParser();
    CommandLine commandLine;

    try {
        commandLine = parser.parse(options, args);
    } catch (ParseException ex) {
        usage();
        return;
    }

    int jobs = -1;
    boolean allowOdex = false;
    boolean verboseErrors = false;
    boolean printTokens = false;

    int apiLevel = 15;

    String outputDexFile = "out.dex";

    String[] remainingArgs = commandLine.getArgs();

    Option[] options = commandLine.getOptions();

    for (int i = 0; i < options.length; i++) {
        Option option = options[i];
        String opt = option.getOpt();

        switch (opt.charAt(0)) {
        case 'v':
            version();
            return;
        case '?':
            while (++i < options.length) {
                if (options[i].getOpt().charAt(0) == '?') {
                    usage(true);
                    return;
                }
            }
            usage(false);
            return;
        case 'o':
            outputDexFile = commandLine.getOptionValue("o");
            break;
        case 'x':
            allowOdex = true;
            break;
        case 'a':
            apiLevel = Integer.parseInt(commandLine.getOptionValue("a"));
            break;
        case 'j':
            jobs = Integer.parseInt(commandLine.getOptionValue("j"));
            break;
        case 'V':
            verboseErrors = true;
            break;
        case 'T':
            printTokens = true;
            break;
        default:
            assert false;
        }
    }

    if (remainingArgs.length == 0) {
        usage();
        return;
    }

    try {
        LinkedHashSet<File> filesToProcess = new LinkedHashSet<File>();

        for (String arg : remainingArgs) {
            File argFile = new File(arg);

            if (!argFile.exists()) {
                throw new RuntimeException("Cannot find file or directory \"" + arg + "\"");
            }

            if (argFile.isDirectory()) {
                getSmaliFilesInDir(argFile, filesToProcess);
            } else if (argFile.isFile()) {
                filesToProcess.add(argFile);
            }
        }

        if (jobs <= 0) {
            jobs = Runtime.getRuntime().availableProcessors();
            if (jobs > 6) {
                jobs = 6;
            }
        }

        boolean errors = false;

        final DexBuilder dexBuilder = DexBuilder.makeDexBuilder(apiLevel);
        ExecutorService executor = Executors.newFixedThreadPool(jobs);
        List<Future<Boolean>> tasks = Lists.newArrayList();

        final boolean finalVerboseErrors = verboseErrors;
        final boolean finalPrintTokens = printTokens;
        final boolean finalAllowOdex = allowOdex;
        final int finalApiLevel = apiLevel;
        for (final File file : filesToProcess) {
            tasks.add(executor.submit(new Callable<Boolean>() {
                @Override
                public Boolean call() throws Exception {
                    return assembleSmaliFile(file, dexBuilder, finalVerboseErrors, finalPrintTokens,
                            finalAllowOdex, finalApiLevel);
                }
            }));
        }

        for (Future<Boolean> task : tasks) {
            while (true) {
                try {
                    if (!task.get()) {
                        errors = true;
                    }
                } catch (InterruptedException ex) {
                    continue;
                }
                break;
            }
        }

        executor.shutdown();

        if (errors) {
            System.exit(1);
        }

        dexBuilder.writeTo(new FileDataStore(new File(outputDexFile)));
    } catch (RuntimeException ex) {
        System.err.println("\nUNEXPECTED TOP-LEVEL EXCEPTION:");
        ex.printStackTrace();
        System.exit(2);
    } catch (Throwable ex) {
        System.err.println("\nUNEXPECTED TOP-LEVEL ERROR:");
        ex.printStackTrace();
        System.exit(3);
    }
}

From source file:org.jgap.util.SystemKit.java

/**
 * Prints all available comamnd line options.
 *
 * @param cmd the CommandLine object/* ww  w  . j  a v  a2  s  . c om*/
 * @param options the Options list
 *
 * @author Klaus Meffert
 * @since 3.3.4
 */
public static void printHelp(CommandLine cmd, Options options) {
    if (cmd.hasOption("help")) {
        System.out.println("");
        System.out.println(" Command line options:");
        System.out.println(" ---------------------");
        for (Object opt0 : options.getOptions()) {
            Option opt = (Option) opt0;
            String s = opt.getOpt();
            s = StringKit.fill(s, 20, ' ');
            System.out.println(" " + s + " - " + opt.getDescription());
        }
        System.exit(0);
    }
}

From source file:org.jhub1.agent.run.cli.Params.java

protected void addToOptionsReg(Option option) {
    optionsReg.put(option.getOpt(), option);
}

From source file:org.jruyi.cli.Main.java

private boolean processCommandLines(String[] args) throws Throwable {

    Options options = new Options();
    options.addOption("?", "help", false, null);
    options.addOption("h", "host", true, null);
    options.addOption("p", "port", true, null);
    options.addOption("t", "timeout", true, null);
    options.addOption("f", "file", false, null);

    CommandLine line = new PosixParser().parse(options, args);

    Option[] opts = line.getOptions();
    for (Option option : opts) {
        String opt = option.getOpt();
        if (opt.equals("?")) {
            printHelp();/* www.  j a  v  a  2  s  .  com*/
            return false;
        } else if (opt.equals("h")) {
            String v = option.getValue();
            if (v != null)
                RuyiCli.INST.host(v);
        } else if (opt.equals("p")) {
            String v = option.getValue();
            if (v != null)
                RuyiCli.INST.port(Integer.parseInt(v));
        } else if (opt.equals("t")) {
            String v = option.getValue();
            if (v != null)
                RuyiCli.INST.timeout(Integer.parseInt(v) * 1000);
        } else if (opt.equals("f")) {
            args = line.getArgs();
            if (args == null || args.length < 1)
                System.out.println("Please specify SCRIPT.");
            else
                RuyiCli.INST.run(args);

            return false;
        } else
            throw new Exception("Unknown option: " + option);
    }

    args = line.getArgs();
    if (args == null || args.length < 1)
        return true;

    String command = args[0];
    int n = args.length;
    if (n > 1) {
        StringBuilder builder = new StringBuilder(256);
        builder.append(command);
        for (int i = 1; i < n; ++i)
            builder.append(' ').append(args[i]);
        command = builder.toString();
    }

    RuyiCli.INST.run(command);
    return false;
}

From source file:org.jruyi.launcher.Main.java

private static boolean processCommandLines(String[] args) throws Exception {
    Options options = new Options();
    options.addOption("?", "help", false, null);
    options.addOption("v", "version", false, null);
    Option o = new Option("D", true, null);
    o.setArgs(Option.UNLIMITED_VALUES);
    options.addOption(o);/*  w  ww . j av a 2 s  . c  om*/
    options.addOption("r", "run", true, null);

    CommandLine line = new PosixParser().parse(options, args);

    Option[] opts = line.getOptions();
    for (Option option : opts) {
        String opt = option.getOpt();
        if (opt.equals("?")) {
            printHelp();
            return false;
        } else if (opt.equals("v")) {
            MainHolder.INST.printVersion();
            return false;
        } else if (opt.equals("D")) {
            handleSystemProps(option.getValues());
        } else if (opt.equals("r")) {
            System.setProperty(JRUYI_INST_NAME, option.getValue().trim());
        } else
            throw new Exception("Unknown option: " + option);
    }

    return true;
}

From source file:org.jumpmind.symmetric.AbstractCommandLauncher.java

public void execute(String args[]) {
    PosixParser parser = new PosixParser();
    Options options = new Options();
    buildOptions(options);// w ww. ja  v a2s .com
    try {
        CommandLine line = parser.parse(options, args);

        if (line.hasOption(HELP) || (line.getArgList().contains(HELP)) || ((args == null || args.length == 0)
                && line.getOptions().length == 0 && printHelpIfNoOptionsAreProvided())) {
            printHelp(line, options);
            System.exit(2);
        }

        configureLogging(line);
        configurePropertiesFile(line);

        if (line.getOptions() != null) {
            for (Option option : line.getOptions()) {
                log.info("Option: name={}, value={}",
                        new Object[] { option.getLongOpt() != null ? option.getLongOpt() : option.getOpt(),
                                ArrayUtils.toString(option.getValues()) });
            }
        }

        executeWithOptions(line);

    } catch (ParseException e) {
        System.err.println(e.getMessage());
        printUsage(options);
        System.exit(4);
    } catch (Exception e) {
        System.err.println("-------------------------------------------------------------------------------");
        System.err.println("An exception occurred.  Please see the following for details:");
        System.err.println("-------------------------------------------------------------------------------");

        ExceptionUtils.printRootCauseStackTrace(e, System.err);
        System.err.println("-------------------------------------------------------------------------------");
        System.exit(1);
    }
}