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

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

Introduction

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

Prototype

public boolean hasOption(String opt) 

Source Link

Document

Returns whether the named Option is a member of this Options .

Usage

From source file:io.lonelyrobot.empires.client.core.MainClientLauncher.java

public static void main(String[] args) {
    LwjglApplicationConfiguration cfg = new LwjglApplicationConfiguration();
    cfg.title = Values.SUPERTITLE + " - " + Values.VERSION_NUMBER;

    final Options gameOptions = new Options();
    // gameOptions.addOption("fullscreen", false, "Launch as fullscreen");

    if (gameOptions.hasOption("fullscreen")) {
        System.out.println("Attempting to launch as fullscreen Application. This is experimental as of 1.3+");
        GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();

        cfg.width = gd.getDisplayMode().getWidth();
        cfg.height = gd.getDisplayMode().getHeight();
        cfg.fullscreen = true;/*from  w  w  w .  j  a  va  2 s.com*/

        Values.NEW_WIDTH = cfg.width;
        Values.NEW_HEIGHT = cfg.height;
    } else {
        cfg.fullscreen = false;
        cfg.width = Values.OLD_WIDTH;
        cfg.height = Values.OLD_HEIGHT;
    }

    cfg.useGL30 = true;
    cfg.resizable = false;
    cfg.initialBackgroundColor = Color.BLACK;

    new LwjglApplication(GameCore.getInstance(), cfg);
}

From source file:com.spotify.cassandra.opstools.CountTombstones.java

/**
 * Counts the number of tombstones, per row, in a given SSTable
 *
 * Assumes RandomPartitioner, standard columns and UTF8 encoded row keys
 *
 * Does not require a cassandra.yaml file or system tables.
 *
 * @param args command lines arguments/* ww w.j av a  2 s  .c  o m*/
 *
 * @throws java.io.IOException on failure to open/read/write files or output streams
 */
public static void main(String[] args) throws IOException, ParseException {
    String usage = String.format("Usage: %s [-l] <sstable> [<sstable> ...]%n", CountTombstones.class.getName());

    final Options options = new Options();
    options.addOption("l", "legend", false, "Include column name explanation");
    options.addOption("p", "partitioner", true, "The partitioner used by database");

    CommandLineParser parser = new BasicParser();
    CommandLine cmd = parser.parse(options, args);

    if (cmd.getArgs().length < 1) {
        System.err.println("You must supply at least one sstable");
        System.err.println(usage);
        System.exit(1);
    }

    // Fake DatabaseDescriptor settings so we don't have to load cassandra.yaml etc
    Config.setClientMode(true);
    String partitionerName = String.format("org.apache.cassandra.dht.%s",
            options.hasOption("p") ? options.getOption("p") : "RandomPartitioner");
    try {
        Class<?> clazz = Class.forName(partitionerName);
        IPartitioner partitioner = (IPartitioner) clazz.newInstance();
        DatabaseDescriptor.setPartitioner(partitioner);
    } catch (Exception e) {
        throw new RuntimeException("Can't instantiate partitioner " + partitionerName);
    }

    PrintStream out = System.out;

    for (String arg : cmd.getArgs()) {
        String ssTableFileName = new File(arg).getAbsolutePath();

        Descriptor descriptor = Descriptor.fromFilename(ssTableFileName);

        run(descriptor, cmd, out);
    }

    System.exit(0);
}

From source file:com.ultratechnica.mongodb.Main.java

public static void main(String[] args) {

    log.info("=============================================================================================\n"
            + "                       _   _     _                 \n"
            + " |\\/|  _  ._   _   _  | \\ |_)   |_)  _  ._   _ |_  \n"
            + " |  | (_) | | (_| (_) |_/ |_)   |_) (/_ | | (_ | | \n"
            + "               _|                                  \n"
            + "Copyright 2013 Keith Bishop, Ultratechnica Ltd, http://ultratechnica.com\n"
            + "Licensed to Apache "
            + "=============================================================================================\n");
    Options options = getOptions();

    CommandLine commandLine = parseArgs(args, options);

    MongoClient client = null;/*from   ww  w .j a v a  2  s . c om*/

    if (commandLine.hasOption("host") && commandLine.hasOption("port")) {

        String host = commandLine.getOptionValue("host");
        String port = commandLine.getOptionValue("port");

        try {

            client = new MongoClient(host, Integer.parseInt(port));
        } catch (UnknownHostException e) {
            log.error("Unable to connect to host [{}] on port [{}]", host, port);
        }
    } else if (options.hasOption("host")) {

        String host = commandLine.getOptionValue("host");

        try {
            client = new MongoClient(host);
        } catch (UnknownHostException e) {
            log.error("Unable to connect to host [{}] on default port ()", host);
        }
    } else {

        try {
            client = new MongoClient();
        } catch (UnknownHostException e) {
            log.error("Unable to connect default host ({}) on default port ()", DEFAULT_HOST, DEFAULT_PORT);
        }
    }

    if (client == null) {
        System.out.println("Exiting, due to previous connection errors");
        System.exit(1);
    }

    ServerAddress clientAddress = client.getAddress();
    log.info("Connected to MongoDB [{}]", clientAddress);

    MongoClientOptions mongoClientOptions = client.getMongoClientOptions();

    log.info("=============================================================================================\n"
            + "Using Mongo Client options:\n" + "\tConnections per host: "
            + mongoClientOptions.getConnectionsPerHost() + "\n" + "\tConect timeout: "
            + mongoClientOptions.getConnectTimeout() + " \n" + "\tSocket timeout: "
            + mongoClientOptions.getSocketTimeout() + "\n" + "\tMax Wait time: "
            + mongoClientOptions.getMaxWaitTime() + "\n" + "\tMax Auto connect retry time: "
            + mongoClientOptions.getMaxAutoConnectRetryTime() + "\n"
            + "\tMax threads allowed to block for conneciton multipler: "
            + mongoClientOptions.getThreadsAllowedToBlockForConnectionMultiplier() + "\n" + "\tWrite concern: "
            + mongoClientOptions.getWriteConcern() + "\n" + "\tRead Preference: "
            + mongoClientOptions.getReadPreference() + "\n"
            + "=============================================================================================\n");

    String items = commandLine.getOptionValue("n");

    int numberOfItems = 0;
    try {
        numberOfItems = Integer.parseInt(items);
    } catch (NumberFormatException e) {
        log.error("The parameter provided for -n was not an integer [{}]", items);
        System.exit(1);
    }

    DB local = client.getDB("local");

    DBCollection collection = local.getCollection(DEFAULT_COLLECTION_NAME);

    log.info("Starting benchmark, inserting [{}] items into collection [{}]", numberOfItems,
            DEFAULT_COLLECTION_NAME);

    long startTime = System.currentTimeMillis();

    for (int i = 0; i < numberOfItems; i++) {

        BasicDBObjectBuilder builder = BasicDBObjectBuilder.start().add("timestamp", new Date())
                .add("field1", "123456").add("field2", "2345678")
                .add("field3", "123123231313131232131231231231123132123123123").add("field4", true);

        WriteResult result = collection.insert(builder.get());
        if (!result.getLastError().ok()) {
            log.error("An error occurred [{}]", result.getLastError());
        }
    }

    long endTime = System.currentTimeMillis();

    log.info("Finished benchmarking.");
    long timeTakenMillis = endTime - startTime;

    float timeTaken = (float) timeTakenMillis / 1000;

    log.info("Results:\n\n" + String.format("%-25s %d", "Number of Items inserted:", numberOfItems) + "\n"
            + String.format("%-25s %.2f", "Time elapsed:", timeTaken) + " seconds\n"
            + String.format("%-25s %.2f", "Throughput:", numberOfItems / timeTaken) + " items/sec\n");

    log.info("Removing test data...");
    collection.remove(new BasicDBObject());
    log.info("Cleared collection [test]");
}

From source file:com.hurence.logisland.plugin.PluginManager.java

public static void main(String... args) throws Exception {
    System.out.println(BannerLoader.loadBanner());

    String logislandHome = new File(
            new File(PluginManager.class.getProtectionDomain().getCodeSource().getLocation().getPath())
                    .getParent()).getParent();
    System.out.println("Using Logisland home: " + logislandHome);
    Options options = new Options();
    OptionGroup mainGroup = new OptionGroup()
            .addOption(OptionBuilder.withDescription(
                    "Install a component. It can be either a logisland plugin or a kafka connect module.")
                    .withArgName("artifact").hasArgs(1).withLongOpt("install").create("i"))
            .addOption(OptionBuilder.withDescription(
                    "Removes a component. It can be either a logisland plugin or a kafka connect module.")
                    .withArgName("artifact").hasArgs(1).withLongOpt("remove").create("r"))
            .addOption(OptionBuilder.withDescription("List installed components.").withLongOpt("list")
                    .create("l"));

    mainGroup.setRequired(true);/*w  w w  .  ja  v a2s .  c om*/
    options.addOptionGroup(mainGroup);
    options.addOption(OptionBuilder.withDescription("Print this help.").withLongOpt("help").create("h"));

    try {
        CommandLine commandLine = new PosixParser().parse(options, args);
        System.out.println(commandLine.getArgList());
        if (commandLine.hasOption("l")) {
            listPlugins();
        } else if (commandLine.hasOption("i")) {
            installPlugin(commandLine.getOptionValue("i"), logislandHome);

        } else if (commandLine.hasOption("r")) {
            removePlugin(commandLine.getOptionValue("r"));
        } else {
            printUsage(options);
        }

    } catch (ParseException e) {
        if (!options.hasOption("h")) {
            System.err.println(e.getMessage());
            System.out.println();
        }
        printUsage(options);

    }
}

From source file:apps.Source2XML.java

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

    options.addOption("i", null, true, "input file");
    options.addOption("o", null, true, "output file");
    options.addOption("reparse_xml", null, false, "reparse each XML entry to ensure the parser doesn't fail");

    Joiner commaJoin = Joiner.on(',');

    options.addOption("source_type", null, true,
            "document source type: " + commaJoin.join(SourceFactory.getDocSourceList()));

    Joiner spaceJoin = Joiner.on(' ');

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

    BufferedWriter outputFile = null;

    int docNum = 0;

    if (USE_LEMMATIZER && USE_STEMMER) {
        System.err.println("Bug/inconsistent code: cann't use the stemmer and lemmatizer at the same time!");
        System.exit(1);/*from   ww w .  j a  v  a  2 s.  c o m*/
    }

    //Stemmer stemmer = new Stemmer();
    KrovetzStemmer stemmer = new KrovetzStemmer();

    System.out.println("Using Stanford NLP?        " + USE_STANFORD);
    System.out.println("Using Stanford lemmatizer? " + USE_LEMMATIZER);
    System.out.println("Using stemmer?             " + USE_STEMMER
            + (USE_STEMMER ? " (class: " + stemmer.getClass().getCanonicalName() + ")" : ""));

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

        String inputFileName = null, outputFileName = null;

        if (cmd.hasOption("i")) {
            inputFileName = cmd.getOptionValue("i");
        } else {
            Usage("Specify 'input file'", options);
        }

        if (cmd.hasOption("o")) {
            outputFileName = cmd.getOptionValue("o");
        } else {
            Usage("Specify 'output file'", options);
        }

        outputFile = new BufferedWriter(
                new OutputStreamWriter(CompressUtils.createOutputStream(outputFileName)));

        String sourceName = cmd.getOptionValue("source_type");

        if (sourceName == null)
            Usage("Specify document source type", options);

        boolean reparseXML = options.hasOption("reparse_xml");

        DocumentSource inpDocSource = SourceFactory.createDocumentSource(sourceName, inputFileName);
        DocumentEntry inpDoc = null;
        TextCleaner textCleaner = new TextCleaner(
                new DictNoComments(new File("data/stopwords.txt"), true /* lower case */), USE_STANFORD,
                USE_LEMMATIZER);

        Map<String, String> outputMap = new HashMap<String, String>();

        outputMap.put(UtilConst.XML_FIELD_DOCNO, null);
        outputMap.put(UtilConst.XML_FIELD_TEXT, null);

        XmlHelper xmlHlp = new XmlHelper();

        if (reparseXML)
            System.out.println("Will reparse every XML entry to verify correctness!");

        while ((inpDoc = inpDocSource.next()) != null) {
            ++docNum;

            ArrayList<String> toks = textCleaner.cleanUp(inpDoc.mDocText);
            ArrayList<String> goodToks = new ArrayList<String>();
            for (String s : toks)
                if (s.length() <= MAX_WORD_LEN && // Exclude long and short words
                        s.length() >= MIN_WORD_LEN && isGoodWord(s))
                    goodToks.add(USE_STEMMER ? stemmer.stem(s) : s);

            String partlyCleanedText = spaceJoin.join(goodToks);
            String cleanText = XmlHelper.removeInvaildXMLChars(partlyCleanedText);
            // isGoodWord combiend with Stanford tokenizer should be quite restrictive already
            //cleanText = replaceSomePunct(cleanText);

            outputMap.replace(UtilConst.XML_FIELD_DOCNO, inpDoc.mDocId);
            outputMap.replace(UtilConst.XML_FIELD_TEXT, cleanText);

            String xml = xmlHlp.genXMLIndexEntry(outputMap);

            if (reparseXML) {
                try {
                    XmlHelper.parseDocWithoutXMLDecl(xml);
                } catch (Exception e) {
                    System.err.println("Error re-parsing xml for document ID: " + inpDoc.mDocId);
                    System.exit(1);
                }
            }

            /*
            {
              System.out.println(inpDoc.mDocId);
              System.out.println("=====================");
              System.out.println(partlyCleanedText);
              System.out.println("=====================");
              System.out.println(cleanText);
            } 
            */

            try {
                outputFile.write(xml);
                outputFile.write(NL);
            } catch (Exception e) {
                e.printStackTrace();
                System.err.println("Error processing/saving a document!");
            }

            if (docNum % 1000 == 0)
                System.out.println(String.format("Processed %d documents", docNum));
        }

    } catch (ParseException e) {
        e.printStackTrace();
        Usage("Cannot parse arguments" + e, options);
    } catch (Exception e) {
        System.err.println("Terminating due to an exception: " + e);
        System.exit(1);
    } finally {
        System.out.println(String.format("Processed %d documents", docNum));

        try {
            if (null != outputFile) {
                outputFile.close();
                System.out.println("Output file is closed! all seems to be fine...");
            }
        } catch (IOException e) {
            System.err.println("IO exception: " + e);
            e.printStackTrace();
        }
    }
}

From source file:ml.shifu.shifu.ShifuCLI.java

public static void main(String[] args) {
    String[] cleanedArgs = cleanArgs(args);
    // invalid input and help options
    if (cleanedArgs.length < 1 || (isHelpOption(cleanedArgs[0]))) {
        printUsage();/*w w w  . j a  v  a  2s  .c  o m*/
        System.exit(cleanedArgs.length < 1 ? -1 : 0);
    }

    // process -v and -version conditions manually
    if (isVersionOption(cleanedArgs[0])) {
        printLogoAndVersion();
        System.exit(0);
    }

    CommandLineParser parser = new GnuParser();
    Options opts = buildModelSetOptions();
    CommandLine cmd = null;

    try {
        cmd = parser.parse(opts, cleanedArgs);
    } catch (ParseException e) {
        log.error("Invalid command options. Please check help message.");
        printUsage();
        System.exit(1);
    }

    int status = 0;

    try {
        if (cleanedArgs[0].equals(NEW) && cleanedArgs.length >= 2 && StringUtils.isNotEmpty(cleanedArgs[1])) {
            // modelset step
            String modelName = cleanedArgs[1];
            status = createNewModel(modelName, cmd.getOptionValue(MODELSET_CMD_TYPE),
                    cmd.getOptionValue(MODELSET_CMD_M));
            if (status == 0) {
                printModelSetCreatedSuccessfulLog(modelName);
            } else {
                log.warn("Error in create new model set, please check your shifu config or report issue");
            }
            System.exit(status);
            // copyModel(manager, cmd.getOptionValues(MODELSET_CMD_CP));
        } else {
            if (cleanedArgs[0].equals(MODELSET_CMD_CP) && cleanedArgs.length >= 3
                    && StringUtils.isNotEmpty(cleanedArgs[1]) && StringUtils.isNotEmpty(cleanedArgs[2])) {
                String newModelSetName = cleanedArgs[2];
                // modelset step
                copyModel(new String[] { cleanedArgs[1], newModelSetName });
                printModelSetCopiedSuccessfulLog(newModelSetName);
            } else if (cleanedArgs[0].equals(INIT_CMD)) {
                // init step
                if (cmd.getOptions() == null || cmd.getOptions().length == 0) {
                    status = initializeModel();
                    if (status == 0) {
                        log.info(
                                "ModelSet initialization is successful. Please continue next step by using 'shifu stats'.");
                    } else {
                        log.warn(
                                "Error in ModelSet initialization, please check your shifu config or report issue");
                    }
                } else if (cmd.hasOption(INIT_CMD_MODEL)) {
                    initializeModelParam();
                } else {
                    log.error("Invalid command, please check help message.");
                    printUsage();
                }
            } else if (cleanedArgs[0].equals(STATS_CMD)) {
                Map<String, Object> params = new HashMap<String, Object>();
                params.put(Constants.IS_COMPUTE_CORR,
                        cmd.hasOption(CORRELATION) || cmd.hasOption(SHORT_CORRELATION));
                params.put(Constants.IS_REBIN, cmd.hasOption(REBIN));
                params.put(Constants.REQUEST_VARS, cmd.getOptionValue(VARS));
                params.put(Constants.EXPECTED_BIN_NUM, cmd.getOptionValue(N));
                params.put(Constants.IV_KEEP_RATIO, cmd.getOptionValue(IVR));
                params.put(Constants.MINIMUM_BIN_INST_CNT, cmd.getOptionValue(BIC));
                params.put(Constants.IS_COMPUTE_PSI, cmd.hasOption(PSI) || cmd.hasOption(SHORT_PSI));

                // stats step
                status = calModelStats(params);
                if (status == 0) {
                    if (cmd.hasOption(CORRELATION) || cmd.hasOption(SHORT_CORRELATION)) {
                        log.info(
                                "Do model set correlation computing successfully. Please continue next step by using 'shifu normalize or shifu norm'. For tree ensemble model, no need do norm, please continue next step by using 'shifu varsel'");
                    }
                    if (cmd.hasOption(PSI) || cmd.hasOption(SHORT_PSI)) {
                        log.info(
                                "Do model set psi computing successfully. Please continue next step by using 'shifu normalize or shifu norm'. For tree ensemble model, no need do norm, please continue next step by using 'shifu varsel'");
                    } else {
                        log.info(
                                "Do model set statistic successfully. Please continue next step by using 'shifu normalize or shifu norm or shifu transform'. For tree ensemble model, no need do norm, please continue next step by using 'shifu varsel'");
                    }
                } else {
                    log.warn(
                            "Error in model set stats computation, please report issue on http:/github.com/shifuml/shifu/issues.");
                }
            } else if (cleanedArgs[0].equals(NORMALIZE_CMD) || cleanedArgs[0].equals(NORM_CMD)
                    || cleanedArgs[0].equals(TRANSFORM_CMD)) {
                // normalize step
                Map<String, Object> params = new HashMap<String, Object>();
                params.put(Constants.IS_TO_SHUFFLE_DATA, cmd.hasOption(SHUFFLE));
                status = normalizeTrainData(params);
                if (status == 0) {
                    log.info(
                            "Do model set normalization successfully. Please continue next step by using 'shifu varselect or shifu varsel'.");
                } else {
                    log.warn(
                            "Error in model set stats computation, please report issue on http:/github.com/shifuml/shifu/issues.");
                }
            } else if (cleanedArgs[0].equals(VARSELECT_CMD) || cleanedArgs[0].equals(VARSEL_CMD)) {
                Map<String, Object> params = new HashMap<String, Object>();
                params.put(Constants.IS_TO_RESET, cmd.hasOption(RESET));
                params.put(Constants.IS_TO_LIST, cmd.hasOption(LIST));
                params.put(Constants.IS_TO_FILTER_AUTO, cmd.hasOption(FILTER_AUTO));
                params.put(Constants.IS_TO_RECOVER_AUTO, cmd.hasOption(RECOVER_AUTO));
                params.put(Constants.RECURSIVE_CNT, cmd.getOptionValue(RECURSIVE));

                // variable selected step
                status = selectModelVar(params);
                if (status == 0) {
                    log.info(
                            "Do model set variables selection successfully. Please continue next step by using 'shifu train'.");
                } else {
                    log.info("Do variable selection with error, please check error message or report issue.");
                }
            } else if (cleanedArgs[0].equals(TRAIN_CMD)) {
                // train step
                status = trainModel(cmd.hasOption(TRAIN_CMD_DRY), cmd.hasOption(TRAIN_CMD_DEBUG),
                        cmd.hasOption(SHUFFLE));
                if (status == 0) {
                    log.info(
                            "Do model set training successfully. Please continue next step by using 'shifu posttrain' or if no need posttrain you can go through with 'shifu eval'.");
                } else {
                    log.info("Do model training with error, please check error message or report issue.");
                }
            } else if (cleanedArgs[0].equals(CMD_ENCODE)) {
                Map<String, Object> params = new HashMap<String, Object>();
                params.put(ModelDataEncodeProcessor.ENCODE_DATA_SET, cmd.getOptionValue(EVAL_CMD_RUN));
                params.put(ModelDataEncodeProcessor.ENCODE_REF_MODEL, cmd.getOptionValue(REF));
                status = runEncode(params);
            } else if (cleanedArgs[0].equals(CMD_COMBO)) {
                if (cmd.hasOption(MODELSET_CMD_NEW)) {
                    log.info("Create new commbo models");
                    status = createNewCombo(cmd.getOptionValue(MODELSET_CMD_NEW));
                } else if (cmd.hasOption(INIT_CMD)) {
                    log.info("Init commbo models");
                    status = initComboModels();
                } else if (cmd.hasOption(EVAL_CMD_RUN)) {
                    log.info("Run combo model - with toShuffle: {}, with toResume: {}", opts.hasOption(SHUFFLE),
                            opts.hasOption(RESUME));
                    status = runComboModels(cmd.hasOption(SHUFFLE), cmd.hasOption(RESUME));
                    // train combo models
                } else if (cmd.hasOption(EVAL_CMD)) {
                    log.info("Eval combo model.");
                    // eval combo model performance
                    status = evalComboModels(cmd.hasOption(RESUME));
                } else {
                    log.error("Invalid command usage.");
                    printUsage();
                }
            } else if (cleanedArgs[0].equals(POSTTRAIN_CMD)) {
                // post train step
                status = postTrainModel();
                if (status == 0) {
                    log.info(
                            "Do model set post-training successfully. Please configure your eval set in ModelConfig.json and continue next step by using 'shifu eval' or 'shifu eval -new <eval set>' to create a new eval set.");
                } else {
                    log.info("Do model post training with error, please check error message or report issue.");
                }
            } else if (cleanedArgs[0].equals(SAVE)) {
                String newModelSetName = cleanedArgs.length >= 2 ? cleanedArgs[1] : null;
                saveCurrentModel(newModelSetName);
            } else if (cleanedArgs[0].equals(SWITCH)) {
                String newModelSetName = cleanedArgs[1];
                switchCurrentModel(newModelSetName);
            } else if (cleanedArgs[0].equals(SHOW)) {
                ManageModelProcessor p = new ManageModelProcessor(ModelAction.SHOW, null);
                p.run();
            } else if (cleanedArgs[0].equals(EVAL_CMD)) {
                Map<String, Object> params = new HashMap<String, Object>();

                // eval step
                if (cleanedArgs.length == 1) {
                    // run everything
                    status = runEvalSet(cmd.hasOption(TRAIN_CMD_DRY));
                    if (status == 0) {
                        log.info("Run eval performance with all eval sets successfully.");
                    } else {
                        log.info("Do evaluation with error, please check error message or report issue.");
                    }
                } else if (cmd.getOptionValue(MODELSET_CMD_NEW) != null) {
                    // create new eval
                    createNewEvalSet(cmd.getOptionValue(MODELSET_CMD_NEW));
                    log.info(
                            "Create eval set successfully. You can configure EvalConfig.json or directly run 'shifu eval -run <evalSetName>' to get performance info.");
                } else if (cmd.hasOption(EVAL_CMD_RUN)) {
                    runEvalSet(cmd.getOptionValue(EVAL_CMD_RUN), cmd.hasOption(TRAIN_CMD_DRY));
                    log.info("Finish run eval performance with eval set {}.", cmd.getOptionValue(EVAL_CMD_RUN));
                } else if (cmd.hasOption(SCORE)) {
                    params.put(EvalModelProcessor.NOSORT, cmd.hasOption(NOSORT));
                    // run score
                    runEvalScore(cmd.getOptionValue(SCORE), params);
                    log.info("Finish run score with eval set {}.", cmd.getOptionValue(SCORE));
                } else if (cmd.hasOption(CONFMAT)) {
                    // run confusion matrix
                    runEvalConfMat(cmd.getOptionValue(CONFMAT));
                    log.info("Finish run confusion matrix with eval set {}.", cmd.getOptionValue(CONFMAT));
                } else if (cmd.hasOption(PERF)) {
                    // run perfermance
                    runEvalPerf(cmd.getOptionValue(PERF));
                    log.info("Finish run performance maxtrix with eval set {}.", cmd.getOptionValue(PERF));
                } else if (cmd.hasOption(LIST)) {
                    // list all evaluation sets
                    listEvalSet();
                } else if (cmd.hasOption(DELETE)) {
                    // delete some evaluation set
                    deleteEvalSet(cmd.getOptionValue(DELETE));
                } else if (cmd.hasOption(NORM)) {
                    runEvalNorm(cmd.getOptionValue(NORM), cmd.hasOption(STRICT));
                } else {
                    log.error("Invalid command, please check help message.");
                    printUsage();
                }
            } else if (cleanedArgs[0].equals(CMD_EXPORT)) {
                Map<String, Object> params = new HashMap<String, Object>();
                params.put(ExportModelProcessor.IS_CONCISE, cmd.hasOption(EXPORT_CONCISE));
                params.put(ExportModelProcessor.REQUEST_VARS, cmd.getOptionValue(VARS));
                params.put(ExportModelProcessor.EXPECTED_BIN_NUM, cmd.getOptionValue(N));
                params.put(ExportModelProcessor.IV_KEEP_RATIO, cmd.getOptionValue(IVR));
                params.put(ExportModelProcessor.MINIMUM_BIN_INST_CNT, cmd.getOptionValue(BIC));
                status = exportModel(cmd.getOptionValue(MODELSET_CMD_TYPE), params);
                if (status == 0) {
                    log.info("Export models/columnstats/corr successfully.");
                } else {
                    log.warn("Fail to export models/columnstats/corr, please check or report issue.");
                }
            } else if (cleanedArgs[0].equals(CMD_TEST)) {
                Map<String, Object> params = new HashMap<String, Object>();
                params.put(ShifuTestProcessor.IS_TO_TEST_FILTER, cmd.hasOption(FILTER));
                params.put(ShifuTestProcessor.TEST_TARGET, cmd.getOptionValue(FILTER));
                params.put(ShifuTestProcessor.TEST_RECORD_CNT, cmd.getOptionValue(N));
                status = runShifuTest(params);
                if (status == 0) {
                    log.info("Run test for Shifu Successfully.");
                } else {
                    log.warn("Fail to run Shifu test.");
                }
            } else if (cleanedArgs[0].equals(CMD_CONVERT)) {
                int optType = -1;
                if (cmd.hasOption(TO_ZIPB)) {
                    optType = 1;
                } else if (cmd.hasOption(TO_TREEB)) {
                    optType = 2;
                }

                String[] convertArgs = new String[2];
                int j = 0;
                for (int i = 1; i < cleanedArgs.length; i++) {
                    if (!cleanedArgs[i].startsWith("-")) {
                        convertArgs[j++] = cleanedArgs[i];
                    }
                }

                if (optType < 0 || StringUtils.isBlank(convertArgs[0]) || StringUtils.isBlank(convertArgs[1])) {
                    printUsage();
                } else {
                    status = runShifuConvert(optType, convertArgs[0], convertArgs[1]);
                }
            } else if (cleanedArgs[0].equals(CMD_ANALYSIS)) {
                if (cmd.hasOption(FI)) {
                    String modelPath = cmd.getOptionValue(FI);
                    analysisModelFi(modelPath);
                }
            } else {
                log.error("Invalid command, please check help message.");
                printUsage();
            }
        }
        // for some case jvm cannot stop
        System.exit(status);
    } catch (ShifuException e) {
        // need define error code in each step.
        log.error(e.getError().toString() + "; msg: " + e.getMessage(), e.getCause());
        exceptionExit(e);
    } catch (Exception e) {
        exceptionExit(e);
    }
}

From source file:co.cask.cdap.cli.CLIMainArgs.java

public static CLIMainArgs parse(String[] args, Options options) {
    List<String> optionsPart = Lists.newArrayList();
    List<String> commandPart = Lists.newArrayList();

    boolean inOptionsPart = true;
    for (int i = 0; i < args.length; i++) {
        String token = args[i];// w w w  .  ja  v  a  2  s . com
        if (inOptionsPart) {
            if (!token.startsWith("-")) {
                inOptionsPart = false;
            } else if (!options.hasOption(token)) {
                inOptionsPart = true;
            } else if (!options.getOption(token).hasArg()) {
                inOptionsPart = true;
            } else if (options.getOption(token).hasArg() && i + 1 < args.length) {
                inOptionsPart = true;
                // add the option and option value
                optionsPart.add(token);
                optionsPart.add(args[++i]);
                continue;
            } else {
                inOptionsPart = false;
            }
        }

        if (inOptionsPart) {
            optionsPart.add(token);
        } else {
            commandPart.add(token);
        }
    }
    return new CLIMainArgs(optionsPart.toArray(new String[optionsPart.size()]),
            commandPart.toArray(new String[commandPart.size()]));
}

From source file:com.netflix.exhibitor.application.ExhibitorMain.java

private static ConfigProvider getS3Provider(Options options, CommandLine commandLine,
        PropertyBasedS3Credential awsCredentials, String hostname) throws Exception {
    ConfigProvider provider;// ww  w .j  a  v  a  2 s  . co  m
    String prefix = options.hasOption(S3_CONFIG_PREFIX) ? commandLine.getOptionValue(S3_CONFIG_PREFIX)
            : DEFAULT_FILESYSTEMCONFIG_PREFIX;
    provider = new S3ConfigProvider(new S3ClientFactoryImpl(), awsCredentials,
            getS3Arguments(commandLine.getOptionValue(S3_CONFIG), options, prefix), hostname);
    return provider;
}

From source file:com.yahoo.storm.yarn.Client.java

/**
 * @param args the command line arguments
 * @throws Exception  //from  ww  w. ja  v a  2s. co  m
 */
@SuppressWarnings("rawtypes")
public void execute(String[] args) throws Exception {
    HashMap<String, ClientCommand> commands = new HashMap<String, ClientCommand>();
    HelpCommand help = new HelpCommand(commands);
    commands.put("help", help);
    commands.put("launch", new LaunchCommand());
    commands.put("setStormConfig", new StormMasterCommand(StormMasterCommand.COMMAND.SET_STORM_CONFIG));
    commands.put("getStormConfig", new StormMasterCommand(StormMasterCommand.COMMAND.GET_STORM_CONFIG));
    commands.put("addSupervisors", new StormMasterCommand(StormMasterCommand.COMMAND.ADD_SUPERVISORS));
    commands.put("startNimbus", new StormMasterCommand(StormMasterCommand.COMMAND.START_NIMBUS));
    commands.put("stopNimbus", new StormMasterCommand(StormMasterCommand.COMMAND.STOP_NIMBUS));
    commands.put("startUI", new StormMasterCommand(StormMasterCommand.COMMAND.START_UI));
    commands.put("stopUI", new StormMasterCommand(StormMasterCommand.COMMAND.STOP_UI));
    commands.put("startSupervisors", new StormMasterCommand(StormMasterCommand.COMMAND.START_SUPERVISORS));
    commands.put("stopSupervisors", new StormMasterCommand(StormMasterCommand.COMMAND.STOP_SUPERVISORS));
    commands.put("shutdown", new StormMasterCommand(StormMasterCommand.COMMAND.SHUTDOWN));
    commands.put("version", new VersionCommand());

    String commandName = null;
    String[] commandArgs = null;
    if (args.length < 1) {
        commandName = "help";
        commandArgs = new String[0];
    } else {
        commandName = args[0];
        commandArgs = Arrays.copyOfRange(args, 1, args.length);
    }
    ClientCommand command = commands.get(commandName);
    if (command == null) {
        LOG.error("ERROR: " + commandName + " is not a supported command.");
        help.printHelpFor(null);
        System.exit(1);
    }
    Options opts = command.getOpts();
    if (!opts.hasOption("h")) {
        opts.addOption("h", "help", false, "print out a help message");
    }
    CommandLine cl = new GnuParser().parse(command.getOpts(), commandArgs);
    if (cl.hasOption("help")) {
        help.printHelpFor(Arrays.asList(commandName));
    } else {

        command.process(cl);
    }
}

From source file:ape_test.CLITest.java

public void testHelpOption() {
    Main.createOptions();
    Options opts = Main.getOptions();

    assertEquals(opts.hasOption("-h"), true);
}