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

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

Introduction

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

Prototype

public void printOptions(PrintWriter pw, int width, Options options, int leftPad, int descPad) 

Source Link

Document

Print the help for the specified Options to the specified writer, using the specified width, left padding and description padding.

Usage

From source file:org.apache.sqoop.shell.SqoopFunction.java

public void printHelp() {
    HelpFormatter formatter = new HelpFormatter();
    formatter.printOptions(getIo().out, formatter.getWidth(), this, 0, 4);
}

From source file:org.deegree.commons.tools.CommandUtils.java

/**
 * Prints a help message for a apache commons-cli based command line tool and <b>terminates the programm</b>.
 * /*from   ww  w  .  jav a 2  s. c  om*/
 * @param options
 *            the options to generate help/usage information for
 * @param toolName
 *            the name of the command line tool
 * @param helpMsg
 *            some further information
 * @param otherUsageInfo
 *            an optional string to append to the usage information (e.g. for additional arguments like input files)
 */
public static void printHelp(Options options, String toolName, String helpMsg, String otherUsageInfo) {
    HelpFormatter formatter = new HelpFormatter();

    StringWriter helpWriter = new StringWriter();
    StringBuffer helpBuffer = helpWriter.getBuffer();
    PrintWriter helpPrintWriter = new PrintWriter(helpWriter);

    helpPrintWriter.println();

    if (helpMsg != null && helpMsg.length() != 0) {
        formatter.printWrapped(helpPrintWriter, HELP_TEXT_WIDTH, helpMsg);
        helpPrintWriter.println();
    }
    formatter.printUsage(helpPrintWriter, HELP_TEXT_WIDTH, toolName, options);
    if (otherUsageInfo != null) {
        helpBuffer.deleteCharAt(helpBuffer.length() - 1); // append additional arguments
        helpBuffer.append(' ').append(otherUsageInfo).append("\n");
    }

    helpBuffer.append("\n");
    formatter.printOptions(helpPrintWriter, HELP_TEXT_WIDTH, options, 3, 5);
    System.err.print(helpBuffer.toString());
    System.exit(1);
}

From source file:org.dfotos.rssfilter.App.java

/**
 * Prints "help" to the System.out.// www . j a v  a2s . c o  m
 * @param options Our command line options.
 */
private static void printHelp(final Options options) {
    System.out.println("");
    HelpFormatter formatter = new HelpFormatter();
    PrintWriter pw1 = new MyPrintWriter(System.out);
    pw1.print(" ");
    formatter.printUsage(pw1, formatter.getWidth(), "rss-filter", options);
    pw1.println(" <command> [command2] [command3] ... [commandN]");
    pw1.flush();
    System.out.println("\n\n Commands:");
    COMMANDS.keySet();
    for (String cmd : COMMANDS.keySet()) {
        String tabs = "\t\t";
        if (cmd.length() > 6) {
            tabs = "\t";
        }
        System.out.println(" " + cmd + tabs + COMMANDS.get(cmd).getHelpStr());
    }
    System.out.println("\n Options:");
    PrintWriter pw2 = new PrintWriter(System.out);
    formatter.printOptions(pw2, formatter.getWidth(), options, formatter.getLeftPadding(),
            formatter.getDescPadding());
    pw2.flush();
    System.out.println("\n Example:");
    System.out.println(" rss-filter -v get tag export \n");
}

From source file:org.esxx.Main.java

private static void usage(Options opt, String error, int rc) {
    PrintWriter err = new PrintWriter(System.err);
    HelpFormatter hf = new HelpFormatter();

    hf.printUsage(err, 80, "esxx.jar [OPTION...] [--script -- <script.js> SCRIPT ARGS...]");
    hf.printOptions(err, 80, opt, 2, 8);

    if (error != null) {
        err.println();/*  w  ww.  jav  a2s.  com*/
        hf.printWrapped(err, 80, "Invalid arguments: " + error + ".");
    }

    err.flush();
    System.exit(rc);
}

From source file:org.fusesource.hawtjni.generator.HawtJNI.java

private void displayHelp() {
    System.err.flush();/*w  w  w  . j a  v  a 2 s. c  o  m*/
    String app = System.getProperty("hawtjni.application");
    if (app == null) {
        try {
            URL location = getClass().getProtectionDomain().getCodeSource().getLocation();
            String[] split = location.toString().split("/");
            if (split[split.length - 1].endsWith(".jar")) {
                app = split[split.length - 1];
            }
        } catch (Throwable e) {
        }
        if (app == null) {
            app = getClass().getSimpleName();
        }
    }

    // The commented out line is 80 chars long.  We have it here as a visual reference
    //      p("                                                                                ");
    p();
    p("Usage: " + app + " [options] <classpath>");
    p();
    p("Description:");
    p();
    pw("  " + app + " is a code generator that produces the JNI code needed to implement java native methods.",
            2);
    p();

    p("Options:");
    p();
    PrintWriter out = new PrintWriter(System.out);
    HelpFormatter formatter = new HelpFormatter();
    formatter.printOptions(out, 78, createOptions(), 2, 2);
    out.flush();
    p();
    p("Examples:");
    p();
    pw("  " + app + " -o build foo.jar bar.jar ", 2);
    pw("  " + app + " -o build foo.jar:bar.jar ", 2);
    pw("  " + app + " -o build -p org.mypackage foo.jar;bar.jar ", 2);
    p();
}

From source file:org.fusesource.mop.MOP.java

public void displayHelp() {
    System.err.flush();/* www  .  ja  v a  2 s .c  om*/
    String app = System.getProperty("mop.application", "mop");

    // The commented out line is 80 chars long.  We have it here as a visual reference
    //      p("                                                                                ");
    p();
    p("Usage: " + app + " [options] <command>");
    p();
    p("Description:");
    p();
    pw("  mop is a tool for running Java code on the command line using maven repositories to download code and create classpaths.",
            2);
    p();

    p("Options:");
    p();
    PrintWriter out = new PrintWriter(System.out);
    HelpFormatter formatter = new HelpFormatter();
    formatter.printOptions(out, 78, createOptions(), 2, 2);
    out.flush();
    p();

    checkCommandsLoaded();
    p("Commands:");
    p();
    for (Map.Entry<String, CommandDefinition> entry : commands.entrySet()) {
        CommandDefinition command = entry.getValue();
        pw("  * " + entry.getKey() + ": " + removeNewLines(command.getDescription()), 4);
        pw("      usage: " + app + " [options] " + entry.getKey() + " " + removeNewLines(command.getUsage()),
                6);
        p();
    }

    p("Where:");
    p();
    p("  <repo>     is of the format: repo_id=repo_url");
    p("  <artifact> is of the format: ");
    p("             [groupId:]artifactId[[:type[:classifier]]:version] [+<artifact>]");
    p();
    p("Learn more at: http://mop.fusesource.org/");
}

From source file:org.gtdfree.GTDFree.java

/**
 * @param args//from   ww  w .  j a  v a  2 s  . com
 */
@SuppressWarnings("static-access")
public static void main(final String[] args) {

    //ApplicationHelper.changeDefaultFontSize(6, "TextField");
    //ApplicationHelper.changeDefaultFontSize(6, "TextArea");
    //ApplicationHelper.changeDefaultFontSize(6, "Table");
    //ApplicationHelper.changeDefaultFontSize(6, "Tree");

    //ApplicationHelper.changeDefaultFontStyle(Font.BOLD, "Tree");

    final Logger logger = Logger.getLogger(GTDFree.class);
    logger.setLevel(Level.ALL);
    BasicConfigurator.configure();

    Options op = new Options();
    op.addOption("data", true, Messages.getString("GTDFree.Options.data")); //$NON-NLS-1$ //$NON-NLS-2$
    op.addOption("eodb", true, Messages.getString("GTDFree.Options.eodb")); //$NON-NLS-1$ //$NON-NLS-2$
    op.addOption("exml", true, Messages.getString("GTDFree.Options.exml")); //$NON-NLS-1$ //$NON-NLS-2$
    op.addOption("h", "help", false, Messages.getString("GTDFree.Options.help")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
    op.addOption("log", true, Messages.getString("GTDFree.Options.log")); //$NON-NLS-1$ //$NON-NLS-2$

    Options op2 = new Options();
    op2.addOption(OptionBuilder.hasArg().isRequired(false)
            .withDescription(new MessageFormat(Messages.getString("GTDFree.Options.lang")) //$NON-NLS-1$
                    .format(new Object[] { "'en'", "'de', 'en'" })) //$NON-NLS-1$ //$NON-NLS-2$
            .withArgName("de|en") //$NON-NLS-1$
            .withLongOpt("Duser.language") //$NON-NLS-1$
            .withValueSeparator('=').create());
    op2.addOption(OptionBuilder.hasArg().isRequired(false)
            .withDescription(new MessageFormat(Messages.getString("GTDFree.Options.laf")).format(new Object[] { //$NON-NLS-1$
                    "'com.jgoodies.looks.plastic.Plastic3DLookAndFeel', 'com.jgoodies.looks.plastic.PlasticLookAndFeel', 'com.jgoodies.looks.plastic.PlasticXPLookAndFeel', 'com.jgoodies.looks.windows.WindowsLookAndFeel' (only on MS Windows), 'com.sun.java.swing.plaf.gtk.GTKLookAndFeel' (only on Linux with GTK), 'com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel', 'javax.swing.plaf.metal.MetalLookAndFeel'" })) //$NON-NLS-1$
            .withLongOpt("Dswing.crossplatformlaf") //$NON-NLS-1$
            .withValueSeparator('=').create());

    CommandLineParser clp = new GnuParser();
    CommandLine cl = null;
    try {
        cl = clp.parse(op, args);
    } catch (ParseException e1) {
        logger.error("Parse error.", e1); //$NON-NLS-1$
    }

    System.out.print("GTD-Free"); //$NON-NLS-1$
    String ver = ""; //$NON-NLS-1$
    try {
        System.out.println(" version " + (ver = ApplicationHelper.getVersion())); //$NON-NLS-1$

    } catch (Exception e) {
        System.out.println();
        // ignore
    }

    if (true) { // || cl.hasOption("help") || cl.hasOption("h")) {
        HelpFormatter hf = new HelpFormatter();
        hf.printHelp("java [Java options] -jar gtd-free.jar [gtd-free options]" //$NON-NLS-1$
                , "[gtd-free options] - " + Messages.getString("GTDFree.Options.appop") //$NON-NLS-1$ //$NON-NLS-2$
                , op, "[Java options] - " + new MessageFormat(Messages.getString("GTDFree.Options.javaop")) //$NON-NLS-1$//$NON-NLS-2$
                        .format(new Object[] { "'-jar'" }) //$NON-NLS-1$
                , false);
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        hf.setLongOptPrefix("-"); //$NON-NLS-1$
        hf.setWidth(88);
        hf.printOptions(pw, hf.getWidth(), op2, hf.getLeftPadding(), hf.getDescPadding());
        String s = sw.getBuffer().toString();
        s = s.replaceAll("\\A {3}", ""); //$NON-NLS-1$ //$NON-NLS-2$
        s = s.replaceAll("\n {3}", "\n"); //$NON-NLS-1$ //$NON-NLS-2$
        s = s.replaceAll(" <", "=<"); //$NON-NLS-1$ //$NON-NLS-2$
        System.out.print(s);
    }

    String val = cl.getOptionValue("data"); //$NON-NLS-1$
    if (val != null) {
        System.setProperty(ApplicationHelper.DATA_PROPERTY, val);
        System.setProperty(ApplicationHelper.TITLE_PROPERTY, "1"); //$NON-NLS-1$
    } else {
        System.setProperty(ApplicationHelper.TITLE_PROPERTY, "0"); //$NON-NLS-1$
    }

    val = cl.getOptionValue("log"); //$NON-NLS-1$
    if (val != null) {
        Level l = Level.toLevel(val, Level.ALL);
        logger.setLevel(l);
    }

    if (!ApplicationHelper.tryLock(null)) {
        System.out.println("Instance of GTD-Free already running, pushing it to be visible..."); //$NON-NLS-1$
        remotePushVisible();
        System.out.println("Instance of GTD-Free already running, exiting."); //$NON-NLS-1$
        System.exit(0);
    }

    if (!"OFF".equalsIgnoreCase(val)) { //$NON-NLS-1$
        RollingFileAppender f = null;
        try {
            f = new RollingFileAppender(new PatternLayout(PatternLayout.TTCC_CONVERSION_PATTERN),
                    ApplicationHelper.getLogFileName(), true);
            f.setMaxBackupIndex(3);
            BasicConfigurator.configure(f);
            f.rollOver();
        } catch (IOException e2) {
            logger.error("Logging error.", e2); //$NON-NLS-1$
        }
    }
    logger.info("GTD-Free " + ver + " started."); //$NON-NLS-1$ //$NON-NLS-2$
    logger.debug("Args: " + Arrays.toString(args)); //$NON-NLS-1$
    logger.info("Using data in: " + ApplicationHelper.getDataFolder()); //$NON-NLS-1$

    if (cl.getOptionValue("exml") != null || cl.getOptionValue("eodb") != null) { //$NON-NLS-1$ //$NON-NLS-2$

        GTDFreeEngine engine = null;

        try {
            engine = new GTDFreeEngine();
        } catch (Exception e1) {
            logger.fatal("Fatal error, exiting.", e1); //$NON-NLS-1$
        }

        val = cl.getOptionValue("exml"); //$NON-NLS-1$
        if (val != null) {
            File f1 = new File(val);
            if (f1.isDirectory()) {
                f1 = new File(f1, "gtd-free-" + ApplicationHelper.formatLongISO(new Date()) + ".xml"); //$NON-NLS-1$ //$NON-NLS-2$
            }
            try {
                f1.getParentFile().mkdirs();
            } catch (Exception e) {
                logger.error("Export error.", e); //$NON-NLS-1$
            }
            try {
                engine.getGTDModel().exportXML(f1);
                logger.info("Data successfully exported as XML to " + f1.toString()); //$NON-NLS-1$
            } catch (Exception e) {
                logger.error("Export error.", e); //$NON-NLS-1$
            }
        }

        val = cl.getOptionValue("eodb"); //$NON-NLS-1$
        if (val != null) {
            File f1 = new File(val);
            if (f1.isDirectory()) {
                f1 = new File(f1, "gtd-free-" + ApplicationHelper.formatLongISO(new Date()) + ".odb-xml"); //$NON-NLS-1$ //$NON-NLS-2$
            }
            try {
                f1.getParentFile().mkdirs();
            } catch (Exception e) {
                logger.error("Export error.", e); //$NON-NLS-1$
            }
            try {
                GTDData data = engine.getGTDModel().getDataRepository();
                if (data instanceof GTDDataODB) {
                    try {
                        ((GTDDataODB) data).exportODB(f1);
                    } catch (Exception e) {
                        logger.error("Export error.", e); //$NON-NLS-1$
                    }
                    logger.info("Data successfully exported as ODB to " + f1.toString()); //$NON-NLS-1$
                } else {
                    logger.info("Data is not stored in ODB database, nothing is exported."); //$NON-NLS-1$
                }
            } catch (Exception e) {
                logger.error("Export error.", e); //$NON-NLS-1$
            }
        }

        try {
            engine.close(true, false);
        } catch (Exception e) {
            logger.error("Internal error.", e); //$NON-NLS-1$
        }

        return;
    }

    logger.debug("Using OS '" + System.getProperty("os.name") + "', '" + System.getProperty("os.version") //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$//$NON-NLS-4$
            + "', '" + System.getProperty("os.arch") + "'."); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
    logger.debug("Using Java '" + System.getProperty("java.runtime.name") + "' version '" //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$
            + System.getProperty("java.runtime.version") + "'."); //$NON-NLS-1$ //$NON-NLS-2$

    Locale[] supported = { Locale.ENGLISH, Locale.GERMAN };

    String def = Locale.getDefault().getLanguage();
    boolean toSet = true;
    for (Locale locale : supported) {
        toSet &= !locale.getLanguage().equals(def);
    }

    if (toSet) {
        logger.debug("System locale '" + def + "' not supported, setting to '" + Locale.ENGLISH.getLanguage() //$NON-NLS-1$//$NON-NLS-2$
                + "'."); //$NON-NLS-1$
        try {
            Locale.setDefault(Locale.ENGLISH);
        } catch (Exception e) {
            logger.warn("Setting default locale failed.", e); //$NON-NLS-1$
        }
    } else {
        logger.debug("Using locale '" + Locale.getDefault().toString() + "'."); //$NON-NLS-1$ //$NON-NLS-2$
    }

    try {
        //System.setProperty("swing.crossplatformlaf", "com.jgoodies.looks.plastic.PlasticXPLookAndFeel");
        //System.setProperty("swing.crossplatformlaf", "com.jgoodies.looks.plastic.Plastic3DLookAndFeel");
        //System.setProperty("swing.crossplatformlaf", "com.jgoodies.looks.plastic.PlasticLookAndFeel");
        //System.setProperty("swing.crossplatformlaf", "javax.swing.plaf.metal.MetalLookAndFeel");
        //System.setProperty("swing.crossplatformlaf", "com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
        if (System.getProperty("swing.crossplatformlaf") == null) { //$NON-NLS-1$
            String osName = System.getProperty("os.name"); //$NON-NLS-1$
            if (osName != null && osName.toLowerCase().indexOf("windows") != -1) { //$NON-NLS-1$
                UIManager.setLookAndFeel("com.jgoodies.looks.windows.WindowsLookAndFeel"); //$NON-NLS-1$
            } else {
                try {
                    // we prefer to use native L&F, many systems support GTK, even if Java thinks it is not supported
                    UIManager.setLookAndFeel("com.sun.java.swing.plaf.gtk.GTKLookAndFeel"); //$NON-NLS-1$
                } catch (Throwable e) {
                    logger.debug("GTK L&F not supported.", e); //$NON-NLS-1$
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                }
            }
        }
    } catch (Throwable e) {
        logger.warn("Setting L&F failed.", e); //$NON-NLS-1$
    }
    logger.debug("Using L&F '" + UIManager.getLookAndFeel().getName() + "' by " //$NON-NLS-1$//$NON-NLS-2$
            + UIManager.getLookAndFeel().getClass().getName());

    try {
        final GTDFree application = new GTDFree();

        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {

                    application.getJFrame();
                    application.restore();
                    //application.getJFrame().setVisible(true);
                    application.pushVisible();

                    ApplicationHelper.executeInBackground(new Runnable() {
                        @Override
                        public void run() {
                            if (SystemTray.isSupported() && application.getEngine().getGlobalProperties()
                                    .getBoolean(GlobalProperties.SHOW_TRAY_ICON, false)) {
                                try {
                                    SystemTray.getSystemTray().add(application.getTrayIcon());
                                } catch (AWTException e) {
                                    logger.error("Failed to activate system tray icon.", e); //$NON-NLS-1$
                                }
                            }
                        }
                    });

                    ApplicationHelper.executeInBackground(new Runnable() {

                        @Override
                        public void run() {
                            application.exportRemote();
                        }
                    });

                    if (application.getEngine().getGlobalProperties()
                            .getBoolean(GlobalProperties.CHECK_FOR_UPDATE_AT_START, true)) {
                        ApplicationHelper.executeInBackground(new Runnable() {

                            @Override
                            public void run() {
                                application.checkForUpdates(false);
                            }
                        });
                    }

                } catch (Throwable t) {
                    t.printStackTrace();
                    logger.fatal("Failed to start application, exiting.", t); //$NON-NLS-1$
                    if (application != null) {
                        application.close(true);
                    }
                    System.exit(0);
                }
            }
        });

        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                try {
                    application.close(true);
                } catch (Exception e) {
                    logger.warn("Failed to stop application.", e); //$NON-NLS-1$
                }
                logger.info("Closed."); //$NON-NLS-1$
                ApplicationHelper.releaseLock();
                LogManager.shutdown();
            }
        });
    } catch (Throwable t) {
        logger.fatal("Initialization failed, exiting.", t); //$NON-NLS-1$
        t.printStackTrace();
        System.exit(0);
    }
}

From source file:org.gudy.azureus2.ui.console.commands.OptionsConsoleCommand.java

public void printHelpExtra(PrintStream out, List args) {
    HelpFormatter formatter = new HelpFormatter();
    PrintWriter writer = new PrintWriter(out);
    writer.println("> -----");
    writer.println(getCommandDescriptions());
    //      formatter.printHelp(writer, 80, getCommandDescriptions(), ">>>", getOptions(), 4, 4, ">>>", true);
    formatter.printOptions(writer, 80, getOptions(), 4, 4);
    writer.println("> -----");
    writer.flush();//from   w ww .  ja  va 2 s  .  c om
}

From source file:org.jcryptool.commands.core.HelpCommand.java

/**
 * Generates an argument table for a command
 *
 * @param options the options of this command
 * @return/*from   w w  w  .  j  a  v  a2 s  .  c om*/
 */
private static String getGeneratedArglist(Options options) {
    HelpFormatter formatter = new HelpFormatter();
    StringWriter writer = new StringWriter();
    formatter.printOptions(new PrintWriter(writer), CONSOLE_WIDTH, options, 4, 8);
    return writer.toString();
}

From source file:org.jumpmind.symmetric.SymmetricAdmin.java

private void printHelpCommand(CommandLine line) {
    String[] args = line.getArgs();
    if (args.length > 1) {
        String cmd = args[1];/*from  ww w . j  a v a 2  s . co m*/
        HelpFormatter format = new HelpFormatter();
        PrintWriter writer = new PrintWriter(System.out);
        Options options = new Options();

        if (!Message.containsKey("SymAdmin.Usage." + cmd)) {
            System.err.println("ERROR: no help text for subcommand '" + cmd + "' was found.");
            System.err.println("For a list of subcommands, use " + app + " --" + HELP + "\n");
            return;
        }
        format.printWrapped(writer, WIDTH,
                "Usage: " + app + " " + cmd + " " + Message.get("SymAdmin.Usage." + cmd) + "\n");
        format.printWrapped(writer, WIDTH, Message.get("SymAdmin.Help." + cmd));

        if (cmd.equals(CMD_SEND_SQL) || cmd.equals(CMD_SEND_SCHEMA) || cmd.equals(CMD_RELOAD_TABLE)
                || cmd.equals(CMD_SEND_SCRIPT)) {
            addOption(options, "n", OPTION_NODE, true);
            addOption(options, "g", OPTION_NODE_GROUP, true);
        }
        if (cmd.equals(CMD_RELOAD_TABLE)) {
            addOption(options, "c", OPTION_CATALOG, true);
            addOption(options, "s", OPTION_SCHEMA, true);
            addOption(options, "w", OPTION_WHERE, true);
        }
        if (cmd.equals(CMD_SYNC_TRIGGERS)) {
            addOption(options, "o", OPTION_OUT, false);
            addOption(options, "f", OPTION_FORCE, false);
        }
        if (cmd.equals(CMD_RELOAD_NODE)) {
            addOption(options, "r", OPTION_REVERSE, false);
        }

        if (options.getOptions().size() > 0) {
            format.printWrapped(writer, WIDTH, "\nOptions:");
            format.printOptions(writer, WIDTH, options, PAD, PAD);
        }

        if (!ArrayUtils.contains(NO_ENGINE_REQUIRED, cmd)) {
            format.printWrapped(writer, WIDTH, "\nEngine options:");
            options = new Options();
            super.buildOptions(options);
            format.printOptions(writer, WIDTH, options, PAD, PAD);

            format.printWrapped(writer, WIDTH, "\nCrypto options:");
            options = new Options();
            buildCryptoOptions(options);
            format.printOptions(writer, WIDTH, options, PAD, PAD);
        }
        writer.flush();
    }
}