Example usage for org.apache.commons.cli Options addOption

List of usage examples for org.apache.commons.cli Options addOption

Introduction

In this page you can find the example usage for org.apache.commons.cli Options addOption.

Prototype

public Options addOption(String opt, String longOpt, boolean hasArg, String description) 

Source Link

Document

Add an option that contains a short-name and a long-name.

Usage

From source file:net.anthonypoon.ngram.rollingregression.Main.java

public static void main(String[] args) throws Exception {
    Options options = new Options();
    options.addOption("a", "action", true, "Action");
    options.addOption("i", "input", true, "input");
    options.addOption("o", "output", true, "output");
    //options.addOption("f", "format", true, "Format");
    options.addOption("u", "upbound", true, "Year up bound");
    options.addOption("l", "lowbound", true, "Year low bound");
    options.addOption("r", "range", true, "Range");
    options.addOption("T", "threshold", true, "Threshold - min count for regression");
    options.addOption("p", "positive-only", false, "Write positive slope only"); // default faluse
    CommandLineParser parser = new GnuParser();
    CommandLine cmd = parser.parse(options, args);
    Configuration conf = new Configuration();
    if (cmd.hasOption("range")) {
        conf.set("range", cmd.getOptionValue("range"));
    }/*  w w  w  .  j ava 2  s  .  c om*/
    if (cmd.hasOption("upbound")) {
        conf.set("upbound", cmd.getOptionValue("upbound"));
    } else {
        conf.set("upbound", "9999");
    }
    if (cmd.hasOption("lowbound")) {
        conf.set("lowbound", cmd.getOptionValue("lowbound"));
    } else {
        conf.set("lowbound", "0");
    }
    if (cmd.hasOption("threshold")) {
        conf.set("threshold", cmd.getOptionValue("threshold"));
    }
    if (cmd.hasOption("positive-only")) {
        conf.set("positive-only", "true");
    }
    Job job = Job.getInstance(conf);
    /**
    if (cmd.hasOption("format")) {
    switch (cmd.getOptionValue("format")) {
        case "compressed":
            job.setInputFormatClass(SequenceFileAsTextInputFormat.class);
            break;
        case "text":
            job.setInputFormatClass(KeyValueTextInputFormat.class);
            break;
    }
            
    }**/
    job.setJarByClass(Main.class);
    switch (cmd.getOptionValue("action")) {
    case "get-regression":
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(Text.class);
        for (String inputPath : cmd.getOptionValue("input").split(",")) {
            MultipleInputs.addInputPath(job, new Path(inputPath), KeyValueTextInputFormat.class,
                    RollingRegressionMapper.class);
        }
        job.setReducerClass(RollingRegressionReducer.class);
        break;
    default:
        throw new IllegalArgumentException("Missing action");
    }

    String timestamp = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss").format(new Date());

    //FileInputFormat.setInputPaths(job, new Path(cmd.getOptionValue("input")));
    FileOutputFormat.setOutputPath(job, new Path(cmd.getOptionValue("output") + "/" + timestamp));
    System.exit(job.waitForCompletion(true) ? 0 : 1);
    /**
    double[] nazismBaseLine = {3, 12, 12, 18, 233, 239, 386, 333, 593, 1244, 1925, 3013, 3120, 3215, 3002, 3355, 2130, 1828, 1406, 1751, 1433, 1033, 881, 1330, 1029, 760, 1288, 1013, 1014};
    InputStream inStream = Main.class.getResourceAsStream("/1g-matrix.txt");
    BufferedReader br = new BufferedReader(new InputStreamReader(inStream));
    String line = "";
    Map<String, Double> result = new HashMap();
    while ((line = br.readLine()) != null) {
    String[] strArray = line.split("\t");
    double[] compareArray = new double[nazismBaseLine.length];
    for (int i = 0; i < nazismBaseLine.length; i ++) {
        compareArray[i] = Double.valueOf(strArray[i + 24]);
    }
    result.put(strArray[0], new PearsonsCorrelation().correlation(nazismBaseLine, compareArray));
    }
    List<Map.Entry<String, Double>> toBeSorted = new ArrayList();
    for (Map.Entry pair : result.entrySet()) {
    toBeSorted.add(pair);
    }
    Collections.sort(toBeSorted, new Comparator<Map.Entry<String, Double>>(){
    @Override
    public int compare(Map.Entry<String, Double> o1, Map.Entry<String, Double> o2) {
        return o2.getValue().compareTo(o1.getValue());
    }
    });
    for (Map.Entry<String, Double> pair : toBeSorted) {
    if (!Double.isNaN(pair.getValue())) {
        System.out.println(pair.getKey() + "\t" + pair.getValue());
    }
    }**/
}

From source file:edu.cmu.lti.oaqa.knn4qa.apps.BuildInMemFwdIndexApp.java

public static void main(String[] args) {
    Options options = new Options();

    options.addOption(CommonParams.ROOT_DIR_PARAM, null, true, CommonParams.ROOT_DIR_DESC);
    options.addOption(CommonParams.SUB_DIR_TYPE_PARAM, null, true, CommonParams.SUB_DIR_TYPE_DESC);
    options.addOption(CommonParams.MAX_NUM_REC_PARAM, null, true, CommonParams.MAX_NUM_REC_DESC);
    options.addOption(CommonParams.SOLR_FILE_NAME_PARAM, null, true, CommonParams.SOLR_FILE_NAME_DESC);
    options.addOption(CommonParams.OUT_INDEX_PARAM, null, true, CommonParams.OUT_MINDEX_DESC);
    options.addOption(EXCLUDE_FIELDS_PARAM, null, true, EXCLUDE_FIELDS_DESC);

    CommandLineParser parser = new org.apache.commons.cli.GnuParser();

    try {//from  ww w  . j  a  va  2 s.  co m
        CommandLine cmd = parser.parse(options, args);

        String rootDir = null;

        rootDir = cmd.getOptionValue(CommonParams.ROOT_DIR_PARAM);

        if (null == rootDir)
            Usage("Specify: " + CommonParams.ROOT_DIR_DESC, options);

        String outPrefix = cmd.getOptionValue(CommonParams.OUT_INDEX_PARAM);

        if (null == outPrefix)
            Usage("Specify: " + CommonParams.OUT_MINDEX_DESC, options);

        String subDirTypeList = cmd.getOptionValue(CommonParams.SUB_DIR_TYPE_PARAM);

        if (null == subDirTypeList || subDirTypeList.isEmpty())
            Usage("Specify: " + CommonParams.SUB_DIR_TYPE_DESC, options);

        String solrFileName = cmd.getOptionValue(CommonParams.SOLR_FILE_NAME_PARAM);
        if (null == solrFileName)
            Usage("Specify: " + CommonParams.SOLR_FILE_NAME_DESC, options);

        int maxNumRec = Integer.MAX_VALUE;

        String tmp = cmd.getOptionValue(CommonParams.MAX_NUM_REC_PARAM);

        if (tmp != null) {
            try {
                maxNumRec = Integer.parseInt(tmp);
                if (maxNumRec <= 0) {
                    Usage("The maximum number of records should be a positive integer", options);
                }
            } catch (NumberFormatException e) {
                Usage("The maximum number of records should be a positive integer", options);
            }
        }

        String[] exclFields = new String[0];
        tmp = cmd.getOptionValue(EXCLUDE_FIELDS_PARAM);
        if (null != tmp) {
            exclFields = tmp.split(",");
        }

        String[] subDirs = subDirTypeList.split(",");

        for (int k = 0; k < FeatureExtractor.mFieldNames.length; ++k) {
            String field = FeatureExtractor.mFieldsSOLR[k];
            String fieldName = FeatureExtractor.mFieldNames[k];

            boolean bOk = !StringUtilsLeo.isInArrayNoCase(fieldName, exclFields);

            if (bOk)
                System.out.println("Processing field: " + field);
            else {
                System.out.println("Skipping field: " + field);
                continue;
            }

            String[] fileNames = new String[subDirs.length];
            for (int i = 0; i < fileNames.length; ++i)
                fileNames[i] = rootDir + "/" + subDirs[i] + "/" + solrFileName;

            InMemForwardIndex indx = new InMemForwardIndex(field, fileNames, maxNumRec);

            indx.save(InMemIndexFeatureExtractor.indexFileName(outPrefix, fieldName));
        }

    } catch (ParseException e) {
        Usage("Cannot parse arguments", options);
    } catch (Exception e) {
        e.printStackTrace();
        System.err.println("Terminating due to an exception: " + e);
        System.exit(1);
    }
}

From source file:gr.seab.r2rml.beans.Main.java

public static void main(String[] args) {
    Calendar c0 = Calendar.getInstance();
    long t0 = c0.getTimeInMillis();

    CommandLineParser cmdParser = new PosixParser();

    Options cmdOptions = new Options();
    cmdOptions.addOption("p", "properties", true,
            "define the properties file. Example: r2rml-parser -p r2rml.properties");
    cmdOptions.addOption("h", "print help", false, "help");

    String propertiesFile = "r2rml.properties";

    try {//from  w  w w  .j  a va  2  s.com
        CommandLine line = cmdParser.parse(cmdOptions, args);

        if (line.hasOption("h")) {
            HelpFormatter help = new HelpFormatter();
            help.printHelp("r2rml-parser\n", cmdOptions);
            System.exit(0);
        }

        if (line.hasOption("p")) {
            propertiesFile = line.getOptionValue("p");
        }
    } catch (ParseException e1) {
        //e1.printStackTrace();
        log.error("Error parsing command line arguments.");
        System.exit(1);
    }

    try {
        if (StringUtils.isNotEmpty(propertiesFile)) {
            properties.load(new FileInputStream(propertiesFile));
            log.info("Loaded properties from " + propertiesFile);
        }
    } catch (FileNotFoundException e) {
        //e.printStackTrace();
        log.error("Properties file not found (" + propertiesFile + ").");
        System.exit(1);
    } catch (IOException e) {
        //e.printStackTrace();
        log.error("Error reading properties file (" + propertiesFile + ").");
        System.exit(1);
    }

    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("app-context.xml");

    Database db = (Database) context.getBean("db");
    db.setProperties(properties);

    Parser parser = (Parser) context.getBean("parser");
    parser.setProperties(properties);

    MappingDocument mappingDocument = parser.parse();

    mappingDocument.getTimestamps().add(t0); //0 Started
    mappingDocument.getTimestamps().add(Calendar.getInstance().getTimeInMillis()); //1 Finished parsing. Starting generating result model.

    Generator generator = (Generator) context.getBean("generator");
    generator.setProperties(properties);
    generator.setResultModel(parser.getResultModel());

    //Actually do the output
    generator.createTriples(mappingDocument);

    context.close();
    Calendar c1 = Calendar.getInstance();
    long t1 = c1.getTimeInMillis();
    log.info("Finished in " + (t1 - t0) + " milliseconds. Done.");
    mappingDocument.getTimestamps().add(Calendar.getInstance().getTimeInMillis()); //5 Finished.
    //log.info("5 Finished.");

    //output the result
    for (int i = 0; i < mappingDocument.getTimestamps().size(); i++) {
        if (i > 0) {
            long l = (mappingDocument.getTimestamps().get(i).longValue()
                    - mappingDocument.getTimestamps().get(i - 1).longValue());
            //System.out.println(l);
            log.info(String.valueOf(l));
        }
    }
    log.info("Parse. Generate in memory. Dump to disk/database. Log. - Alltogether in "
            + String.valueOf(mappingDocument.getTimestamps().get(5).longValue()
                    - mappingDocument.getTimestamps().get(0).longValue())
            + " msec.");
    log.info("Done.");
    System.out.println("Done.");
}

From source file:de.mpi_bremen.mgg.FastaValidatorUi.java

/**
 * @param args the command line arguments
 *//*from www.  ja va  2s . c  om*/
public static void main(String[] args) {
    // create Options object
    Options options = new Options();
    // add verbose option
    options.addOption("v", "verbose", false, "verbose mode");
    // add inputfile option
    options.addOption("f", "file", true, "FASTA-formatted input file");
    // add help option
    options.addOption("h", "help", false, "print this help message");
    // add sequencetype option
    options.addOption("t", "seqtype", true, "sequence type (allowed values: all|dna|rna|protein)");
    // add gui-mode option
    options.addOption("nogui", false, "start in non-interactive mode");

    //create the cmdline-parser   
    GnuParser parser = new GnuParser();

    // parse the command line arguments
    try {
        //get cmdline arguments
        cmdline = parser.parse(options, args);
    } catch (ParseException exp) {
        System.err.println(exp.getMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("FastaValidatorUi", options, true);
        System.exit(1); //indicate error to external environment
    }

    if (cmdline.hasOption("h")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("FastaValidatorUi", options, true);
        System.exit(0); //indicate no errors to external environment
    }

    //which mode? (gui or cmdline)
    if (cmdline.hasOption("nogui")) { //cmdline-mode

        //create new cmdline-gui
        FvCmdline cmdlinegui = new FvCmdline();

        //set verbosity
        cmdlinegui.setVerbose(cmdline.hasOption("v"));

        //handle input file
        if (cmdline.hasOption("f")) {
            cmdlinegui.setInput(cmdline.getOptionValue("f"));
        }

        //set sequencetype
        if (cmdline.hasOption("t")) {
            cmdlinegui.setSequencetype(getSeqtype(cmdline.getOptionValue("t")));
        } else {
            cmdlinegui.setSequencetype(FastaValidator.Sequencetype.ALL);
        }

        //trigger validation and exit with exitcode
        int exitcode = cmdlinegui.validate().getValue();
        System.exit(exitcode);

    } else { //gui-mode
        //start gui in its own thread
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                FvGui w = new FvGui();
            }
        });
    }
}

From source file:com.github.megatronking.svg.cli.Main.java

public static void main(String[] args) {
    Options opt = new Options();
    opt.addOption("d", "dir", true, "the target svg directory");
    opt.addOption("f", "file", true, "the target svg file");
    opt.addOption("o", "output", true, "the output vector file or directory");
    opt.addOption("w", "width", true, "the width size of target vector image");
    opt.addOption("h", "height", true, "the height size of target vector image");

    HelpFormatter formatter = new HelpFormatter();
    CommandLineParser parser = new PosixParser();

    CommandLine cl;//w w w  .  ja  v  a  2 s  .co  m
    try {
        cl = parser.parse(opt, args);
    } catch (ParseException e) {
        formatter.printHelp(HELPER_INFO, opt);
        return;
    }

    if (cl == null) {
        formatter.printHelp(HELPER_INFO, opt);
        return;
    }

    int width = 0;
    int height = 0;
    if (cl.hasOption("w")) {
        width = SCU.parseInt(cl.getOptionValue("w"));
    }
    if (cl.hasOption("h")) {
        height = SCU.parseInt(cl.getOptionValue("h"));
    }

    String dir = null;
    String file = null;
    if (cl.hasOption("d")) {
        dir = cl.getOptionValue("d");
    } else if (cl.hasOption("f")) {
        file = cl.getOptionValue("f");
    }

    String output = null;
    if (cl.hasOption("o")) {
        output = cl.getOptionValue("o");
    }

    if (output == null) {
        if (dir != null) {
            output = dir;
        }
        if (file != null) {
            output = FileUtils.noExtensionName(file) + ".xml";
        }
    }

    if (dir == null && file == null) {
        formatter.printHelp(HELPER_INFO, opt);
        throw new RuntimeException("You must input the target svg file or directory");
    }

    if (dir != null) {
        File inputDir = new File(dir);
        if (!inputDir.exists() || !inputDir.isDirectory()) {
            throw new RuntimeException("The path [" + dir + "] is not exist or valid directory");
        }
        File outputDir = new File(output);
        if (outputDir.exists() || outputDir.mkdirs()) {
            svg2vectorForDirectory(inputDir, outputDir, width, height);
        } else {
            throw new RuntimeException("The path [" + outputDir + "] is not a valid directory");
        }
    }

    if (file != null) {
        File inputFile = new File(file);
        if (!inputFile.exists() || !inputFile.isFile()) {
            throw new RuntimeException("The path [" + file + "] is not exist or valid file");
        }
        svg2vectorForFile(inputFile, new File(output), width, height);
    }
}

From source file:cz.muni.fi.mir.mathmlunificator.MathMLUnificatorCommandLineTool.java

/**
 * Main (starting) method of the command line application.
 *
 * @param argv Array of command line arguments that are expected to be
 * filesystem paths to input XML documents with MathML to be unified.
 * @throws ParserConfigurationException If a XML DOM builder cannot be
 * created with the configuration requested.
 *//*from  ww  w . j av  a  2s.co  m*/
public static void main(String argv[]) throws ParserConfigurationException {

    final Options options = new Options();
    options.addOption("p", "operator-unification", false, "unify operator in addition to other types of nodes");
    options.addOption("h", "help", false, "print help");

    final CommandLineParser parser = new DefaultParser();
    CommandLine line = null;
    try {
        line = parser.parse(options, argv);
    } catch (ParseException ex) {
        printHelp(options);
        System.exit(1);
    }

    if (line != null) {
        if (line.hasOption('h')) {
            printHelp(options);
            System.exit(0);
        }
        operatorUnification = line.hasOption('p');

        final List<String> arguments = Arrays.asList(line.getArgs());
        if (arguments.size() > 0) {

            Document outerDocument = DOMBuilder.getDocumentBuilder().newDocument();
            Node rootNode = outerDocument.createElementNS(UNIFIED_MATHML_NS,
                    UNIFIED_MATHML_NS_PREFIX + ":" + UNIFIED_MATHML_BATCH_OUTPUT_ROOT_ELEM);
            outerDocument.appendChild(rootNode);

            for (String filepath : arguments) {
                try {

                    Document doc = DOMBuilder.buildDocFromFilepath(filepath);
                    MathMLUnificator.unifyMathML(doc, operatorUnification);
                    if (arguments.size() == 1) {
                        xmlStdoutSerializer(doc);
                    } else {
                        Node itemNode = rootNode.getOwnerDocument().createElementNS(UNIFIED_MATHML_NS,
                                UNIFIED_MATHML_NS_PREFIX + ":" + UNIFIED_MATHML_BATCH_OUTPUT_ITEM_ELEM);
                        Attr filenameAttr = itemNode.getOwnerDocument().createAttributeNS(UNIFIED_MATHML_NS,
                                UNIFIED_MATHML_NS_PREFIX + ":"
                                        + UNIFIED_MATHML_BATCH_OUTPUT_ITEM_FILEPATH_ATTR);
                        filenameAttr.setTextContent(String.valueOf(filepath));
                        ((Element) itemNode).setAttributeNodeNS(filenameAttr);
                        itemNode.appendChild(
                                rootNode.getOwnerDocument().importNode(doc.getDocumentElement(), true));
                        rootNode.appendChild(itemNode);

                    }

                } catch (SAXException | IOException ex) {
                    Logger.getLogger(MathMLUnificatorCommandLineTool.class.getName()).log(Level.SEVERE,
                            "Failed processing of file: " + filepath, ex);
                }
            }

            if (rootNode.getChildNodes().getLength() > 0) {
                xmlStdoutSerializer(rootNode.getOwnerDocument());
            }

        } else {
            printHelp(options);
            System.exit(0);
        }
    }

}

From source file:gov.lanl.adore.djatoka.DjatokaExtract.java

/**
 * Uses apache commons cli to parse input args. Passes parsed
 * parameters to IExtract implementation.
 * @param args command line parameters to defined input,output,etc.
 *//*from w ww  .j  av  a 2s  .  c  o m*/
public static void main(String[] args) {
    // create the command line parser
    CommandLineParser parser = new PosixParser();

    // create the Options
    Options options = new Options();
    options.addOption("i", "input", true, "Filepath of the input file.");
    options.addOption("o", "output", true, "Filepath of the output file.");
    options.addOption("l", "level", true, "Resolution level to extract.");
    options.addOption("d", "reduce", true, "Resolution levels to subtract from max resolution.");
    options.addOption("r", "region", true, "Format: Y,X,H,W. ");
    options.addOption("c", "cLayer", true, "Compositing Layer Index.");
    options.addOption("s", "scale", true,
            "Format: Option 1. Define a long-side dimension (e.g. 96); Option 2. Define absolute w,h values (e.g. 1024,768); Option 3. Define a single dimension (e.g. 1024,0) with or without Level Parameter; Option 4. Use a single decimal scaling factor (e.g. 0.854)");
    options.addOption("t", "rotate", true, "Number of degrees to rotate image (i.e. 90, 180, 270).");
    options.addOption("f", "format", true,
            "Mimetype of the image format to be provided as response. Default: image/jpeg");
    options.addOption("a", "AltImpl", true, "Alternate IExtract Implemenation");

    try {
        if (args.length == 0) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("gov.lanl.adore.djatoka.DjatokaExtract", options);
            System.exit(0);
        }

        // parse the command line arguments
        CommandLine line = parser.parse(options, args);
        String input = line.getOptionValue("i");
        String output = line.getOptionValue("o");

        DjatokaDecodeParam p = new DjatokaDecodeParam();
        String level = line.getOptionValue("l");
        if (level != null)
            p.setLevel(Integer.parseInt(level));
        String reduce = line.getOptionValue("d");
        if (level == null && reduce != null)
            p.setLevelReductionFactor(Integer.parseInt(reduce));
        String region = line.getOptionValue("r");
        if (region != null)
            p.setRegion(region);
        String cl = line.getOptionValue("c");
        if (cl != null) {
            int clayer = Integer.parseInt(cl);
            if (clayer > 0)
                p.setCompositingLayer(clayer);
        }
        String scale = line.getOptionValue("s");
        if (scale != null) {
            String[] v = scale.split(",");
            if (v.length == 1) {
                if (v[0].contains("."))
                    p.setScalingFactor(Double.parseDouble(v[0]));
                else {
                    int[] dims = new int[] { -1, Integer.parseInt(v[0]) };
                    p.setScalingDimensions(dims);
                }
            } else if (v.length == 2) {
                int[] dims = new int[] { Integer.parseInt(v[0]), Integer.parseInt(v[1]) };
                p.setScalingDimensions(dims);
            }
        }
        String rotate = line.getOptionValue("t");
        if (rotate != null)
            p.setRotationDegree(Integer.parseInt(rotate));
        String format = line.getOptionValue("f");
        if (format == null)
            format = "image/jpeg";
        String alt = line.getOptionValue("a");
        if (output == null)
            output = input + ".jpg";

        long x = System.currentTimeMillis();
        IExtract ex = new KduExtractExe();
        if (alt != null)
            ex = (IExtract) Class.forName(alt).newInstance();
        DjatokaExtractProcessor e = new DjatokaExtractProcessor(ex);
        e.extractImage(input, output, p, format);
        logger.info("Extraction Time: " + ((double) (System.currentTimeMillis() - x) / 1000) + " seconds");

    } catch (ParseException e) {
        logger.error("Parse exception:" + e.getMessage(), e);
    } catch (DjatokaException e) {
        logger.error("djatoka Extraction exception:" + e.getMessage(), e);
    } catch (InstantiationException e) {
        logger.error("Unable to initialize alternate implemenation:" + e.getMessage(), e);
    } catch (Exception e) {
        logger.error("Unexpected exception:" + e.getMessage(), e);
    }
}

From source file:dhtaccess.tools.Put.java

public static void main(String[] args) {
    byte[] secret = null;
    int ttl = 3600;

    // parse properties
    Properties prop = System.getProperties();
    String gateway = prop.getProperty("dhtaccess.gateway");
    if (gateway == null || gateway.length() <= 0) {
        gateway = DEFAULT_GATEWAY;/*from  ww w.  j  av  a 2 s. co m*/
    }

    // parse options
    Options options = new Options();
    options.addOption("h", "help", false, "print help");
    options.addOption("g", "gateway", true, "gateway URI, list at http://opendht.org/servers.txt");
    options.addOption("s", "secret", true, "can be used to remove the value later");
    options.addOption("t", "ttl", true, "how long (in seconds) to store the value");

    CommandLineParser parser = new PosixParser();
    CommandLine cmd = null;
    try {
        cmd = parser.parse(options, args);
    } catch (ParseException e) {
        System.out.println("There is an invalid option.");
        e.printStackTrace();
        System.exit(1);
    }

    String optVal;
    if (cmd.hasOption('h')) {
        usage(COMMAND);
        System.exit(1);
    }
    optVal = cmd.getOptionValue('g');
    if (optVal != null) {
        gateway = optVal;
    }
    optVal = cmd.getOptionValue('s');
    if (optVal != null) {
        try {
            secret = optVal.getBytes(ENCODE);
        } catch (UnsupportedEncodingException e) {
            // NOTREACHED
        }
    }
    optVal = cmd.getOptionValue('t');
    if (optVal != null) {
        ttl = Integer.parseInt(optVal);
    }

    args = cmd.getArgs();

    // parse arguments
    if (args.length < 2) {
        usage(COMMAND);
        System.exit(1);
    }

    for (int index = 0; index + 1 < args.length; index += 2) {
        byte[] key = null, value = null;
        try {
            key = args[index].getBytes(ENCODE);
            value = args[index + 1].getBytes(ENCODE);
        } catch (UnsupportedEncodingException e1) {
            // NOTREACHED
        }

        // prepare for RPC
        DHTAccessor accessor = null;
        try {
            accessor = new DHTAccessor(gateway);
        } catch (MalformedURLException e) {
            e.printStackTrace();
            System.exit(1);
        }

        // RPC
        int res = accessor.put(key, value, ttl, secret);

        String resultString;
        switch (res) {
        case 0:
            resultString = "Success";
            break;
        case 1:
            resultString = "Capacity";
            break;
        case 2:
            resultString = "Again";
            break;
        default:
            resultString = "???";
        }
        System.out.println(resultString + ": " + args[index] + ", " + args[index + 1]);
    }
}

From source file:edu.msu.cme.rdp.readseq.writers.StkWriter.java

public static void main(String[] args) throws Exception {
    Options options = new Options();
    options.addOption("r", "removeref", false, "is set, do not write the GC reference sequences to output");
    options.addOption("h", "header", true,
            "the header of the output file in case a differenet stk version, default is " + STK_HEADER);
    String header = STK_HEADER;//from w  ww .  ja v  a2s  . c  om
    boolean removeRef = false;

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

        if (line.hasOption("removeref")) {
            removeRef = true;
        }
        if (line.hasOption("header")) {
            header = line.getOptionValue("header");
        }

        args = line.getArgs();
        if (args.length < 2) {
            throw new Exception("Need input and output files");
        }

    } catch (Exception e) {
        new HelpFormatter().printHelp("USAGE: to-stk <input-file> <out-file>", options);
        System.err.println("ERROR: " + e.getMessage());
        System.exit(1);
        return;
    }

    SequenceReader reader = new SequenceReader(new File(args[0]));
    PrintStream out = new PrintStream(new File(args[1]));
    StkWriter writer = new StkWriter(reader, out, header);
    reader = new SequenceReader(new File(args[0]));
    Sequence seq;
    while ((seq = reader.readNextSequence()) != null) {
        if (seq.getSeqName().startsWith("#") && removeRef) {
            continue;
        }
        writer.writeSeq(seq);
    }
    writer.writeEndOfBlock();
    writer.close();
    reader.close();

}

From source file:com.aerospike.examples.Main.java

/**
 * Main entry point.//from w  ww.jav a  2  s  .c om
 */
public static void main(String[] args) {

    try {
        Options options = new Options();
        options.addOption("h", "host", true, "Server hostname (default: localhost)");
        options.addOption("p", "port", true, "Server port (default: 3000)");
        options.addOption("U", "user", true, "User name");
        options.addOption("P", "password", true, "Password");
        options.addOption("n", "namespace", true, "Namespace (default: test)");
        options.addOption("s", "set", true, "Set name. Use 'empty' for empty set (default: demoset)");
        options.addOption("g", "gui", false, "Invoke GUI to selectively run tests.");
        options.addOption("d", "debug", false, "Run in debug mode.");
        options.addOption("u", "usage", false, "Print usage.");

        CommandLineParser parser = new PosixParser();
        CommandLine cl = parser.parse(options, args, false);

        if (args.length == 0 || cl.hasOption("u")) {
            logUsage(options);
            return;
        }
        Parameters params = parseParameters(cl);
        String[] exampleNames = cl.getArgs();

        if ((exampleNames.length == 0) && (!cl.hasOption("g"))) {
            logUsage(options);
            return;
        }

        // Check for all.
        for (String exampleName : exampleNames) {
            if (exampleName.equalsIgnoreCase("all")) {
                exampleNames = ExampleNames;
                break;
            }
        }

        if (cl.hasOption("d")) {
            Log.setLevel(Level.DEBUG);
        }

        if (cl.hasOption("g")) {
            GuiDisplay.startGui(params);
        } else {
            Console console = new Console();
            runExamples(console, params, exampleNames);
        }
    } catch (Exception ex) {
        System.out.println(ex.getMessage());
        ex.printStackTrace();
    }
}