Example usage for org.apache.commons.cli BasicParser BasicParser

List of usage examples for org.apache.commons.cli BasicParser BasicParser

Introduction

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

Prototype

BasicParser

Source Link

Usage

From source file:edu.usc.pgroup.floe.client.commands.Signal.java

/**
 * Entry point for Scale command.//ww w  . ja v  a 2s. c  o  m
 * @param args command line arguments sent by the floe.py script.
 */
public static void main(final String[] args) {

    Options options = new Options();

    Option appOption = OptionBuilder.withArgName("name").hasArg().isRequired()
            .withDescription("Application Name").create("app");

    Option pelletNameOption = OptionBuilder.withArgName("name").hasArg().isRequired()
            .withDescription("Pellet Name").create("pellet");

    Option signalOption = OptionBuilder.withArgName("data").hasArg().withType(new String())
            .withDescription("signal data to send to the pellet").create("data");

    options.addOption(appOption);
    options.addOption(pelletNameOption);
    options.addOption(signalOption);

    CommandLineParser parser = new BasicParser();
    CommandLine line;

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

    } catch (ParseException e) {
        LOGGER.error("Invalid command: " + e.getMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("scale options", options);
        return;
    }

    String app = line.getOptionValue("app");
    String pellet = line.getOptionValue("pellet");
    String data = line.getOptionValue("data");

    LOGGER.info("Application: {}", app);
    LOGGER.info("Pellet: {}", pellet);
    LOGGER.info("data: {}", data);

    byte[] datab = Utils.serialize(data);
    try {
        TSignal signal = new TSignal();
        signal.set_destApp(app);
        signal.set_destPellet(pellet);
        signal.set_data(datab);
        FloeClient.getInstance().getClient().signal(signal);
    } catch (TException e) {
        LOGGER.error("Error while connecting to the coordinator: {}", e);
    }
}

From source file:de.citec.csra.elancsv.parser.SimpleParser.java

public static void main(String[] args) throws IOException, ParseException {

    Options opts = new Options();
    opts.addOption("file", true, "Tab-separated ELAN export file to load.");
    opts.addOption("tier", true,
            "Tier to analyze. Optional: Append ::num to interpret annotations numerically.");
    opts.addOption("format", true,
            "How to read information from the file name. %V -> participant, %A -> annoatator, %C -> condition, e.g. \"%V - %A\"");
    opts.addOption("help", false, "Print this help and exit");

    CommandLineParser parser = new BasicParser();
    CommandLine cmd = parser.parse(opts, args);
    if (cmd.hasOption("help")) {
        helpExit(opts, "where OPTION includes:");
    }/*  w  ww . java  2 s. c o m*/

    String infile = cmd.getOptionValue("file");
    if (infile == null) {
        helpExit(opts, "Error: no file given.");
    }

    String format = cmd.getOptionValue("format");
    if (format == null) {
        helpExit(opts, "Error: no format given.");
    }

    String tier = cmd.getOptionValue("tier");
    if (tier == null) {
        helpExit(opts, "Error: no tier given.");
    }

    //      TODO count values in annotations (e.g. search all robot occurrences)
    String[] tn = tier.split("::");
    boolean numeric = false;
    if (tn.length == 2 && tn[1].equals("num")) {
        numeric = true;
        tier = tn[0];
    }

    format = "^" + format + "$";
    format = format.replaceFirst("%V", "(?<V>.*?)");
    format = format.replaceFirst("%A", "(?<A>.*?)");
    format = format.replaceFirst("%C", "(?<C>.*?)");
    Pattern pa = Pattern.compile(format);

    Map<String, Participant> participants = new HashMap<>();
    BufferedReader br = new BufferedReader(new FileReader(infile));
    String line;
    int lineno = 0;
    while ((line = br.readLine()) != null) {
        String[] parts = line.split("\t");
        lineno++;
        if (parts.length < 5) {
            System.err.println("WARNING: line '" + lineno + "' too short '" + line + "'");
            continue;
        }
        Annotation a = new Annotation(Long.valueOf(parts[ElanFormat.START.field]),
                Long.valueOf(parts[ElanFormat.STOP.field]), Long.valueOf(parts[ElanFormat.DURATION.field]),
                parts[ElanFormat.VALUE.field]);
        String tname = parts[ElanFormat.TIER.field];
        String file = parts[ElanFormat.FILE.field].replaceAll(".eaf", "");

        Matcher m = pa.matcher(file);
        String vp = file;
        String condition = "?";
        String annotator = "?";
        String participantID = vp;

        if (m.find()) {
            vp = m.group("V");
            if (format.indexOf("<A>") > 0) {
                annotator = m.group("A");
            }

            if (format.indexOf("<C>") > 0) {
                condition = m.group("C");
            }
        }
        participantID = vp + ";" + annotator;

        if (!participants.containsKey(participantID)) {
            participants.put(participantID, new Participant(vp, condition, annotator));
        }
        Participant p = participants.get(participantID);

        if (!p.tiers.containsKey(tname)) {
            p.tiers.put(tname, new Tier(tname));
        }

        p.tiers.get(tname).annotations.add(a);

    }

    Map<String, Map<String, Number>> values = new HashMap<>();
    Set<String> rownames = new HashSet<>();

    String allCountKey = "c: all values";
    String allDurationKey = "d: all values";
    String allMeanKey = "m: all values";

    for (Map.Entry<String, Participant> e : participants.entrySet()) {
        //         System.out.println(e);
        Tier t = e.getValue().tiers.get(tier);
        String participantID = e.getKey();

        if (!values.containsKey(participantID)) {
            values.put(participantID, new HashMap<String, Number>());
        }
        Map<String, Number> row = values.get(participantID); //participant id

        if (t != null) {

            row.put(allCountKey, 0l);
            row.put(allDurationKey, 0l);
            row.put(allMeanKey, 0l);

            for (Annotation a : t.annotations) {

                long countAll = (long) row.get(allCountKey) + 1;
                long durationAll = (long) row.get(allDurationKey) + a.duration;
                long meanAll = durationAll / countAll;

                row.put(allCountKey, countAll);
                row.put(allDurationKey, durationAll);
                row.put(allMeanKey, meanAll);

                if (!numeric) {
                    String countKey = "c: " + a.value;
                    String durationKey = "d: " + a.value;
                    String meanKey = "m: " + a.value;

                    if (!row.containsKey(countKey)) {
                        row.put(countKey, 0l);
                    }
                    if (!row.containsKey(durationKey)) {
                        row.put(durationKey, 0l);
                    }
                    if (!row.containsKey(meanKey)) {
                        row.put(meanKey, 0d);
                    }

                    long count = (long) row.get(countKey) + 1;
                    long duration = (long) row.get(durationKey) + a.duration;
                    double mean = duration * 1.0 / count;

                    row.put(countKey, count);
                    row.put(durationKey, duration);
                    row.put(meanKey, mean);

                    rownames.add(countKey);
                    rownames.add(durationKey);
                    rownames.add(meanKey);
                } else {
                    String countKey = "c: " + t.name;
                    String sumKey = "s: " + t.name;
                    String meanKey = "m: " + t.name;

                    if (!row.containsKey(countKey)) {
                        row.put(countKey, 0l);
                    }
                    if (!row.containsKey(sumKey)) {
                        row.put(sumKey, 0d);
                    }
                    if (!row.containsKey(meanKey)) {
                        row.put(meanKey, 0d);
                    }

                    double d = 0;
                    try {
                        d = Double.valueOf(a.value);
                    } catch (NumberFormatException ex) {

                    }

                    long count = (long) row.get(countKey) + 1;
                    double sum = (double) row.get(sumKey) + d;
                    double mean = sum / count;

                    row.put(countKey, count);
                    row.put(sumKey, sum);
                    row.put(meanKey, mean);

                    rownames.add(countKey);
                    rownames.add(sumKey);
                    rownames.add(meanKey);
                }

            }
        }

    }

    ArrayList<String> list = new ArrayList(rownames);
    Collections.sort(list);
    StringBuilder header = new StringBuilder("ID;Annotator;");
    header.append(allCountKey);
    header.append(";");
    header.append(allDurationKey);
    header.append(";");
    header.append(allMeanKey);
    header.append(";");
    for (String l : list) {
        header.append(l);
        header.append(";");
    }
    System.out.println(header);

    for (Map.Entry<String, Map<String, Number>> e : values.entrySet()) {
        StringBuilder row = new StringBuilder(e.getKey());
        row.append(";");
        if (e.getValue().containsKey(allCountKey)) {
            row.append(e.getValue().get(allCountKey));
        } else {
            row.append("0");
        }
        row.append(";");
        if (e.getValue().containsKey(allDurationKey)) {
            row.append(e.getValue().get(allDurationKey));
        } else {
            row.append("0");
        }
        row.append(";");
        if (e.getValue().containsKey(allMeanKey)) {
            row.append(e.getValue().get(allMeanKey));
        } else {
            row.append("0");
        }
        row.append(";");
        for (String l : list) {
            if (e.getValue().containsKey(l)) {
                row.append(e.getValue().get(l));
            } else {
                row.append("0");
            }
            row.append(";");
        }
        System.out.println(row);
    }
}

From source file:baldrickv.s3streamingtool.S3StreamingTool.java

public static void main(String args[]) throws Exception {
    BasicParser p = new BasicParser();

    Options o = getOptions();/*w w  w.  j a  va2s.  c  o m*/

    CommandLine cl = p.parse(o, args);

    if (cl.hasOption('h')) {
        HelpFormatter hf = new HelpFormatter();
        hf.setWidth(80);

        StringBuilder sb = new StringBuilder();

        sb.append("\n");
        sb.append("Upload:\n");
        sb.append("    -u -r creds -s 50M -b my_bucket -f hda1.dump -t 10\n");
        sb.append("Download:\n");
        sb.append("    -d -r creds -s 50M -b my_bucket -f hda1.dump -t 10\n");
        sb.append("Upload encrypted:\n");
        sb.append("    -u -r creds -z -k secret_key -s 50M -b my_bucket -f hda1.dump -t 10\n");
        sb.append("Download encrypted:\n");
        sb.append("    -d -r creds -z -k secret_key -s 50M -b my_bucket -f hda1.dump -t 10\n");
        sb.append("Cleanup in-progress multipart uploads\n");
        sb.append("    -c -r creds -b my_bucket\n");
        System.out.println(sb.toString());

        hf.printHelp("See above", o);

        return;
    }

    int n = 0;
    if (cl.hasOption('d'))
        n++;
    if (cl.hasOption('u'))
        n++;
    if (cl.hasOption('c'))
        n++;
    if (cl.hasOption('m'))
        n++;

    if (n != 1) {
        System.err.println("Must specify at exactly one of -d, -u, -c or -m");
        System.exit(-1);
    }

    if (cl.hasOption('m')) {
        //InputStream in = new java.io.BufferedInputStream(System.in,1024*1024*2);
        InputStream in = System.in;
        System.out.println(TreeHashGenerator.calculateTreeHash(in));
        return;
    }

    require(cl, 'b');

    if (cl.hasOption('d') || cl.hasOption('u')) {
        require(cl, 'f');
    }
    if (cl.hasOption('z')) {
        require(cl, 'k');
    }

    AWSCredentials creds = null;

    if (cl.hasOption('r')) {
        creds = Utils.loadAWSCredentails(cl.getOptionValue('r'));
    } else {
        if (cl.hasOption('i') && cl.hasOption('e')) {
            creds = new BasicAWSCredentials(cl.getOptionValue('i'), cl.getOptionValue('e'));
        } else {

            System.out.println("Must specify either credential file (-r) or AWS key ID and secret (-i and -e)");
            System.exit(-1);
        }
    }

    S3StreamConfig config = new S3StreamConfig();
    config.setEncryption(false);
    if (cl.hasOption('z')) {
        config.setEncryption(true);
        config.setSecretKey(Utils.loadSecretKey(cl.getOptionValue("k")));
    }

    if (cl.hasOption("encryption-mode")) {
        config.setEncryptionMode(cl.getOptionValue("encryption-mode"));
    }
    config.setS3Bucket(cl.getOptionValue("bucket"));
    if (cl.hasOption("file")) {
        config.setS3File(cl.getOptionValue("file"));
    }

    if (cl.hasOption("threads")) {
        config.setIOThreads(Integer.parseInt(cl.getOptionValue("threads")));
    }

    if (cl.hasOption("blocksize")) {
        String s = cl.getOptionValue("blocksize");
        s = s.toUpperCase();
        int multi = 1;

        int end = 0;
        while ((end < s.length()) && (s.charAt(end) >= '0') && (s.charAt(end) <= '9')) {
            end++;
        }
        int size = Integer.parseInt(s.substring(0, end));

        if (end < s.length()) {
            String m = s.substring(end);
            if (m.equals("K"))
                multi = 1024;
            else if (m.equals("M"))
                multi = 1048576;
            else if (m.equals("G"))
                multi = 1024 * 1024 * 1024;
            else if (m.equals("KB"))
                multi = 1024;
            else if (m.equals("MB"))
                multi = 1048576;
            else if (m.equals("GB"))
                multi = 1024 * 1024 * 1024;
            else {
                System.out.println("Unknown suffix on block size.  Only K,M and G understood.");
                System.exit(-1);
            }

        }
        size *= multi;
        config.setBlockSize(size);
    }

    Logger.getLogger("").setLevel(Level.FINE);

    S3StreamingDownload.log.setLevel(Level.FINE);
    S3StreamingUpload.log.setLevel(Level.FINE);

    config.setS3Client(new AmazonS3Client(creds));
    config.setGlacierClient(new AmazonGlacierClient(creds));
    config.getGlacierClient().setEndpoint("glacier.us-west-2.amazonaws.com");

    if (cl.hasOption("glacier")) {
        config.setGlacier(true);
        config.setStorageInterface(new StorageGlacier(config.getGlacierClient()));
    } else {
        config.setStorageInterface(new StorageS3(config.getS3Client()));
    }
    if (cl.hasOption("bwlimit")) {
        config.setMaxBytesPerSecond(Double.parseDouble(cl.getOptionValue("bwlimit")));

    }

    if (cl.hasOption('c')) {
        if (config.getGlacier()) {
            GlacierCleanupMultipart.cleanup(config);
        } else {
            S3CleanupMultipart.cleanup(config);
        }
        return;
    }
    if (cl.hasOption('d')) {
        config.setOutputStream(System.out);
        S3StreamingDownload.download(config);
        return;
    }
    if (cl.hasOption('u')) {
        config.setInputStream(System.in);
        S3StreamingUpload.upload(config);
        return;
    }

}

From source file:com.esri.geoevent.test.performance.OrchestratorMain.java

/**
 * Main method - this is used to when running from command line
 *
 * @param args Command Line Arguments//from   ww w.  ja  v a2 s  .  co m
 */
@SuppressWarnings("static-access")
public static void main(String[] args) {
    // TODO: Localize the messages
    // test harness options
    Options testHarnessOptions = new Options();
    testHarnessOptions.addOption(OptionBuilder.withLongOpt("fixtures")
            .withDescription("The fixtures xml file to load and configure the performance test harness.")
            .hasArg().create("f"));
    testHarnessOptions.addOption("h", "help", false, "print the help message");

    // parse the command line
    CommandLineParser parser = new BasicParser();
    CommandLine cmd = null;
    try {
        cmd = parser.parse(testHarnessOptions, args, false);
    } catch (ParseException ignore) {
        printHelp(testHarnessOptions);
        return;
    }

    if (cmd.getOptions().length == 0) {
        OrchestratorUI ui = new OrchestratorUI();
        ui.run(args);
    } else {
        if (cmd.hasOption("h")) {
            printHelp(testHarnessOptions);
            return;
        }

        if (cmd.hasOption("h") || !cmd.hasOption("f")) {
            printHelp(testHarnessOptions);
            return;
        }

        String fixturesFilePath = cmd.getOptionValue("f");
        // validate
        if (!validateFixturesFile(fixturesFilePath)) {
            printHelp(testHarnessOptions);
            return;
        }

        // parse the xml file
        final Fixtures fixtures;
        try {
            fixtures = fromXML(fixturesFilePath);
        } catch (JAXBException error) {
            System.err.println(ImplMessages.getMessage("TEST_HARNESS_EXECUTOR_CONFIG_ERROR", fixturesFilePath));
            error.printStackTrace();
            return;
        }

        // run the test harness
        try {
            OrchestratorRunner executor = new OrchestratorRunner(fixtures);

            executor.start();
        } catch (RunningException error) {
            error.printStackTrace();
        }

    }

}

From source file:com.github.zk1931.zabkv.Main.java

public static void main(String[] args) throws Exception {
    // Options for command arguments.
    Options options = new Options();

    Option port = OptionBuilder.withArgName("port").hasArg(true).isRequired(true).withDescription("port number")
            .create("port");

    Option ip = OptionBuilder.withArgName("ip").hasArg(true).isRequired(true)
            .withDescription("current ip address").create("ip");

    Option join = OptionBuilder.withArgName("join").hasArg(true).withDescription("the addr of server to join.")
            .create("join");

    Option help = OptionBuilder.withArgName("h").hasArg(false).withLongOpt("help")
            .withDescription("print out usages.").create("h");

    options.addOption(port).addOption(ip).addOption(join).addOption(help);

    CommandLineParser parser = new BasicParser();
    CommandLine cmd;/*from w  w w  . j av a2  s  . c o m*/

    try {
        cmd = parser.parse(options, args);
        if (cmd.hasOption("h")) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("zabkv", options);
            return;
        }
    } catch (ParseException exp) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("zabkv", options);
        return;
    }

    int zabPort = Integer.parseInt(cmd.getOptionValue("port"));
    String myIp = cmd.getOptionValue("ip");

    if (zabPort < 5000 && zabPort >= 5010) {
        System.err.println("port parameter can have value only between 5000 & 5010");
        System.exit(1);
    }

    int serverPort = zabPort % 5000 + 8000;

    Database db = new Database(myIp, zabPort, cmd.getOptionValue("join"));

    Server server = new Server(serverPort);
    ServletHandler handler = new ServletHandler();
    server.setHandler(handler);
    ServletHolder holder = new ServletHolder(new RequestHandler(db));
    handler.addServletWithMapping(holder, "/*");
    server.start();
    server.join();
    System.out.println("hi");
}

From source file:RedPenRunner.java

public static void main(String[] args) throws Exception {
    Options options = new Options();
    options.addOption("h", "help", false, "help");
    options.addOption("v", "version", false, "print the version information and exit");

    OptionBuilder.withLongOpt("port");
    OptionBuilder.withDescription("port number");
    OptionBuilder.hasArg();//from w  ww .j a v a 2  s . c  om
    OptionBuilder.withArgName("PORT");
    options.addOption(OptionBuilder.create("p"));

    OptionBuilder.withLongOpt("key");
    OptionBuilder.withDescription("stop key");
    OptionBuilder.hasArg();
    OptionBuilder.withArgName("STOP_KEY");
    options.addOption(OptionBuilder.create("k"));

    OptionBuilder.withLongOpt("conf");
    OptionBuilder.withDescription("configuration file");
    OptionBuilder.hasArg();
    OptionBuilder.withArgName("CONFIG_FILE");
    options.addOption(OptionBuilder.create("c"));

    OptionBuilder.withLongOpt("lang");
    OptionBuilder.withDescription("Language of error messages");
    OptionBuilder.hasArg();
    OptionBuilder.withArgName("LANGUAGE");
    options.addOption(OptionBuilder.create("L"));

    CommandLineParser parser = new BasicParser();
    CommandLine commandLine = null;

    try {
        commandLine = parser.parse(options, args);
    } catch (Exception e) {
        printHelp(options);
        System.exit(-1);
    }

    int portNum = 8080;
    String language = "en";
    if (commandLine.hasOption("h")) {
        printHelp(options);
        System.exit(0);
    }
    if (commandLine.hasOption("v")) {
        System.out.println(RedPen.VERSION);
        System.exit(0);
    }
    if (commandLine.hasOption("p")) {
        portNum = Integer.parseInt(commandLine.getOptionValue("p"));
    }
    if (commandLine.hasOption("L")) {
        language = commandLine.getOptionValue("L");
    }
    if (isPortTaken(portNum)) {
        System.err.println("port is taken...");
        System.exit(1);
    }

    // set language
    if (language.equals("ja")) {
        Locale.setDefault(new Locale("ja", "JA"));
    } else {
        Locale.setDefault(new Locale("en", "EN"));
    }

    final String contextPath = System.getProperty("redpen.home", "/");

    Server server = new Server(portNum);
    ProtectionDomain domain = RedPenRunner.class.getProtectionDomain();
    URL location = domain.getCodeSource().getLocation();

    HandlerList handlerList = new HandlerList();
    if (commandLine.hasOption("key")) {
        // Add Shutdown handler only when STOP_KEY is specified
        ShutdownHandler shutdownHandler = new ShutdownHandler(commandLine.getOptionValue("key"));
        handlerList.addHandler(shutdownHandler);
    }

    WebAppContext webapp = new WebAppContext();
    webapp.setContextPath(contextPath);
    if (location.toExternalForm().endsWith("redpen-server/target/classes/")) {
        // use redpen-server/target/redpen-server instead, because target/classes doesn't contain web resources.
        webapp.setWar(location.toExternalForm() + "../redpen-server/");
    } else {
        webapp.setWar(location.toExternalForm());
    }
    if (commandLine.hasOption("c")) {
        webapp.setInitParameter("redpen.conf.path", commandLine.getOptionValue("c"));
    }

    handlerList.addHandler(webapp);
    server.setHandler(handlerList);

    server.start();
    server.join();
}

From source file:com.teradata.tempto.sql.SqlResultGenerator.java

/**
 * The easiest way to generate expected results is to use
 * the python front-end (generate_results.py).
 *
 * @param args//from   www  .ja  v  a  2s. c o  m
 */
public static void main(String[] args) {
    Options options = configureCommandLineParser();
    try {
        CommandLineParser parser = new BasicParser();
        CommandLine commandLine = parser.parse(options, args);
        if (commandLine.hasOption(HELP)) {
            usage(options);
            return;
        }
        String propertiesFileName = commandLine.getOptionValue("p");
        String testFileName = commandLine.getOptionValue("s");
        SqlResultGenerator resultGenerator = new SqlResultGenerator(testFileName, propertiesFileName);
        resultGenerator.generateExpectedResults();
    } catch (ParseException e) {
        usage(options);
    } catch (Exception e) {
        LOGGER.error("Caught exception in main", e);
    }
    System.exit(99);
}

From source file:com.esri.geoevent.clusterSimulator.GeoeventClusterSimulator.java

public static void main(String[] args) {
    Options options = MyOptions.createOptions();
    CommandLineParser parser = new BasicParser();
    CommandLine cmd = null;//from w  w w .  ja  v a2s .  c  om
    try {
        cmd = parser.parse(options, args);
    } catch (ParseException e1) {
        MyOptions.printUsageAndExit();
    }

    try {
        ClientServerMode mode = getMode(cmd.getOptionValue('m', "CLIENT"));
        Simulator simulator = null;
        int batchSize = 1;
        if (cmd.hasOption('b')) {
            try {
                batchSize = Integer.parseInt(cmd.getOptionValue('b'));
                if (batchSize < 1) {
                    batchSize = 1;
                    System.err.println("Error : " + cmd.getOptionValue('b')
                            + " is not a valid value for the batch size.  Using \'1\' instead.");
                }
            } catch (NumberFormatException ex) {
                System.err.println(
                        "Error : " + cmd.getOptionValue('b') + " is not a valid value for the batch size.");
            }
        }
        boolean trustAllSSLCerts = cmd.hasOption('t');
        int period = Integer.parseInt(cmd.getOptionValue('d', "1000"));
        switch (mode) {
        case CLIENT:
            simulator = getSimulator(cmd.getOptionValue('f'), true, cmd.hasOption('l'), batchSize, period);
            serverAdminClient = new ServerAdminClient(cmd.getOptionValue('h'),
                    cmd.getOptionValue('u', "siteadmin"), cmd.getOptionValue('p', "password"), simulator,
                    (trustAllSSLCerts) ? new AcceptAlwaysCertChecker() : new CommandLineCertChecker());
            simulator.start();
            break;
        case SERVER:
            simulator = getSimulator(cmd.getOptionValue('f'), false, cmd.hasOption('l'), batchSize, period);
            tcpServer = new TCPServer(simulator);
            simulator.start();
            break;
        default:
            break;
        }
    } catch (Exception e) {
        System.err.println("Error : " + e.getMessage());
        System.exit(1);
    }
}

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

public static void main(String[] args) throws Exception {
    // logging/*from  w ww.j a va2 s . c om*/
    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: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/*from w w  w. j av a  2  s  .c om*/
 *
 * @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);
}