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

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

Introduction

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

Prototype

public String getValue() 

Source Link

Document

Returns the specified value of this Option or null if there is no value.

Usage

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);//from  ww  w  . j a v a2  s. c  o m
    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.ldaptive.cli.AbstractCli.java

/**
 * Reads the options from the supplied command line and returns a properties
 * containing those options.//from w ww. j a  va 2s.c  o  m
 *
 * @param  domain  to place property names in
 * @param  line  command line
 *
 * @return  properties for each option and value
 */
protected Properties getPropertiesFromOptions(final String domain, final CommandLine line) {
    final Properties props = new Properties();
    for (Option o : line.getOptions()) {
        if (o.hasArg()) {
            // if provider property, split the value
            // else add the domain to the ldaptive properties
            if (o.getOpt().equals(OPT_PROVIDER_PROPERTIES)) {
                final String[] s = o.getValue().split("=");
                props.setProperty(s[0], s[1]);
            } else {
                props.setProperty(domain + o.getOpt(), o.getValue());
            }
        }
    }
    return props;
}

From source file:org.mitre.ccv.mapred.CompleteCompositionVectors.java

/**
 *
 * The JSO data will be the same as {@link org.mitre.ccv.CompleteMatrix#jsonCompleteMatrix}, but the features
 * will be in a different order. This version, by default sorts, only by entropy values, whereas the
 * ccv in-memory version sorts by the k-mer natural order (i.e., lexigraphic).
 * @param argv//w w w.  ja  va 2  s  . c om
 * @return
 * @throws java.lang.Exception
 */
@Override
@SuppressWarnings("static-access") // For OptionBuilder
public int run(String[] argv) throws Exception {
    JobConf conf = new JobConf(getConf());
    String cli_title = "CompleteCompositionVectorHadoop";

    int start = CalculateKmerCounts.DEFAULT_START;
    int end = CalculateKmerCounts.DEFAULT_END;
    int topkmers = 0;

    String input = null;
    String output = null;
    String vectorJsonOutput = null;
    //String kmerJsonOutput = null;

    boolean cleanLogs = false;

    /** create the Options */
    Options options = new Options();

    /** Hadoop Options */
    options.addOption(
            OptionBuilder.withArgName("number").hasArg(true).withDescription("number of maps").create("m"));
    options.addOption(
            OptionBuilder.withArgName("number").hasArg(true).withDescription("number of reducers").create("r"));

    // org.hadoop.util.GenericOptionsParser should captures this, but it doesn't
    options.addOption(OptionBuilder.withArgName("property=value").hasArg(true).withValueSeparator()
            .withDescription("use value for given property").create("D"));

    /** CompleteCompositionVector Options */
    options.addOption(OptionBuilder.withArgName("number").hasArg(true)
            .withDescription("number of top k-mers to use in calculations").create("topKmers"));
    options.addOption(OptionBuilder.withArgName("start").hasArg(true).withDescription("starting length of tile")
            .create("start"));
    options.addOption(OptionBuilder.withArgName("end").hasArg(true).withDescription("ending length of title")
            .create("end"));
    options.addOption(OptionBuilder.hasArg(true).withArgName("file")
            .withDescription("JSON file to write out k-mers to").create("kmersfile"));

    options.addOption(OptionBuilder.hasArg(true).withArgName("file")
            .withDescription("JSON file to write out feature vectors to "
                    + "(Overrides kmersout, only one file will be written).")
            .create("vectorsfile"));

    options.addOption(OptionBuilder.withArgName("number").hasArg(true)
            .withDescription("What preference to use: 0-min 1-median 2-avg(min,med): default is median")
            .create("prefval"));

    options.addOption(OptionBuilder.withArgName("help").hasArg(false).withDescription("print this message")
            .create("help"));

    // automatically generate the help statement
    HelpFormatter formatter = new HelpFormatter();

    //GenericOptionsParser gop = new GenericOptionsParser(conf, options, argv);
    GenericOptionsParser gop = new GenericOptionsParser(conf, argv);

    String[] remaining_args = gop.getRemainingArgs();

    // create the parser
    CommandLineParser parser = new GnuParser();
    //CommandLine line = gop.getCommandLine();
    String[] other_args = new String[] {};

    try {
        CommandLine line = parser.parse(options, remaining_args);
        other_args = line.getArgs();

        // Make sure there is a parameter left.
        if (other_args.length == 0) {
            System.out.println(cli_title);
            System.out.println("Missing input path!");
            formatter.printHelp("hccv [options] <input> [<output>] ", options);
            GenericOptionsParser.printGenericCommandUsage(System.out);
            return -1;
        }

        Option[] opts = line.getOptions();
        if (line.hasOption("help")) {
            System.out.println(cli_title);
            formatter.printHelp("hccv [options] <input> [<output>] ", options);
            GenericOptionsParser.printGenericCommandUsage(System.out);
            return -1;
        }

        // could also use line.iterator()
        for (Option opt : opts) {
            if (opt.getOpt().equals("m")) {
                conf.setNumMapTasks(Integer.parseInt(opt.getValue()));
            }
            if (opt.getOpt().equals("r")) {
                conf.setNumReduceTasks(Integer.parseInt(opt.getValue()));
            }
            if (opt.getOpt().equals("D")) {
                // We can have multiple properties we want to set
                String[] properties = opt.getValues();
                for (String property : properties) {
                    String[] keyval = property.split("=");
                    conf.set(keyval[0], keyval[1]);
                }
            }
            if (opt.getOpt().equals("start")) {
                start = Integer.parseInt(opt.getValue());
            }
            if (opt.getOpt().equals("end")) {
                end = Integer.parseInt(opt.getValue());
            }
            if (opt.getOpt().equals("topKmers")) {
                topkmers = Integer.parseInt(opt.getValue());
            }
            if (opt.getOpt().equals("vectorsfile")) {
                vectorJsonOutput = opt.getValue();
            }
        }
    } catch (ParseException e) {
        LOG.warn("options parsing faild: " + e.getMessage());
        System.out.println(cli_title);
        formatter.printHelp("hccv [options] <input> [<output>] ", options);
        GenericOptionsParser.printGenericCommandUsage(System.out);
    }
    if (start <= 2) {
        throw new IllegalArgumentException("Value of 'start' argument must be larger than 2");
    }

    input = other_args[0];
    if (other_args.length < 2) {
        output = input + "_" + FileUtils.getSimpleDate();
    } else {
        output = other_args[2];
    }

    /**
     * Check output path. Either needs to exist as a directory or not exist
     */
    Path outputPath = new Path(output);
    FileSystem fs = outputPath.getFileSystem(conf);
    if (!fs.exists(outputPath)) {
        fs.mkdirs(outputPath);
    } else if (fs.exists(outputPath) || !fs.getFileStatus(outputPath).isDir()) {
        LOG.fatal(String.format("Output directory %s already exists", outputPath.makeQualified(fs)));
        throw new FileAlreadyExistsException(
                String.format("Output directory %s already exists", outputPath.makeQualified(fs)));
    }

    String outputDir = output + Path.SEPARATOR;

    int res;
    /**
     * Zero, CalculateCompositionVectors
     */
    LOG.info("Starting CalculateCompositionVectors Map-Reduce job");
    CalculateCompositionVectors cv = new CalculateCompositionVectors();
    res = cv.initJob(conf, start, end, input, outputDir + COMPOSITION_VECTORS, cleanLogs);
    if (res != 0) {
        LOG.info("CalculateCompositionVectors returned non-zero result!");
        return res;
    }
    // We can stop now or continue to reduce dimensionallity using RRE or other means

    /**
     * First, CalculateKmerCounts
     */
    LOG.info("Starting CalculateKmerCounts Map-Reduce job");
    // FastMap option for CalculateKmers!?!
    CalculateKmerCounts ckc = new CalculateKmerCounts();
    res = ckc.initJob(conf, start, end, input, outputDir + KMER_COUNTS);
    if (res != 0) {
        LOG.fatal("CalculateKmerCounts returned non-zero result!");
        return res;
    }

    /**
     * Second, TotalSequenceLength
     */
    LOG.info("Starting TotalSequenceLength Map-Reduce job");
    TotalSequenceLength tsl = new TotalSequenceLength();
    res = tsl.initJob(conf, input, outputDir + TOTAL_LENGTH, cleanLogs);
    if (res != 0) {
        LOG.fatal("TotalSequenceLength returned non-zero result!");
        return res;
    }
    int length = tsl.getCount(conf, outputDir + TOTAL_LENGTH);

    if (length < 3) {
        LOG.fatal("TotalSequenceLength returned a total sequence length of less than 3.");
        return -1;
    } else {
        LOG.info(String.format("TotalSequenceLength returned a total sequence length of %d.", length));
    }

    /**
     * Third, CalculateKmerProbabilities
     */
    LOG.info("Starting CalculateKmerProbabilities Map-Reduce job");
    CalculateKmerProbabilities ckp = new CalculateKmerProbabilities();
    res = ckp.initJob(conf, start, end, length, outputDir + KMER_COUNTS, outputDir + KMER_PROBABILITIES,
            cleanLogs);
    if (res != 0) {
        LOG.fatal("CalculateKmerProbabilities returned non-zero result!");
        return res;
    }

    /**
     * Fourth, InvertKmerProbabilities
     */
    LOG.info("Starting InvertKmerProbabilities Map-Reduce job");
    InvertKmerProbabilities ikp = new InvertKmerProbabilities();
    res = ikp.initJob(conf, outputDir + KMER_PROBABILITIES, outputDir + INVERTED_KMER_PROBABILITIES, cleanLogs);
    if (res != 0) {
        LOG.fatal("InvertKmerProbabilities returned non-zero result!");
        return res;
    }

    /**
     * Fifth, CalculateKmerPiValues
     */
    LOG.info("Starting CalculateKmerPiValues Map-Reduce job");
    CalculateKmerPiValues kpv = new CalculateKmerPiValues();
    res = kpv.initJob(conf, start, end, outputDir + INVERTED_KMER_PROBABILITIES, outputDir + KMER_PI_VALUES,
            cleanLogs);
    if (res != 0) {
        LOG.fatal("CalculateKmerPiValues returned non-zero result!");
        return res;
    }

    /**
     * Sixth,CalculateKmerRevisedRelativeEntropy
     */
    LOG.info("Starting CalculateKmerRevisedRelativeEntropy Map-Reduce job");
    CalculateKmerRevisedRelativeEntropy krre = new CalculateKmerRevisedRelativeEntropy();
    res = krre.initJob(conf, outputDir + KMER_PI_VALUES, outputDir + COMPOSITION_VECTORS,
            outputDir + ENTROPY_VALUES, cleanLogs);
    if (res != 0) {
        LOG.fatal("CalculateKmerRevisedRelativeEntropy returned non-zero result!");
        return res;
    }

    /**
     * Seventh, SortKmerRevisedRelativeEntropies
     */
    SortKmerRevisedRelativeEntropies srre = new SortKmerRevisedRelativeEntropies();
    res = srre.initJob(conf, outputDir + ENTROPY_VALUES, outputDir + SORTED_ENTROPY_VALUES, cleanLogs);
    if (res != 0) {
        LOG.fatal("SortKmerRevisedRelativeEntropies returned non-zero result!");
        return res;
    }

    /**
     * Eigth, GenerateFeatureVectors
     *
     * Generate a flatten list to add to the cache to be distributed to the map-tasks.
     */
    Path listOutputPath = new Path(outputDir + Integer.toString(topkmers) + KMER_ENTROPY_SET);
    LOG.info(String.format("Loading %d sorted k-mers from %s to %s", topkmers,
            outputDir + SORTED_ENTROPY_VALUES, listOutputPath.toString()));
    int num = CompleteCompositionVectorUtils.flattenKmerEntropySequenceFile(conf, topkmers,
            outputDir + SORTED_ENTROPY_VALUES, listOutputPath.toString(), cleanLogs);

    if (num != topkmers) {
        LOG.fatal(String.format("Requested %d k-mers, but got %d. Using %d", topkmers, num, num));
        topkmers = num;
    }
    GenerateFeatureVectors fv = new GenerateFeatureVectors();
    res = fv.initJob(conf, listOutputPath.toString(), topkmers, outputDir + COMPOSITION_VECTORS,
            outputDir + FEATURE_VECTORS, cleanLogs);
    if (res != 0) {
        LOG.fatal("GenerateFeatureVectors returned non-zero result!");
        return res;
    }

    /**
     * Save feature vectors, features (k-mers), and properties to a JSON file.
     *
     * The data will be the same as {@link org.mitre.ccv.CompleteMatrix#jsonCompleteMatrix}, but the features
     * will be in a different order. This version, by default sorts, only by entropy values, whereas the
     * ccv in-memory version sorts by the k-mer natural order (i.e., lexigraphic).
     */
    if (vectorJsonOutput != null && vectorJsonOutput.length() > 0) {
        LOG.info("Writing features out to " + vectorJsonOutput);
        CompleteCompositionVectorUtils.featureVectors2Json(conf, start, end, topkmers,
                outputDir + SORTED_ENTROPY_VALUES, outputDir + FEATURE_VECTORS, vectorJsonOutput);
    }

    LOG.info("All done generating complete composition vectors and feature vectors.");
    return res;
}

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

public boolean execute(Option opt, ClientContext context) {
    BitwiseStoreUtil bwsUtil = BitwiseStoreUtil.getInstance();

    //Extract name of store to be opened
    String newStoreName = opt.getValue();

    //Make sure the store name exists
    if (!(bwsUtil.exists(newStoreName))) {
        System.out.println("Specified store name doesn't exist.\n");
        return false;
    }// w w w .  ja  v  a  2s.  c  o  m

    //Close the currently opened store
    BitwiseStore currentStore = context.getStore();
    if (!(currentStore == null)) {
        currentStore.endTransaction();
        currentStore.close();
    }

    //Open the new store
    BitwiseStore newStore = bwsUtil.open(newStoreName);
    newStore.startTransaction();
    context.setStore(newStore);

    System.out.println("Switching to store " + newStoreName + "\n");
    return false;
}

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

public boolean execute(Option opt, ClientContext context) throws ParseException {
    String str = opt.getValue();
    try {//from   w  ww.  ja  va2  s  . c  o m
        int index = Integer.valueOf(str);
        BitwiseStore store = context.getStore();
        ResultDisplay rd = new ResultDisplay();
        rd.setDisplayType(ResultDisplay.DisplayType.PLAIN);

        //Filter out template fields
        for (String field : store.getFieldList()) {
            //        if (field.matches(".*_\\d+")) {
            //          continue;
            //        }
            rd.addField(field);
        }

        rd.putRecord(store, index);
        System.out.println(rd.getOutput());
    } catch (NumberFormatException e) {
        throw new ParseException(e.getMessage());
    }
    return false;
}

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

public boolean execute(Option opt, CliContext context) throws ParseException {
    String storeName = opt.getValue();
    if (context.getStore() != null) {
        if (context.getStore().getSampleRecordStore().getStore().getName().equals(storeName + "_samples")) {
            context.getOutput().println("Closing current store.");
            context.getStore().close();/*from   ww  w.  j  av a 2s .c  o  m*/
            context.clear();
        }
    }

    context.getOutput().println("Deleting store " + storeName + ".");
    BitwiseDiskUtil.deleteStores(storeName + "_samples", storeName + "_assays");
    return false;
}

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

public boolean execute(Option opt, CliContext context) throws ParseException {
    String storeName = opt.getValue();
    if (context.getStore() != null) {
        context.getOutput().println("Closing current store.");
        context.getStore().close();/*  ww  w  .  j a  v a 2  s.com*/
    }

    context.clear();
    context.getOutput().println("Opening store " + storeName + ".");
    GenotypingStore<?, ?, ?, ?> store = open(storeName);
    if (store == null) {
        context.getOutput().println("Store " + storeName + " does not exist");
        return false;
    }
    context.setStore(store);
    context.setActiveRecordStore(store.getSampleRecordStore());

    return false;
}

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

public boolean execute(Option opt, CliContext context) {
    String str = opt.getValue();
    QueryExecution qe = context.getHistory().resolveQuery(str);
    if (qe != null) {
        context.getOutput().println("Store: " + qe.getStore().getStore().getName());
        context.getOutput().println("Query: " + qe.getQuery());
        context.getOutput().println("Count: " + qe.count());
        context.getOutput().println("Results: ");
        if (qe.count() > 0) {
            int hits = qe.count();
            QueryResult qr = qe.getResult();
            for (int i = 0; i < hits; i++) {
                int hit = qr.hit(i);
                context.getOutput().print(hit + " ");
            }/*from w  w  w  . ja v  a2s.  co m*/
            context.getOutput().println("");
        } else {
            context.getOutput().println("Query [" + str + "] produced no result. Nothing to print.");
        }
    } else {
        context.getOutput().println("No query result to print. Execute a query first.");
    }
    return false;
}

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

public boolean execute(Option opt, CliContext context) throws ParseException {
    String str = opt.getValue();
    try {/*from w w  w  .ja va  2s . c o m*/
        int index = Integer.valueOf(str);
        GenotypingRecordStore<?, ?, ?> store = context.getActiveRecordStore();
        if (store.getStore().getSize() == 0) {
            context.getOutput().println("Store is empty. To load records, use the --load command.");
        } else if (index < 0 || index >= store.getStore().getSize()) {
            context.getOutput().println(
                    "Record index invalid. Value must be between 0 and " + (store.getStore().getSize() - 1));
        } else {
            context.getOutput().println(store.getRecordManager().load(index));
        }
    } catch (NumberFormatException e) {
        context.getOutput().println("Record index invalid. The argument to this command should be an integer.");
    }
    return false;
}

From source file:org.obiba.illumina.bitwise.client.CreateStoreCommand.java

public boolean execute(Option opt, CliContext context) throws ParseException {

    if (context.getStore() != null) {
        context.getOutput().println("Closing current store.");
        context.getStore().close();// w  ww  .  j av a 2s.c  o  m
        context.clear();
    }

    String name = opt.getValue();
    AnnotationStoreSchemaBuilder schemaBuilder = new AnnotationStoreSchemaBuilder();
    BitwiseStore samples;
    BitwiseStore assays;
    try {
        String samplesName = name + "_samples";
        if (BitwiseStoreUtil.getInstance().exists(samplesName) == true) {
            context.getOutput().println("A store named " + name
                    + " already exists. Either use the existing store or delete it to create a new store with that name.");
            return false;
        }
        context.getOutput().println("Creating store " + name + ".");
        samples = BitwiseStoreUtil.getInstance().create(name + "_samples",
                schemaBuilder.createSchema(Sample.class), 0);
        assays = BitwiseStoreUtil.getInstance().create(name + "_assays",
                schemaBuilder.createSchema(Assay.class), 0);
    } catch (Exception e) {
        context.getOutput()
                .println("An unexpected error occured while creating store [" + name + "]: " + e.getMessage());
        e.printStackTrace(context.getOutput());
        return false;
    }

    context.setStore(new InfiniumGenotypingStore(samples, assays));
    context.setActiveRecordStore(context.getStore().getSampleRecordStore());
    return false;
}