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

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

Introduction

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

Prototype

public boolean hasOption(char opt) 

Source Link

Document

Query to see if an option has been set.

Usage

From source file:com.yahoo.gondola.tsunami.Tsunami.java

public static void main(String[] args) throws Exception {
    PropertyConfigurator.configure("conf/log4j.properties");
    config = new Config(new File("conf/gondola-tsunami.conf"));

    // Process command line arguments
    CommandLineParser parser = new DefaultParser();
    Options options = new Options();
    options.addOption("w", true, "Number of writers per member, default = " + numWriters);
    options.addOption("h", false, "help");
    CommandLine commandLine = parser.parse(options, args);
    if (commandLine.hasOption("h")) {
        new HelpFormatter().printHelp("Tsunami Test", options);
        return;//from ww  w  .j  a  va 2 s .  c o  m
    }
    if (commandLine.hasOption("w")) {
        numWriters = Integer.parseInt(commandLine.getOptionValue("w"));
    }
    new Tsunami();
}

From source file:com.zimbra.common.util.RandomPassword.java

public static void main(String args[]) {
    CommandLineParser parser = new GnuParser();
    Options options = new Options();
    options.addOption("l", "localpart", false, "generated string does not contain dot(.)");

    CommandLine cl = null;
    boolean err = false;

    try {/*www  .j av  a  2 s  .  c  o m*/
        cl = parser.parse(options, args, true);
    } catch (ParseException pe) {
        System.err.println("error: " + pe.getMessage());
        err = true;
    }

    if (err || cl.hasOption('h')) {
        usage();
    }

    boolean localpart = false;
    int minLength = DEFAULT_MIN_LENGTH;
    int maxLength = DEFAULT_MAX_LENGTH;

    if (cl.hasOption('l'))
        localpart = true;

    args = cl.getArgs();

    if (args.length != 0) {
        if (args.length != 2) {
            usage();
        }
        try {
            minLength = Integer.valueOf(args[0]).intValue();
            maxLength = Integer.valueOf(args[1]).intValue();
        } catch (Exception e) {
            System.err.println(e);
            e.printStackTrace();
        }
    }

    System.out.println(generate(minLength, maxLength, localpart));
}

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

@SuppressWarnings("unchecked")
public static void main(String[] args) throws Exception {
    LOG.info("Starting the AM!!!!");

    Options opts = new Options();
    opts.addOption("app_attempt_id", true, "App Attempt ID. Not to be used " + "unless for testing purposes");

    CommandLine cl = new GnuParser().parse(opts, args);

    ApplicationAttemptId appAttemptID;/*from  w ww .ja  va  2s. c  om*/
    Map<String, String> envs = System.getenv();
    if (cl.hasOption("app_attempt_id")) {
        String appIdStr = cl.getOptionValue("app_attempt_id", "");
        appAttemptID = ConverterUtils.toApplicationAttemptId(appIdStr);
    } else if (envs.containsKey(ApplicationConstants.Environment.CONTAINER_ID.name())) {
        ContainerId containerId = ConverterUtils
                .toContainerId(envs.get(ApplicationConstants.Environment.CONTAINER_ID.name()));
        appAttemptID = containerId.getApplicationAttemptId();
        LOG.info("appAttemptID from env:" + appAttemptID.toString());
    } else {
        LOG.error("appAttemptID is not specified for storm master");
        throw new Exception("appAttemptID is not specified for storm master");
    }

    @SuppressWarnings("rawtypes")
    Map storm_conf = Config.readStormConfig(null);
    Util.rmNulls(storm_conf);

    YarnConfiguration hadoopConf = new YarnConfiguration();

    final String host = InetAddress.getLocalHost().getHostName();
    storm_conf.put("nimbus.host", host);

    StormAMRMClient rmClient = new StormAMRMClient(appAttemptID, storm_conf, hadoopConf);
    rmClient.init(hadoopConf);
    rmClient.start();

    BlockingQueue<Container> launcherQueue = new LinkedBlockingQueue<Container>();

    MasterServer server = new MasterServer(storm_conf, rmClient);
    try {
        final int port = Utils.getInt(storm_conf.get(Config.MASTER_THRIFT_PORT));
        final String target = host + ":" + port;
        InetSocketAddress addr = NetUtils.createSocketAddr(target);
        RegisterApplicationMasterResponse resp = rmClient.registerApplicationMaster(addr.getHostName(), port,
                null);
        LOG.info("Got a registration response " + resp);
        LOG.info("Max Capability " + resp.getMaximumResourceCapability());
        rmClient.setMaxResource(resp.getMaximumResourceCapability());
        LOG.info("Starting HB thread");
        server.initAndStartHeartbeat(rmClient, launcherQueue,
                (Integer) storm_conf.get(Config.MASTER_HEARTBEAT_INTERVAL_MILLIS));
        LOG.info("Starting launcher");
        initAndStartLauncher(rmClient, launcherQueue);
        rmClient.startAllSupervisors();
        LOG.info("Starting Master Thrift Server");
        server.serve();
        LOG.info("StormAMRMClient::unregisterApplicationMaster");
        rmClient.unregisterApplicationMaster(FinalApplicationStatus.SUCCEEDED, "AllDone", null);
    } finally {
        if (server.isServing()) {
            LOG.info("Stop Master Thrift Server");
            server.stop();
        }
        LOG.info("Stop RM client");
        rmClient.stop();
    }
    System.exit(0);
}

From source file:edu.ehu.galan.lite.Lite.java

/**
 * Main entry point for LiTe from the command Line use -h option for help
 *
 * @param args//from  ww  w . j a  va2  s  .  c om
 */
public static void main(String[] args) {

    // create Options object
    Options options = new Options();
    Option corpus = new Option("c", true,
            "the location (directory) of the corpus to process, containing only one document at the moment");
    Option language = new Option("l", true,
            "the language of the corpus (lowercase ISO format, for example 'en'");
    Option algorithms = new Option("a", true, "the algorithms you want to process separated by commas: \n"
            + "see the documentation for see the available algorithms for each language");
    Option help = new Option("h", false, "print this message");
    Option resources = new Option("r", true, "the location of the lite resources folder");
    Option output = new Option("o", true,
            "The directory where the results will be stored, by default the one where the vm has been launched");
    Option listAlgs = new Option("listAlgs", false,
            " Algorithm list names with the supported languages (remember that the cvalue will be processed chosen or not):\n"
                    + "===================================================\n"
                    + "tfidf => processes the TFIDF algorithm, process terms of the input document using the Wikipedia corpus as IDF (en,es)\n"
                    + "cvalue => processes the CValue altorithm for the inputdocument, CValue is processed whether is chosed or not! (en, es)\n"
                    + "shallow => processes the shallow parsing grammar algorithm (en)\n"
                    + "rake => processes the rake algorithm (language agnostig)\n"
                    + "kpminer => processes the KPMiner algorithm (en)\n"
                    + "chisquare => processes the ChiSquare using the NLTK toolkit (language agnostic)\n"
                    + "pmi=> processes the Point Mutual Information using the NLTK toolkit (language agnostic)\n"
                    + "likehood=> processes the Likehood Ratio using the NLTK toolkit (language agnostic)\n"
                    + "tstudent=> processes the T-Student using the NLTK toolkit (language agnostic)\n"
                    + "rawfreq=> processes the raw frequency algorithm using the NLTK toolkit (language agnostic)\n"
                    + "freelingner=> processes the FreeLing ner algorithm via external call(es, en)\n");
    options.addOption(resources);
    options.addOption(corpus);
    options.addOption(language);
    options.addOption(algorithms);
    options.addOption(listAlgs);
    options.addOption(output);
    // automatically generate the help statement
    HelpFormatter formatter = new HelpFormatter();
    String[] s = new String[] {};
    // create the parser
    CommandLineParser parser = new org.apache.commons.cli.GnuParser();
    try {
        // parse the command line arguments
        CommandLine line = parser.parse(options, args);
        if (line.hasOption('c') && line.hasOption('l') && line.hasOption('a') && line.hasOption('r')) {
            if (!line.getOptionValue('l').equals("en") && !line.getOptionValue("l").equals("es")) {
                System.out.println(
                        "Supported languages \"en\" or \"es\", however you may use the statistical algorithms via the API");
            } else {
                String outputDir = "";
                if (line.hasOption('o')) {
                    outputDir = line.getOptionValue('o');
                }
                String lang = line.getOptionValue('l');
                Corpus cor = new Corpus(line.getOptionValue('l'));
                cor.loadCorpus(line.getOptionValue('c'), Document.SourceType.wikipedia);
                String res = line.getOptionValue('r');
                List<String> algs = Arrays.asList(line.getOptionValue('a').split(","));
                System.out.println("Processing.... (it may take a while...)");
                runner(lang, res + File.separator, algs, cor, outputDir);
            }
        }
        if (line.hasOption('c') && line.hasOption('l') && line.hasOption('r')) {
            if (!line.getOptionValue('l').equals("en") && !line.getOptionValue("l").equals("es")) {
                System.out.println(
                        "Supported languages \"en\" or \"es\", however you may use the statistical algorithms via the API");
            } else {
                String outputDir = "";
                if (line.hasOption('o')) {
                    outputDir = line.getOptionValue('o');
                }
                System.out.println(
                        "Processing with default algorithms (TFIDF/CValue).... (it may take a while...)");
                Corpus cor = new Corpus(line.getOptionValue('l'));
                String res = line.getOptionValue('r');
                cor.loadCorpus(line.getOptionValue('c'), Document.SourceType.wikipedia);
                String lang = line.getOptionValue('l');
                List<String> algos = null;
                switch (lang) {
                case "es": {
                    String[] algs = { "cvalue", "tfidf", "rake" };
                    algos = Arrays.asList(algs);
                    break;
                }
                case "en": {
                    String[] algs = { "cvalue", "tfidf", "rake" };
                    algos = Arrays.asList(algs);
                    break;
                }
                }
                runner(lang, res + File.separator, algos, cor, outputDir);
            }
        } else if (line.hasOption("h")) {
            formatter.printHelp("LiTe: a language indepent term extractor", options);
        } else if (line.getOptions().length == 0) {
            formatter.printHelp("LiTe: a language indepent term extractor", options);
        } else {
            System.err.println("The 'c', 'l' and 'r' arguments are required \n");
            formatter.printHelp("LiTe: a language indepent term extractor", options);
        }
    } catch (ParseException exp) {
        // oops, something went wrong
        System.err.println("Parsing failed.  Reason: " + exp.getMessage() + "\n");
        formatter.printHelp("LiTe: a language indepent term extractor", options);

    }

}

From source file:cnxchecker.Client.java

public static void main(String[] args) {
    Options options = new Options();
    options.addOption("H", "host", true, "Remote IP address");
    options.addOption("p", "port", true, "Remote TCP port");
    options.addOption("s", "size", true, "Packet size in bytes (1 KiB)");
    options.addOption("f", "freq", true, "Packets per seconds  (1 Hz)");
    options.addOption("w", "workers", true, "Number of Workers (1)");
    options.addOption("d", "duration", true, "Duration of the test in seconds (60 s)");
    options.addOption("h", "help", false, "Print help");
    CommandLineParser parser = new GnuParser();
    try {/*from  w  ww  .j a v  a  2 s  . c  o m*/
        CommandLine cmd = parser.parse(options, args);

        if (cmd.hasOption("h")) {
            HelpFormatter hf = new HelpFormatter();
            hf.printHelp("client", options);
            System.exit(0);
        }

        // host
        InetAddress ia = null;
        if (cmd.hasOption("H")) {
            String host = cmd.getOptionValue("H");

            try {
                ia = InetAddress.getByName(host);
            } catch (UnknownHostException e) {
                printAndExit("Unknown host: " + host);
            }
        } else {
            printAndExit("Host option is mandatory");
        }

        // port
        int port = 0;
        if (cmd.hasOption("p")) {
            try {
                port = Integer.parseInt(cmd.getOptionValue("p"));
            } catch (NumberFormatException e) {
                printAndExit("Invalid port number " + cmd.getOptionValue("p"));
            }

            if (port < 0 || port > 65535) {
                printAndExit("Invalid port number " + port);
            }
        }

        // size
        int size = 1024;
        if (cmd.hasOption("s")) {
            try {
                size = Integer.parseInt(cmd.getOptionValue("s"));
            } catch (NumberFormatException e) {
                printAndExit("Invalid packet size " + cmd.getOptionValue("s"));
            }

            if (size < 0) {
                printAndExit("Invalid packet size: " + port);
            }
        }

        // freq
        double freq = 1;
        if (cmd.hasOption("f")) {
            try {
                freq = Double.parseDouble(cmd.getOptionValue("f"));
            } catch (NumberFormatException e) {
                printAndExit("Invalid frequency: " + cmd.getOptionValue("f"));
            }

            if (freq <= 0) {
                printAndExit("Invalid frequency: " + freq);
            }
        }

        // workers
        int workers = 1;
        if (cmd.hasOption("w")) {
            try {
                workers = Integer.parseInt(cmd.getOptionValue("w"));
            } catch (NumberFormatException e) {
                printAndExit("Invalid number of workers: " + cmd.getOptionValue("w"));
            }

            if (workers < 0) {
                printAndExit("Invalid number of workers: " + workers);
            }
        }

        // duration
        int duration = 60000;
        if (cmd.hasOption("d")) {
            try {
                duration = Integer.parseInt(cmd.getOptionValue("d")) * 1000;
            } catch (NumberFormatException e) {
                printAndExit("Invalid duration: " + cmd.getOptionValue("d"));
            }

            if (duration < 0) {
                printAndExit("Invalid duration: " + duration);
            }
        }

        Client client = new Client(ia, port, size, freq, workers, duration);
        client.doit();
    } catch (ParseException e) {
        printAndExit("Failed to parse options: " + e.getMessage());
    }

    System.exit(0);
}

From source file:com.microsoft.kafkaavailability.App.java

public static void main(String[] args) throws IOException, MetaDataManagerException, InterruptedException {
    System.out.println("Starting KafkaAvailability Tool");
    IPropertiesManager appPropertiesManager = new PropertiesManager<AppProperties>("appProperties.json",
            AppProperties.class);
    appProperties = (AppProperties) appPropertiesManager.getProperties();
    Options options = new Options();
    options.addOption("r", "run", true,
            "Number of runs. Don't use this argument if you want to run infintely.");
    options.addOption("s", "sleep", true,
            "Time (in milliseconds) to sleep between each run. Default is 300000");
    Option clusterOption = Option.builder("c").hasArg().required(true).longOpt("cluster")
            .desc("(REQUIRED) Cluster name").build();
    options.addOption(clusterOption);//from www .  j a  v a 2  s  .  c o  m
    CommandLineParser parser = new DefaultParser();
    HelpFormatter formatter = new HelpFormatter();
    try {
        // parse the command line arguments
        CommandLine line = parser.parse(options, args);
        int howManyRuns;

        m_cluster = line.getOptionValue("cluster");
        MDC.put("cluster", m_cluster);

        if (line.hasOption("sleep")) {
            m_sleepTime = Integer.parseInt(line.getOptionValue("sleep"));
        }
        if (line.hasOption("run")) {
            howManyRuns = Integer.parseInt(line.getOptionValue("run"));
            for (int i = 0; i < howManyRuns; i++) {
                InitMetrics();
                RunOnce();
                Thread.sleep(m_sleepTime);
            }
        } else {
            while (true) {
                InitMetrics();
                RunOnce();
                Thread.sleep(m_sleepTime);
            }
        }
    } catch (ParseException exp) {
        // oops, something went wrong
        System.err.println("Parsing failed.  Reason: " + exp.getMessage());
        formatter.printHelp("KafkaAvailability", options);
    }

}

From source file:cc.twittertools.corpus.demo.ReadStatuses.java

@SuppressWarnings("static-access")
public static void main(String[] args) throws Exception {
    Options options = new Options();
    options.addOption(OptionBuilder.withArgName("path").hasArg().withDescription("input directory or file")
            .create(INPUT_OPTION));/*from w w  w .j a v  a2 s  .c  o m*/
    options.addOption(VERBOSE_OPTION, false, "print logging output every 10000 tweets");
    options.addOption(DUMP_OPTION, false, "dump statuses");

    CommandLine cmdline = null;
    CommandLineParser parser = new GnuParser();
    try {
        cmdline = parser.parse(options, args);
    } catch (ParseException exp) {
        System.err.println("Error parsing command line: " + exp.getMessage());
        System.exit(-1);
    }

    if (!cmdline.hasOption(INPUT_OPTION)) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(ReadStatuses.class.getName(), options);
        System.exit(-1);
    }

    PrintStream out = new PrintStream(System.out, true, "UTF-8");

    StatusStream stream;
    // Figure out if we're reading from HTML SequenceFiles or JSON.
    File file = new File(cmdline.getOptionValue(INPUT_OPTION));
    if (!file.exists()) {
        System.err.println("Error: " + file + " does not exist!");
        System.exit(-1);
    }

    if (file.isDirectory()) {
        stream = new JsonStatusCorpusReader(file);
    } else {
        stream = new JsonStatusBlockReader(file);
    }

    int cnt = 0;
    Status status;
    while ((status = stream.next()) != null) {
        if (cmdline.hasOption(DUMP_OPTION)) {
            String text = status.getText();
            if (text != null) {
                text = text.replaceAll("\\s+", " ");
                text = text.replaceAll("\0", "");
            }
            out.println(String.format("%d\t%s\t%s\t%s", status.getId(), status.getScreenname(),
                    status.getCreatedAt(), text));
        }
        cnt++;
        if (cnt % 10000 == 0 && cmdline.hasOption(VERBOSE_OPTION)) {
            LOG.info(cnt + " statuses read");
        }
    }
    stream.close();
    LOG.info(String.format("Total of %s statuses read.", cnt));
}

From source file:jmdbtools.JMdbTools.java

public static void main(String[] args) {
    System.out.println("[INFO] Starting mdb file processing");
    Options options = createOptions();//from   w  ww.  j a v a 2 s  . c  o  m
    CommandLineParser parser = new BasicParser();
    try {
        CommandLine cmd = parser.parse(options, args);

        if (cmd.hasOption("f")) {

            JMdbTools tool = new JMdbTools(cmd);

            tool.processOptions(cmd);

            if (cmd.hasOption("s")) {
                tool.showStats();
            }
            //export
            if (cmd.hasOption("e")) {
                tool.exportCSV();
            }

            //export to mysql
            if (cmd.hasOption("db")) {

                tool.exportToMySQL();
            }

        } else {
            System.out.println("[ERROR] No file parameter given!");

        }
    } catch (ParseException e) {
        e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
    }
}

From source file:de.l3s.content.mapred.WikipediaPagesBz2InputStream.java

@SuppressWarnings("static-access")
public static void main(String[] args) throws Exception {
    Options options = new Options();
    options.addOption(OptionBuilder.withArgName("path").hasArg().withDescription("gzipped XML dump file")
            .create(INPUT_OPTION));/*from   w  w  w.jav a2 s . c  o m*/
    options.addOption(OptionBuilder.withArgName("lang").hasArg().withDescription("output location")
            .create(LANGUAGE_OPTION));

    CommandLine cmdline = null;
    CommandLineParser parser = new GnuParser();
    try {
        cmdline = parser.parse(options, args);
    } catch (ParseException exp) {
        System.err.println("Error parsing command line: " + exp.getMessage());
        System.exit(-1);
    }

    if (!cmdline.hasOption(INPUT_OPTION)) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(WikipediaPagesBz2InputStream.class.getCanonicalName(), options);
        ToolRunner.printGenericCommandUsage(System.out);
        System.exit(-1);
    }

    String path = cmdline.getOptionValue(INPUT_OPTION);
    String lang = cmdline.hasOption(LANGUAGE_OPTION) ? cmdline.getOptionValue(LANGUAGE_OPTION) : "en";
    WikipediaPage p = WikipediaPageFactory.createWikipediaPage(lang);

    WikipediaPagesBz2InputStream stream = new WikipediaPagesBz2InputStream(path);
    while (stream.readNext(p)) {
        System.out.println(p.getTitle() + "\t" + p.getDocid());
    }
}