Example usage for org.apache.commons.cli HelpFormatter setOptionComparator

List of usage examples for org.apache.commons.cli HelpFormatter setOptionComparator

Introduction

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

Prototype

public void setOptionComparator(Comparator comparator) 

Source Link

Document

Set the comparator used to sort the options when they output in help text Passing in a null parameter will set the ordering to the default mode

Usage

From source file:com.archivas.clienttools.arcmover.cli.AbstractArcCli.java

public String helpScreen() {
    StringBuffer usage = new StringBuffer();
    HelpFormatter formatter = new HelpFormatter();

    if (cliOrder != null && cliOrder.size() > 0) {
        formatter.setOptionComparator(new OptionComparator());
    }//from   w w  w  . j a v  a2s .c om

    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    formatter.printHelp(pw, HCPMoverProperties.CLI_WIDTH.getAsInt(), getHelpUsageLine(), null /* header */,
            getOptions(), HelpFormatter.DEFAULT_LEFT_PAD /* leftPad */,
            HelpFormatter.DEFAULT_DESC_PAD /* descPad */, null /* footer */, false /* autoUsage */
    );

    usage.append(getHelpHeader());
    usage.append(sw.toString());
    usage.append(getHelpFooter());
    return usage.toString();
}

From source file:io.github.felsenhower.stine_calendar_bot.main.CallLevelWrapper.java

/**
 * Prints the help screen for the current Options instance and exits the
 * application//from w w  w .  j  a  v a  2  s.c  om
 */
private void printHelp() {
    HelpFormatter formatter = new HelpFormatter();
    formatter.setOptionComparator(null);
    formatter.setDescPadding(4);
    formatter.setLeftPadding(2);
    formatter.setLongOptSeparator("=");
    formatter.setLongOptPrefix(" --");
    formatter.setSyntaxPrefix(cliStrings.get("Usage"));
    formatter.printHelp(cliStrings.get("UsageTemplate", appInfo.get("Name")),
            cliStrings.get("HelpHeader", appInfo.get("Name"), appInfo.get("Version")), this.options,
            cliStrings.get("HelpFooter", cliStrings.get("Author"), cliStrings.get("License"),
                    appInfo.get("ProjectPage")),
            true);
    System.exit(0);
}

From source file:jurbano.melodyshape.ui.ConsoleUIObserver.java

/**
 * Prints the usage message to stderr./*from  w  ww  .  jav a2 s  .  c  om*/
 * 
 * @param options
 *            the command line options.
 */
protected void printUsage(Options options) {
    HelpFormatter formatter = new HelpFormatter();
    formatter.setOptionComparator(new Comparator<Option>() {
        public int compare(Option o1, Option o2) {
            List<String> options = Arrays.asList("q", "c", "a", "k", "l", "t", "v", "vv", "gui", "h");

            return Integer.compare(options.indexOf(o1.getOpt()), options.indexOf(o2.getOpt()));
        }
    });
    formatter.printHelp(new PrintWriter(System.err, true), Integer.MAX_VALUE,
            "melodyshape-" + MelodyShape.VERSION, null, options, 0, 2, "\n" + MelodyShape.COPYRIGHT_NOTICE,
            true);
}

From source file:bdsup2sub.cli.CommandLineParser.java

public void printHelp() {
    HelpFormatter formatter = new HelpFormatter();
    formatter.setOptionComparator(new Comparator() {
        @Override/*from  w w  w  .j a  v  a 2 s. c o m*/
        public int compare(Object o1, Object o2) {
            Option opt1 = (Option) o1;
            Option opt2 = (Option) o2;

            int opt1Index = OPTION_ORDER.indexOf(opt1.getOpt());
            int opt2Index = OPTION_ORDER.indexOf(opt2.getOpt());

            return (int) Math.signum(opt1Index - opt2Index);
        }
    });
    formatter.setWidth(79);
    String command = System.getProperty("wrapper") == null ? "java -jar BDSup2Sub" : "bdsup2sub";
    formatter.printHelp(command + " [options] -o <output> <input>", options);
}

From source file:de.clusteval.serverclient.BackendClient.java

@Override
public void run() {
    boolean checkForRunStatus = false;
    boolean checkForOptRunStatus = false;
    try {/*w  ww  .j av  a  2  s .co m*/
        if (params.hasOption("performRun")) {
            this.performRun(params.getOptionValue("performRun"));
        }
        if (params.hasOption("resumeRun")) {
            this.resumeRun(params.getOptionValue("resumeRun"));
        }
        if (params.hasOption("terminateRun")) {
            this.terminateRun(params.getOptionValue("terminateRun"));
        }
        if (params.hasOption("getRuns")) {
            System.out.println("Runs: " + this.getRuns());
        }
        if (params.hasOption("getRunResumes")) {
            System.out.println("RunResumes: " + this.getRunResumes());
        }
        if (params.hasOption("getQueue")) {
            System.out.println("Queue: " + this.getQueue());
        }
        if (params.hasOption("getActiveThreads")) {
            Map<String, Triple<String, Integer, Long>> activeThreads = this.server.getActiveThreads();
            if (activeThreads.isEmpty())
                System.out.println("No active threads");
            else {
                System.out.println("Active threads:");
                System.out.format("%10s%20s%50s%30s%40s%10s%20s\n", "Thread #", "Thread", "Run",
                        "ProgramConfig", "DataConfig", "Iteration", "Running time");
                List<String> threadNames = new ArrayList<String>(activeThreads.keySet());
                Collections.sort(threadNames);
                int i = 1;
                for (String t : threadNames) {
                    Triple<String, Integer, Long> value = activeThreads.get(t);
                    String[] split1 = value.getFirst().split(": ");
                    String[] split2 = split1[1].split(",");

                    switch (value.getSecond()) {
                    case -1:
                        System.out.format("%10d%20s%50s%30s%40s%10s%20s\n", i++, t, split1[0], split2[0],
                                split2[1], "isoMDS", Formatter.formatMsToDuration(
                                        System.currentTimeMillis() - value.getThird(), false));
                        break;
                    case -2:
                        System.out.format("%10d%20s%50s%30s%40s%10s%20s\n", i++, t, split1[0], split2[0],
                                split2[1], "PCA", Formatter.formatMsToDuration(
                                        System.currentTimeMillis() - value.getThird(), false));
                        break;
                    default:
                        System.out.format("%10d%20s%50s%30s%40s%10d%20s\n", i++, t, split1[0], split2[0],
                                split2[1], value.getSecond(), Formatter.formatMsToDuration(
                                        System.currentTimeMillis() - value.getThird(), false));
                    }
                }
            }
        }
        if (params.hasOption("getRunResults")) {
            Map<Pair<String, String>, Map<String, Double>> result = this
                    .getRunResults(params.getOptionValue("getRunResults"));
            boolean first = true;
            for (Pair<String, String> p : result.keySet()) {
                if (first) {
                    for (String m : result.get(p).keySet()) {
                        System.out.format("%-30s", "");
                        System.out.print("\t" + m);
                    }
                    System.out.println();
                }
                System.out.format("%-30s", "(" + p.getFirst() + "," + p.getSecond() + ")");
                for (String m : result.get(p).keySet()) {
                    System.out.println("\t" + result.get(p).get(m));
                }
                first = false;
            }
        }
        if (params.hasOption("getDataSets")) {
            System.out.println("DataSets: " + this.getDataSets());
        }
        if (params.hasOption("getPrograms")) {
            System.out.println("Programs: " + this.getPrograms());
        }
        if (params.hasOption("getRunStatus")) {
            checkForRunStatus = true;
        }
        if (params.hasOption("getOptRunStatus")) {
            checkForOptRunStatus = true;
        }
        if (params.hasOption("shutdown")) {
            this.shutdownFramework();
        }
        if (params.hasOption("generateDataSet")) {
            String generatorName = params.getOptionValue("generateDataSet");

            CommandLineParser parser = new PosixParser();
            Options options = getOptionsForDataSetGenerator(generatorName);

            try {
                parser.parse(options, this.args);
                this.server.generateDataSet(generatorName, this.args);
            } catch (ParseException e1) {
                try {
                    reader.println();
                    HelpFormatter formatter = new HelpFormatter();
                    formatter.setOptionComparator(new MyOptionComparator());
                    formatter.printHelp("generateDataSet " + generatorName, options, true);
                    reader.println();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        if (params.hasOption("randomizeDataConfig")) {
            String randomizerName = params.getOptionValue("randomizeDataConfig");

            CommandLineParser parser = new PosixParser();
            Options options = getOptionsForDataRandomizer(randomizerName);

            try {
                parser.parse(options, this.args);
                this.server.randomizeDataConfig(randomizerName, this.args);
            } catch (ParseException e1) {
                try {
                    reader.println();
                    HelpFormatter formatter = new HelpFormatter();
                    formatter.setOptionComparator(new MyOptionComparator());
                    formatter.printHelp("randomizeDataConfig " + randomizerName, options, true);
                    reader.println();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        if (checkForRunStatus) {
            try {
                String runName = params.getOptionValue("getRunStatus");

                Map<String, Pair<RUN_STATUS, Float>> status = null;
                if ((status = this.getMyRunStatus()) != null && status.size() > 0) {
                    RUN_STATUS newStatus;
                    Float percent;
                    if (!status.containsKey(runName)) {
                        log.info("No run with name " + runName + " running.");
                        return;
                    }
                    newStatus = status.get(runName).getFirst();
                    percent = status.get(runName).getSecond();
                    System.out.println();
                    System.out.print("\r" + newStatus + " " + percent + "%");
                }
                System.out.println();
            } catch (ConnectException e2) {
                this.log.warn("The server terminated the connection...");
            } catch (RemoteException e2) {
                e2.printStackTrace();
            }
        }

        if (checkForOptRunStatus) {
            try {

                String runName = params.getOptionValue("getOptRunStatus");

                // runId ->
                // ((Status,%),(ProgramConfig,DataConfig)->(QualityMeasure->(ParameterSet->Quality)))
                Map<String, Pair<Pair<RUN_STATUS, Float>, Map<Pair<String, String>, Map<String, Pair<Map<String, String>, String>>>>> optStatus = null;
                if ((optStatus = this.getMyOptimizationRunStatus()) != null && optStatus.size() > 0) {
                    RUN_STATUS newStatus;
                    Float percent;

                    if (!optStatus.containsKey(runName)) {
                        log.info("No run with name " + runName + " running.");
                        return;
                    }
                    newStatus = optStatus.get(runName).getFirst().getFirst();
                    percent = optStatus.get(runName).getFirst().getSecond();
                    System.out.println();
                    System.out.println("\r Status:\t" + newStatus + " " + percent + "%");
                    Map<Pair<String, String>, Map<String, Pair<Map<String, String>, String>>> qualities = optStatus
                            .get(runName).getSecond();

                    // print the quality measures; just take them from the
                    // first pair of programConfig and dataConfig (runnable)
                    String[] qualityMeasures = qualities.values().iterator().next().keySet()
                            .toArray(new String[0]);
                    Arrays.sort(qualityMeasures);
                    int pos = 0;
                    while (true) {
                        boolean foundMeasure = false;
                        for (String measure : qualityMeasures) {
                            if (pos < measure.length()) {
                                System.out.printf("\t%s", measure.charAt(pos));
                                foundMeasure = true;
                            } else
                                System.out.print("\t");
                        }
                        System.out.println();
                        if (!foundMeasure)
                            break;
                        pos++;
                    }

                    // 06.06.2014: added sets to keep order when printing
                    // the results
                    Set<String> programConfigs = new HashSet<String>();
                    Set<String> dataConfigs = new HashSet<String>();

                    for (Pair<String, String> pcDcPair : qualities.keySet()) {
                        programConfigs.add(pcDcPair.getFirst());
                        dataConfigs.add(pcDcPair.getSecond());
                    }

                    for (String programConfig : programConfigs) {
                        System.out.printf("%s:\n", programConfig);
                        for (String dataConfig : dataConfigs) {
                            System.out.printf("-- %s:\n", dataConfig);
                            Pair<String, String> pcDcPair = Pair.getPair(programConfig, dataConfig);
                            Map<String, Pair<Map<String, String>, String>> qualitiesPcDc = qualities
                                    .get(pcDcPair);
                            for (String measure : qualityMeasures) {
                                if (!qualitiesPcDc.containsKey(measure)) {
                                    System.out.print("\t");
                                    continue;
                                }
                                String quality = qualitiesPcDc.get(measure).getSecond();
                                if (quality.equals("NT"))
                                    System.out.print("\tNT");
                                else {
                                    double qualityDouble = Double.valueOf(quality);
                                    if (Double.isInfinite(qualityDouble))
                                        System.out.printf("\t%s%s", qualityDouble < 0 ? "-" : "", "Inf");
                                    else
                                        System.out.printf("\t%.4f", qualityDouble);
                                }
                            }
                            System.out.println();
                        }
                    }
                }
                System.out.println();
            } catch (ConnectException e2) {
                this.log.warn("The server terminated the connection...");
            } catch (RemoteException e2) {
                e2.printStackTrace();
            }
        }
    } catch (RemoteException e) {
        e.printStackTrace();
    }
}

From source file:kieker.tools.traceAnalysis.TraceAnalysisTool.java

@Override
protected HelpFormatter getHelpFormatter() {
    final HelpFormatter helpFormatter = new CLIHelpFormatter();

    helpFormatter.setOptionComparator(new OptionComparator());

    return helpFormatter;
}

From source file:org.apache.druid.examples.rabbitmq.RabbitMQProducerMain.java

public static void main(String[] args) throws Exception {
    // We use a List to keep track of option insertion order. See below.
    final List<Option> optionList = new ArrayList<Option>();

    optionList.add(OptionBuilder.withLongOpt("help").withDescription("display this help message").create("h"));
    optionList.add(OptionBuilder.withLongOpt("hostname").hasArg()
            .withDescription("the hostname of the AMQP broker [defaults to AMQP library default]").create("b"));
    optionList.add(OptionBuilder.withLongOpt("port").hasArg()
            .withDescription("the port of the AMQP broker [defaults to AMQP library default]").create("n"));
    optionList.add(OptionBuilder.withLongOpt("username").hasArg()
            .withDescription("username to connect to the AMQP broker [defaults to AMQP library default]")
            .create("u"));
    optionList.add(OptionBuilder.withLongOpt("password").hasArg()
            .withDescription("password to connect to the AMQP broker [defaults to AMQP library default]")
            .create("p"));
    optionList.add(OptionBuilder.withLongOpt("vhost").hasArg()
            .withDescription("name of virtual host on the AMQP broker [defaults to AMQP library default]")
            .create("v"));
    optionList.add(OptionBuilder.withLongOpt("exchange").isRequired().hasArg()
            .withDescription("name of the AMQP exchange [required - no default]").create("e"));
    optionList.add(OptionBuilder.withLongOpt("key").hasArg()
            .withDescription("the routing key to use when sending messages [default: 'default.routing.key']")
            .create("k"));
    optionList.add(OptionBuilder.withLongOpt("type").hasArg()
            .withDescription("the type of exchange to create [default: 'topic']").create("t"));
    optionList.add(OptionBuilder.withLongOpt("durable")
            .withDescription("if set, a durable exchange will be declared [default: not set]").create("d"));
    optionList.add(OptionBuilder.withLongOpt("autodelete")
            .withDescription("if set, an auto-delete exchange will be declared [default: not set]")
            .create("a"));
    optionList.add(OptionBuilder.withLongOpt("single")
            .withDescription("if set, only a single message will be sent [default: not set]").create("s"));
    optionList.add(OptionBuilder.withLongOpt("start").hasArg()
            .withDescription("time to use to start sending messages from [default: 2010-01-01T00:00:00]")
            .create());//  w w  w . j a  v a  2 s  . co  m
    optionList.add(OptionBuilder.withLongOpt("stop").hasArg().withDescription(
            "time to use to send messages until (format: '2013-07-18T23:45:59') [default: current time]")
            .create());
    optionList.add(OptionBuilder.withLongOpt("interval").hasArg()
            .withDescription("the interval to add to the timestamp between messages in seconds [default: 10]")
            .create());
    optionList.add(OptionBuilder.withLongOpt("delay").hasArg()
            .withDescription("the delay between sending messages in milliseconds [default: 100]").create());

    // An extremely silly hack to maintain the above order in the help formatting.
    HelpFormatter formatter = new HelpFormatter();
    // Add a comparator to the HelpFormatter using the ArrayList above to sort by insertion order.
    //noinspection ComparatorCombinators -- don't replace with comparingInt() to preserve comments
    formatter.setOptionComparator((o1, o2) -> {
        // I know this isn't fast, but who cares! The list is short.
        //noinspection SuspiciousMethodCalls
        return Integer.compare(optionList.indexOf(o1), optionList.indexOf(o2));
    });

    // Now we can add all the options to an Options instance. This is dumb!
    Options options = new Options();
    for (Option option : optionList) {
        options.addOption(option);
    }

    CommandLine cmd = null;

    try {
        cmd = new BasicParser().parse(options, args);
    } catch (ParseException e) {
        formatter.printHelp("RabbitMQProducerMain", e.getMessage(), options, null);
        System.exit(1);
    }

    if (cmd.hasOption("h")) {
        formatter.printHelp("RabbitMQProducerMain", options);
        System.exit(2);
    }

    ConnectionFactory factory = new ConnectionFactory();

    if (cmd.hasOption("b")) {
        factory.setHost(cmd.getOptionValue("b"));
    }
    if (cmd.hasOption("u")) {
        factory.setUsername(cmd.getOptionValue("u"));
    }
    if (cmd.hasOption("p")) {
        factory.setPassword(cmd.getOptionValue("p"));
    }
    if (cmd.hasOption("v")) {
        factory.setVirtualHost(cmd.getOptionValue("v"));
    }
    if (cmd.hasOption("n")) {
        factory.setPort(Integer.parseInt(cmd.getOptionValue("n")));
    }

    String exchange = cmd.getOptionValue("e");
    String routingKey = "default.routing.key";
    if (cmd.hasOption("k")) {
        routingKey = cmd.getOptionValue("k");
    }

    boolean durable = cmd.hasOption("d");
    boolean autoDelete = cmd.hasOption("a");
    String type = cmd.getOptionValue("t", "topic");
    boolean single = cmd.hasOption("single");
    int interval = Integer.parseInt(cmd.getOptionValue("interval", "10"));
    int delay = Integer.parseInt(cmd.getOptionValue("delay", "100"));

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.ENGLISH);
    Date stop = sdf.parse(cmd.getOptionValue("stop", sdf.format(new Date())));

    Random r = ThreadLocalRandom.current();
    Calendar timer = Calendar.getInstance(TimeZone.getTimeZone("UTC"), Locale.ENGLISH);
    timer.setTime(sdf.parse(cmd.getOptionValue("start", "2010-01-01T00:00:00")));

    String msg_template = "{\"utcdt\": \"%s\", \"wp\": %d, \"gender\": \"%s\", \"age\": %d}";

    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    channel.exchangeDeclare(exchange, type, durable, autoDelete, null);

    do {
        int wp = (10 + r.nextInt(90)) * 100;
        String gender = r.nextBoolean() ? "male" : "female";
        int age = 20 + r.nextInt(70);

        String line = StringUtils.format(msg_template, sdf.format(timer.getTime()), wp, gender, age);

        channel.basicPublish(exchange, routingKey, null, StringUtils.toUtf8(line));

        System.out.println("Sent message: " + line);

        timer.add(Calendar.SECOND, interval);

        Thread.sleep(delay);
    } while ((!single && stop.after(timer.getTime())));

    connection.close();
}

From source file:org.apache.solr.core.snapshots.SolrSnapshotsTool.java

private static void printHelp(Options options) {
    StringBuilder helpFooter = new StringBuilder();
    helpFooter.append("Examples: \n");
    helpFooter.append("snapshotscli.sh --create snapshot-1 -c books -z localhost:2181 \n");
    helpFooter.append("snapshotscli.sh --list -c books -z localhost:2181 \n");
    helpFooter.append("snapshotscli.sh --describe snapshot-1 -c books -z localhost:2181 \n");
    helpFooter.append(/*  www  . j  a  va 2 s .c o m*/
            "snapshotscli.sh --export snapshot-1 -c books -z localhost:2181 -b repo -l backupPath -i req_0 \n");
    helpFooter.append("snapshotscli.sh --delete snapshot-1 -c books -z localhost:2181 \n");

    HelpFormatter formatter = new HelpFormatter();
    formatter.setOptionComparator(new OptionComarator<>());
    formatter.printHelp("SolrSnapshotsTool", null, options, helpFooter.toString(), false);
}

From source file:org.dataaccessioner.DataAccessioner.java

private static void printHelp(Options opts) {
    HelpFormatter formatter = new HelpFormatter();
    formatter.setOptionComparator(null);
    formatter.printHelp("dataAccessioner [options] [destination] [source] [additional sources...]", opts);
}

From source file:org.eclipse.jubula.app.autrun.AutRunApplication.java

/**
 * prints help options/*from   ww  w  .j  a  v a  2 s.c  o  m*/
 * @param pe a parse Execption - may also be null
 */
private static void printHelp(ParseException pe) {
    HelpFormatter formatter = new HelpFormatter();
    formatter.setOptionComparator(new OptionComparator());
    if (pe != null) {
        formatter.printHelp(LAUNCHER_NAME, StringConstants.EMPTY, createCmdLineOptions(),
                "\n" + pe.getLocalizedMessage(), //$NON-NLS-1$
                true);
    } else {
        formatter.printHelp(LAUNCHER_NAME, createCmdLineOptions(), true);
    }
}