Example usage for org.apache.commons.cli CommandLineParser parse

List of usage examples for org.apache.commons.cli CommandLineParser parse

Introduction

In this page you can find the example usage for org.apache.commons.cli CommandLineParser parse.

Prototype

CommandLine parse(Options options, String[] arguments) throws ParseException;

Source Link

Document

Parse the arguments according to the specified options.

Usage

From source file:edu.umd.cloud9.example.bigram.AnalyzeBigramCount.java

@SuppressWarnings({ "static-access" })
public static void main(String[] args) {
    Options options = new Options();

    options.addOption(OptionBuilder.withArgName("path").hasArg().withDescription("input path").create(INPUT));

    CommandLine cmdline = null;//  w ww .  j  a  va  2 s .c  om
    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)) {
        System.out.println("args: " + Arrays.toString(args));
        HelpFormatter formatter = new HelpFormatter();
        formatter.setWidth(120);
        formatter.printHelp(AnalyzeBigramCount.class.getName(), options);
        ToolRunner.printGenericCommandUsage(System.out);
        System.exit(-1);
    }

    String inputPath = cmdline.getOptionValue(INPUT);
    System.out.println("input path: " + inputPath);
    List<PairOfWritables<Text, IntWritable>> bigrams = SequenceFileUtils.readDirectory(new Path(inputPath));

    Collections.sort(bigrams, new Comparator<PairOfWritables<Text, IntWritable>>() {
        public int compare(PairOfWritables<Text, IntWritable> e1, PairOfWritables<Text, IntWritable> e2) {
            if (e2.getRightElement().compareTo(e1.getRightElement()) == 0) {
                return e1.getLeftElement().compareTo(e2.getLeftElement());
            }

            return e2.getRightElement().compareTo(e1.getRightElement());
        }
    });

    int singletons = 0;
    int sum = 0;
    for (PairOfWritables<Text, IntWritable> bigram : bigrams) {
        sum += bigram.getRightElement().get();

        if (bigram.getRightElement().get() == 1) {
            singletons++;
        }
    }

    System.out.println("total number of unique bigrams: " + bigrams.size());
    System.out.println("total number of bigrams: " + sum);
    System.out.println("number of bigrams that appear only once: " + singletons);

    System.out.println("\nten most frequent bigrams: ");

    Iterator<PairOfWritables<Text, IntWritable>> iter = Iterators.limit(bigrams.iterator(), 10);
    while (iter.hasNext()) {
        PairOfWritables<Text, IntWritable> bigram = iter.next();
        System.out.println(bigram.getLeftElement() + "\t" + bigram.getRightElement());
    }
}

From source file:net.anthonypoon.ngram.correlation.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("t", "target", true, "Correlation Target URI"); // Can only take file from S# or HDFS
    options.addOption("L", "lag", true, "Lag factor");
    options.addOption("T", "threshold", true, "Correlation threshold");
    CommandLineParser parser = new GnuParser();
    CommandLine cmd = parser.parse(options, args);
    Configuration conf = new Configuration();
    if (cmd.hasOption("lag")) {
        conf.set("lag", cmd.getOptionValue("lag"));
    }//from ww  w. j ava 2  s .  co  m
    if (cmd.hasOption("threshold")) {
        conf.set("threshold", cmd.getOptionValue("threshold"));
    }
    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("target")) {
        conf.set("target", cmd.getOptionValue("target"));
    } else {
        throw new Exception("Missing correlation target file uri");
    }
    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-correlation":
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(Text.class);
        for (String inputPath : cmd.getOptionValue("input").split(",")) {
            MultipleInputs.addInputPath(job, new Path(inputPath), KeyValueTextInputFormat.class,
                    CorrelationMapper.class);
        }
        job.setReducerClass(CorrelationReducer.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);
}

From source file:cc.twittertools.util.ExtractSubcollection.java

@SuppressWarnings("static-access")
public static void main(String[] args) throws Exception {
    Options options = new Options();

    options.addOption(OptionBuilder.withArgName("dir").hasArg().withDescription("source collection directory")
            .create(COLLECTION_OPTION));
    options.addOption(/*www .j  a va 2s .c o  m*/
            OptionBuilder.withArgName("file").hasArg().withDescription("list of tweetids").create(ID_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(COLLECTION_OPTION) || !cmdline.hasOption(ID_OPTION)) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(ExtractSubcollection.class.getName(), options);
        System.exit(-1);
    }

    String collectionPath = cmdline.getOptionValue(COLLECTION_OPTION);

    LongOpenHashSet tweetids = new LongOpenHashSet();
    File tweetidsFile = new File(cmdline.getOptionValue(ID_OPTION));
    if (!tweetidsFile.exists()) {
        System.err.println("Error: " + tweetidsFile + " does not exist!");
        System.exit(-1);
    }
    LOG.info("Reading tweetids from " + tweetidsFile);

    FileInputStream fin = new FileInputStream(tweetidsFile);
    BufferedReader br = new BufferedReader(new InputStreamReader(fin));

    String s;
    while ((s = br.readLine()) != null) {
        tweetids.add(Long.parseLong(s));
    }
    br.close();
    fin.close();
    LOG.info("Read " + tweetids.size() + " tweetids.");

    File file = new File(collectionPath);
    if (!file.exists()) {
        System.err.println("Error: " + file + " does not exist!");
        System.exit(-1);
    }

    PrintStream out = new PrintStream(System.out, true, "UTF-8");
    StatusStream stream = new JsonStatusCorpusReader(file);
    Status status;
    while ((status = stream.next()) != null) {
        if (tweetids.contains(status.getId())) {
            out.println(status.getJsonObject().toString());
        }
    }
    stream.close();
    out.close();
}

From source file:com.ibm.crail.namenode.NameNode.java

public static void main(String args[]) throws Exception {
    LOG.info("initalizing namenode ");
    CrailConfiguration conf = new CrailConfiguration();
    CrailConstants.updateConstants(conf);

    URI uri = CrailUtils.getPrimaryNameNode();
    String address = uri.getHost();
    int port = uri.getPort();

    if (args != null) {
        Option addressOption = Option.builder("a").desc("ip address namenode is started on").hasArg().build();
        Option portOption = Option.builder("p").desc("port namenode is started on").hasArg().build();
        Options options = new Options();
        options.addOption(portOption);//from  w w w  .j  a  v a2s .c  o m
        options.addOption(addressOption);
        CommandLineParser parser = new DefaultParser();

        try {
            CommandLine line = parser.parse(options, Arrays.copyOfRange(args, 0, args.length));
            if (line.hasOption(addressOption.getOpt())) {
                address = line.getOptionValue(addressOption.getOpt());
            }
            if (line.hasOption(portOption.getOpt())) {
                port = Integer.parseInt(line.getOptionValue(portOption.getOpt()));
            }
        } catch (ParseException e) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("Namenode", options);
            System.exit(-1);
        }
    }

    String namenode = "crail://" + address + ":" + port;
    long serviceId = CrailUtils.getServiceId(namenode);
    long serviceSize = CrailUtils.getServiceSize();
    if (!CrailUtils.verifyNamenode(namenode)) {
        throw new Exception("Namenode address/port [" + namenode
                + "] has to be listed in crail.namenode.address " + CrailConstants.NAMENODE_ADDRESS);
    }

    CrailConstants.NAMENODE_ADDRESS = namenode + "?id=" + serviceId + "&size=" + serviceSize;
    CrailConstants.printConf();
    CrailConstants.verify();

    RpcNameNodeService service = RpcNameNodeService.createInstance(CrailConstants.NAMENODE_RPC_SERVICE);
    RpcBinding rpcBinding = RpcBinding.createInstance(CrailConstants.NAMENODE_RPC_TYPE);
    rpcBinding.init(conf, null);
    rpcBinding.printConf(LOG);
    rpcBinding.run(service);
    System.exit(0);
    ;
}

From source file:cloudnet.examples.evaluations.ConfigurableEvaluation.java

/**
 * @param args the command line arguments
 *//*from ww  w .  j  a  v a 2 s .  c o m*/
public static void main(String[] args) {
    Options options = makeOptions();
    CommandLineParser parser = new DefaultParser();
    try {

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

        if (cmd.hasOption("help")) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("vmPlacementSimApp", options);
            return;
        }

        // apply options
        applyOptions(cmd);

        // run simulation
        runSimulation();

    } catch (ParseException exp) {
        System.err.println("Parsing failed.  Reason: " + exp.getMessage());
    }

    // exit in order to stop R-Environment if it is used.
    System.exit(0);
}

From source file:com.act.utils.parser.UniprotInterpreter.java

public static void main(String[] args)
        throws ParserConfigurationException, IOException, SAXException, CompoundNotFoundException {
    Options opts = new Options();
    for (Option.Builder b : OPTION_BUILDERS) {
        opts.addOption(b.build());/*from w  w w .j  a v a2s.  co  m*/
    }

    CommandLine cl = null;
    try {
        CommandLineParser parser = new DefaultParser();
        cl = parser.parse(opts, args);
    } catch (ParseException e) {
        LOGGER.error("Argument parsing failed: %s", e.getMessage());
        HELP_FORMATTER.printHelp(UniprotInterpreter.class.getCanonicalName(), HELP_MESSAGE, opts, null, true);
        System.exit(1);
    }

    if (cl.hasOption("help")) {
        HELP_FORMATTER.printHelp(UniprotInterpreter.class.getCanonicalName(), HELP_MESSAGE, opts, null, true);
        System.exit(1);
    }

    File uniprotFile = new File(cl.getOptionValue(OPTION_UNIPROT_PATH));

    if (!uniprotFile.exists()) {
        String msg = "Uniprot file path is null";
        LOGGER.error(msg);
        throw new RuntimeException(msg);
    } else {
        UniprotInterpreter reader = new UniprotInterpreter(uniprotFile);
        reader.init();
    }
}

From source file:com.k42b3.quantum.Entry.java

public static void main(String[] args) throws Exception {
    // logging/*from w w w  . j ava2s  .  co  m*/
    Layout layout = new PatternLayout(PatternLayout.TTCC_CONVERSION_PATTERN);

    Logger.getLogger("com.k42b3.quantum").addAppender(new WriterAppender(layout, System.out));

    // options
    Options options = new Options();
    options.addOption("p", "port", false, "Port for the web server default is 8080");
    options.addOption("i", "interval", false,
            "The interval how often each worker gets triggered in minutes default is 2");
    options.addOption("d", "database", false, "Path to the sqlite database default is \"quantum.db\"");
    options.addOption("l", "log", false,
            "Defines the log level default is ERROR possible is (ALL, TRACE, DEBUG, INFO, WARN, ERROR, FATAL, OFF)");
    options.addOption("v", "version", false, "Shows the current version");
    options.addOption("h", "help", false, "Shows the help");

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

    // start app
    Quantum app = new Quantum();

    if (cmd.hasOption("p")) {
        try {
            int port = Integer.parseInt(cmd.getOptionValue("p"));

            app.setPort(port);
        } catch (NumberFormatException e) {
            Logger.getLogger("com.k42b3.quantum").info("Port must be an integer");
        }
    }

    if (cmd.hasOption("i")) {
        try {
            int pollInterval = Integer.parseInt(cmd.getOptionValue("i"));

            app.setPollInterval(pollInterval);
        } catch (NumberFormatException e) {
            Logger.getLogger("com.k42b3.quantum").info("Interval must be an integer");
        }
    }

    if (cmd.hasOption("d")) {
        String dbPath = cmd.getOptionValue("d");

        if (!dbPath.isEmpty()) {
            app.setDbPath(dbPath);
        }
    }

    if (cmd.hasOption("l")) {
        Logger.getLogger("com.k42b3.quantum").setLevel(Level.toLevel(cmd.getOptionValue("l")));
    } else {
        Logger.getLogger("com.k42b3.quantum").setLevel(Level.ERROR);
    }

    if (cmd.hasOption("v")) {
        System.out.println("Version: " + Quantum.VERSION);
        System.exit(0);
    }

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

    app.run();
}

From source file:msuresh.raftdistdb.AtomixDB.java

/**
 * Main Method which runs a Apache CLI which takes 3 different options for the 3 operations <br>
 * @param args <br>/*  w ww . j a  v  a  2s  . c om*/
 * Options : <br>
 * -setup numberOfReplicas numberOfPartitions -- which sets the system given thenumber of partitions number of replicas per partition<br>
 * -set key Value -- adds a key value pair to the DB<br>
 * -get key -- returns a value for the key if it exists<br>
 * @throws InterruptedException 
 */
public static void main(String[] args) throws InterruptedException, ExecutionException, FileNotFoundException {
    Options options = new Options();
    Option opt = new Option("setup", true, "Sets up the replica that run the Raft Consensus Algorithm.");
    opt.setArgs(3);
    options.addOption(opt);
    opt = new Option("set", true, " Add a key-value pair into the Distributed Database.");
    opt.setArgs(3);
    options.addOption(opt);
    opt = new Option("get", true, "Given a key gets the value from the DB");
    opt.setArgs(2);
    options.addOption(opt);
    opt = new Option("clean", false, "Cleans the state information.");
    options.addOption(opt);
    opt = new Option("test", true, "Cleans the state information.");
    opt.setArgs(2);
    options.addOption(opt);
    try {
        CommandLineParser parser = new BasicParser();
        CommandLine line = null;
        line = parser.parse(options, args);
        if (line.hasOption("setup")) {
            String[] vals = line.getOptionValues("setup");
            System.out.println(vals[0]);
            RaftCluster.createCluster(vals[0], Integer.parseInt(vals[1]), Integer.parseInt(vals[2]));
        } else if (line.hasOption("set")) {
            String[] vals = line.getOptionValues("set");
            addKey(vals[0], vals[1], vals[2]);
        } else if (line.hasOption("get")) {
            String[] vals = line.getOptionValues("get");
            getKey(vals[0], vals[1]);
        } else if (line.hasOption("clean")) {
            cleanState();
        } else if (line.hasOption("test")) {
            String[] vals = line.getOptionValues("test");
            TestAtomix.createCluster(vals[0], Integer.parseInt(vals[1]));
        }
    } catch (ParseException exp) {
        System.out.println("Unexpected exception:" + exp.getMessage());
    }
}

From source file:ca.cutterslade.match.scheduler.Main.java

public static void main(final String[] args) throws InterruptedException {
    final CommandLineParser parser = new PosixParser();
    try {/*  w w w  . j a v a 2s  . c  om*/
        final CommandLine line = parser.parse(OPTIONS, args);
        final int teams = Integer.parseInt(line.getOptionValue('t'));
        final int tiers = Integer.parseInt(line.getOptionValue('r'));
        final int gyms = Integer.parseInt(line.getOptionValue('g'));
        final int courts = Integer.parseInt(line.getOptionValue('c'));
        final int times = Integer.parseInt(line.getOptionValue('m'));
        final int days = Integer.parseInt(line.getOptionValue('d'));
        final int size = Integer.parseInt(line.getOptionValue('z'));
        final Configuration config;
        if (line.hasOption("random"))
            config = Configuration.RANDOM_CONFIGURATION;
        else
            config = new Configuration(ImmutableMap.<SadFaceFactor, Integer>of(),
                    line.hasOption("randomMatches"), line.hasOption("randomSlots"),
                    line.hasOption("randomDays"));
        final Scheduler s = new Scheduler(config, teams, tiers, gyms, courts, times, days, size);
        System.out.println(summary(s));
    } catch (final ParseException e) {
        final HelpFormatter f = new HelpFormatter();
        final PrintWriter pw = new PrintWriter(System.err);
        f.printHelp(pw, 80, "match-scheduler", null, OPTIONS, 2, 2, null, true);
        pw.println(
                "For example: match-scheduler -t 48 -r 3 -d 12 -m 2 -g 3 -c 2 -z 4 --randomMatches --randomSlots");
        pw.close();
    }
}

From source file:com.dattack.dbcopy.cli.DbCopyCli.java

/**
 * The <code>main</code> method.
 *
 * @param args/*  w ww  .  j  av a  2  s.c  o  m*/
 *            the program arguments
 */
public static void main(final String[] args) {

    final Options options = createOptions();

    try {
        final CommandLineParser parser = new DefaultParser();
        final CommandLine cmd = parser.parse(options, args);
        final String[] filenames = cmd.getOptionValues(FILE_OPTION);
        final String[] jobNames = cmd.getOptionValues(JOB_NAME_OPTION);
        final String[] propertiesFiles = cmd.getOptionValues(PROPERTIES_OPTION);

        HashSet<String> jobNameSet = null;
        if (jobNames != null) {
            jobNameSet = new HashSet<>(Arrays.asList(jobNames));
        }

        CompositeConfiguration configuration = new CompositeConfiguration();
        if (propertiesFiles != null) {
            for (final String fileName : propertiesFiles) {
                configuration.addConfiguration(new PropertiesConfiguration(fileName));
            }
        }

        final DbCopyEngine ping = new DbCopyEngine();
        ping.execute(filenames, jobNameSet, configuration);

    } catch (@SuppressWarnings("unused") final ParseException e) {
        showUsage(options);
    } catch (final ConfigurationException | DattackParserException e) {
        System.err.println(e.getMessage());
    }
}