List of usage examples for org.apache.commons.cli HelpFormatter printWrapped
public void printWrapped(PrintWriter pw, int width, String text)
From source file:openlr.otk.options.UsageBuilder.java
/** * Prints the command line syntax./*from w ww.j av a 2 s.c om*/ * * @param target * The target stream to write to * @param options * The tool options * @param argsList * The tool arguments * @param toolID * The tool short name * @param toolDescription * The description of the tool */ public static void usage(final OutputStream target, final Options options, final List<Argument<?>> argsList, final String toolID, final String toolDescription) { HelpFormatter formatter = new HelpFormatter(); PrintWriter pw = new PrintWriter(new OutputStreamWriter(target, IOUtils.SYSTEM_DEFAULT_CHARSET)); String optionsListStr = buildOptionsList(options); String argsListStr = buildArgumentsList(argsList); formatter.printUsage(pw, HelpFormatter.DEFAULT_WIDTH, "java -jar otk-<version>.jar " + toolID + " " + optionsListStr + " " + argsListStr); formatter.printWrapped(pw, HelpFormatter.DEFAULT_WIDTH, toolDescription); if (options.getOptions().size() > 0) { formatter.printOptions(pw, HelpFormatter.DEFAULT_WIDTH, options, HelpFormatter.DEFAULT_LEFT_PAD, HelpFormatter.DEFAULT_DESC_PAD); } printArgumentDescriptions(pw, argsList); formatter.printWrapped(pw, HelpFormatter.DEFAULT_WIDTH, USAGE_FOOTER); pw.flush(); }
From source file:org.apache.nifi.toolkit.cli.impl.command.AbstractCommand.java
@Override public void printUsage(String errorMessage) { output.println();//from w w w.j ava 2 s . c o m if (errorMessage != null) { output.println("ERROR: " + errorMessage); output.println(); } final PrintWriter printWriter = new PrintWriter(output); final int width = 80; final HelpFormatter hf = new HelpFormatter(); hf.setWidth(width); hf.printWrapped(printWriter, width, getDescription()); hf.printWrapped(printWriter, width, ""); if (isReferencable()) { hf.printWrapped(printWriter, width, "PRODUCES BACK-REFERENCES"); hf.printWrapped(printWriter, width, ""); } hf.printHelp(printWriter, hf.getWidth(), getName(), null, getOptions(), hf.getLeftPadding(), hf.getDescPadding(), null, false); printWriter.println(); printWriter.flush(); }
From source file:org.apache.nifi.toolkit.cli.impl.command.AbstractCommandGroup.java
@Override public void printUsage(final boolean verbose) { if (verbose) { final PrintWriter printWriter = new PrintWriter(output); final int width = 80; final HelpFormatter hf = new HelpFormatter(); hf.setWidth(width);/*from www.j a v a 2s . c o m*/ commands.stream().forEach(c -> { hf.printWrapped(printWriter, width, "-------------------------------------------------------------------------------"); hf.printWrapped(printWriter, width, "COMMAND: " + getName() + " " + c.getName()); hf.printWrapped(printWriter, width, ""); hf.printWrapped(printWriter, width, "- " + c.getDescription()); hf.printWrapped(printWriter, width, ""); if (c.isReferencable()) { hf.printWrapped(printWriter, width, "PRODUCES BACK-REFERENCES"); hf.printWrapped(printWriter, width, ""); } }); printWriter.flush(); } else { commands.stream().forEach(c -> output.println("\t" + getName() + " " + c.getName())); } output.flush(); }
From source file:org.apache.parquet.tools.Main.java
public static void showUsage(HelpFormatter format, PrintWriter err, String name, Command command) { Options options = mergeOptions(OPTIONS, command.getOptions()); String[] usage = command.getUsageDescription(); String ustr = name + " [option...]"; if (usage != null && usage.length >= 1) { ustr = ustr + " " + usage[0]; }/*w w w .j a v a2 s. c o m*/ format.printWrapped(err, WIDTH, name + ":\n" + command.getCommandDescription()); format.printUsage(err, WIDTH, ustr); format.printWrapped(err, WIDTH, LEFT_PAD, "where option is one of:"); format.printOptions(err, WIDTH, options, LEFT_PAD, DESC_PAD); if (usage != null && usage.length >= 2) { for (int i = 1; i < usage.length; ++i) { format.printWrapped(err, WIDTH, LEFT_PAD, usage[i]); } } }
From source file:org.blom.martin.stream2gdrive.Stream2GDrive.java
public static void main(String[] args) throws Exception { Options opt = new Options(); opt.addOption("?", "help", false, "Show usage."); opt.addOption("V", "version", false, "Print version information."); opt.addOption("v", "verbose", false, "Display progress status."); opt.addOption("p", "parent", true, "Operate inside this Google Drive folder instead of root."); opt.addOption("o", "output", true, "Override output/destination file name"); opt.addOption("m", "mime", true, "Override guessed MIME type."); opt.addOption("C", "chunk-size", true, "Set transfer chunk size, in MiB. Default is 10.0 MiB."); opt.addOption("r", "auto-retry", false, "Enable automatic retry with exponential backoff in case of error."); opt.addOption(null, "oob", false, "Provide OAuth authentication out-of-band."); try {//from w ww .j a v a2 s. c o m CommandLine cmd = new GnuParser().parse(opt, args, false); args = cmd.getArgs(); if (cmd.hasOption("version")) { String version = "?"; String date = "?"; try { Properties props = new Properties(); props.load(resource("/build.properties")); version = props.getProperty("version", "?"); date = props.getProperty("date", "?"); } catch (Exception ignored) { } System.err.println(String.format("%s %s. Build %s (%s)", APP_NAME, APP_VERSION, version, date)); System.err.println(); } if (cmd.hasOption("help")) { throw new ParseException(null); } if (args.length < 1) { if (cmd.hasOption("version")) { return; } else { throw new ParseException("<cmd> missing"); } } String command = args[0]; JsonFactory jf = JacksonFactory.getDefaultInstance(); HttpTransport ht = GoogleNetHttpTransport.newTrustedTransport(); GoogleClientSecrets gcs = GoogleClientSecrets.load(jf, resource("/client_secrets.json")); Set<String> scopes = new HashSet<String>(); scopes.add(DriveScopes.DRIVE_FILE); scopes.add(DriveScopes.DRIVE_METADATA_READONLY); GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(ht, jf, gcs, scopes) .setDataStoreFactory(new FileDataStoreFactory(appDataDir())).build(); VerificationCodeReceiver vcr = !cmd.hasOption("oob") ? new LocalServerReceiver() : new GooglePromptReceiver(); Credential creds = new AuthorizationCodeInstalledApp(flow, vcr).authorize("user"); List<HttpRequestInitializer> hrilist = new ArrayList<HttpRequestInitializer>(); hrilist.add(creds); if (cmd.hasOption("auto-retry")) { ExponentialBackOff.Builder backoffBuilder = new ExponentialBackOff.Builder() .setInitialIntervalMillis(6 * 1000) // 6 seconds initial retry period .setMaxElapsedTimeMillis(45 * 60 * 1000) // 45 minutes maximum total wait time .setMaxIntervalMillis(15 * 60 * 1000) // 15 minute maximum interval .setMultiplier(1.85).setRandomizationFactor(0.5); // Expected total waiting time before giving up = sum([6*1.85^i for i in range(10)]) // ~= 55 minutes // Note that Google API's HttpRequest allows for up to 10 retry. hrilist.add(new ExponentialBackOffHttpRequestInitializer(backoffBuilder)); } HttpRequestInitializerStacker hristack = new HttpRequestInitializerStacker(hrilist); Drive client = new Drive.Builder(ht, jf, hristack).setApplicationName(APP_NAME + "/" + APP_VERSION) .build(); boolean verbose = cmd.hasOption("verbose"); float chunkSize = Float.parseFloat(cmd.getOptionValue("chunk-size", "10.0")); String root = null; if (cmd.hasOption("parent")) { root = findWorkingDirectory(client, cmd.getOptionValue("parent")); } if (command.equals("get")) { String file; if (args.length < 2) { throw new ParseException("<file> missing"); } else if (args.length == 2) { file = args[1]; } else { throw new ParseException("Too many arguments"); } download(client, ht, root, file, cmd.getOptionValue("output", file), verbose, chunkSize); } else if (command.equals("put")) { String file; if (args.length < 2) { throw new ParseException("<file> missing"); } else if (args.length == 2) { file = args[1]; } else { throw new ParseException("Too many arguments"); } upload(client, file, root, cmd.getOptionValue("output", new File(file).getName()), cmd.getOptionValue("mime", new javax.activation.MimetypesFileTypeMap().getContentType(file)), verbose, chunkSize); } else if (command.equals("trash")) { String file; if (args.length < 2) { throw new ParseException("<file> missing"); } else if (args.length == 2) { file = args[1]; } else { throw new ParseException("Too many arguments"); } trash(client, root, file); } else if (command.equals("md5") || command.equals("list")) { if (args.length > 1) { throw new ParseException("Too many arguments"); } list(client, root, command.equals("md5")); } else { throw new ParseException("Invalid command: " + command); } } catch (ParseException ex) { PrintWriter pw = new PrintWriter(System.err); HelpFormatter hf = new HelpFormatter(); hf.printHelp(pw, 80, "stream2gdrive [OPTIONS] <cmd> [<options>]", " Commands: get <file>, list, md5, put <file>, trash <file>.", opt, 2, 8, "Use '-' as <file> for standard input."); if (ex.getMessage() != null && !ex.getMessage().isEmpty()) { pw.println(); hf.printWrapped(pw, 80, String.format("Error: %s.", ex.getMessage())); } pw.flush(); System.exit(EX_USAGE); } catch (NumberFormatException ex) { System.err.println("Invalid decimal number: " + ex.getMessage() + "."); System.exit(EX_USAGE); } catch (IOException ex) { System.err.println("I/O error: " + ex.getMessage() + "."); System.exit(EX_IOERR); } }
From source file:org.codeseed.common.config.ext.CommandLineHelper.java
/** * Returns a property source from the supplied command line arguments. * * @param args//ww w . j a v a2s .co m * the arguments passed from the command line * @return a property source backed by the parsed command line arguments */ public PropertySource parse(String[] args) { // Construct the command line options final Options options = this.options.build(); if (helpOption != null) { options.addOption(helpOption); } try { final CommandLine commandLine = parser.parse(options, args); if (helpOption != null && commandLine.hasOption(helpOption.getOpt())) { // Display the help HelpFormatter help = new HelpFormatter(); help.setSyntaxPrefix(syntaxPrefix()); help.setLongOptPrefix(" --"); help.printHelp(err, terminalWidth, applicationName(), header(), options, 1, 1, footer(), true); return helpExit(); } else { // Wrapped the parsed commands in a property source return new CommandLinePropertySource(commandLine); } } catch (ParseException e) { // Display the error and usage message HelpFormatter help = new HelpFormatter(); help.printWrapped(err, terminalWidth, e.getMessage()); help.printUsage(err, terminalWidth, applicationName(), options); throw usageExit(e); } }
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 w ww. java 2 s . c o m*/ * @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.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 w w . j av a 2 s . c o m hf.printWrapped(err, 80, "Invalid arguments: " + error + "."); } err.flush(); System.exit(rc); }
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];// www.j a va2 s .c om 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(); } }
From source file:org.ldmud.jldmud.CommandLineArguments.java
/** * Parse the commandline and set the associated globals. * * @return {@code true} if the main program should exit; in that case {@link @getExitCode()} provides the suggest exit code. *///w ww . j av a2s . c om @SuppressWarnings("static-access") public boolean parseCommandline(String[] args) { try { Option configSetting = OptionBuilder.withLongOpt("config").withArgName("setting=value").hasArgs(2) .withValueSeparator() .withDescription( "Set the configuration setting to the given value (overrides any setting in the <config settings> file). Unsupported settings are ignored.") .create("C"); Option help = OptionBuilder.withLongOpt("help").withDescription("Print the help text and exits.") .create("h"); Option helpConfig = OptionBuilder.withLongOpt("help-config") .withDescription("Print the <config settings> help text and exits.").create(); Option version = OptionBuilder.withLongOpt("version") .withDescription("Print the driver version and exits").create("V"); Option printConfig = OptionBuilder.withLongOpt("print-config") .withDescription("Print the effective configuration settings to stdout and exit.").create(); Option printLicense = OptionBuilder.withLongOpt("license") .withDescription("Print the software license and exit.").create(); Options options = new Options(); options.addOption(help); options.addOption(helpConfig); options.addOption(version); options.addOption(configSetting); options.addOption(printConfig); options.addOption(printLicense); CommandLineParser parser = new PosixParser(); CommandLine line = parser.parse(options, args); /* Handle the print-help-and-exit options first, to allow them to be chained in a nice way. */ boolean helpOptionsGiven = false; if (line.hasOption(version.getOpt())) { System.out.println( Version.DRIVER_NAME + " " + Version.getVersionString() + " - a LPMud Game Driver."); System.out.println(Version.Copyright); System.out.print(Version.DRIVER_NAME + " is licensed under the " + Version.License + "."); if (!line.hasOption(printLicense.getLongOpt())) { System.out.print(" Use option --license for details."); } System.out.println(); helpOptionsGiven = true; } if (line.hasOption(printLicense.getLongOpt())) { if (helpOptionsGiven) { System.out.println(); } printLicense(); helpOptionsGiven = true; } if (line.hasOption(help.getOpt())) { final PrintWriter systemOut = new PrintWriter(System.out, true); HelpFormatter formatter = new HelpFormatter(); if (helpOptionsGiven) { System.out.println(); } System.out.println("Usage: " + Version.DRIVER_NAME + " [options] [<config settings>]"); System.out.println(); formatter.printWrapped(systemOut, formatter.getWidth(), "The <config settings> is a file containing the game settings; if not specified, it defaults to '" + GameConfiguration.DEFAULT_SETTINGS_FILE + "'. " + "The settings file must exist if no configuration setting is specified via commandline argument."); System.out.println(); formatter.printOptions(systemOut, formatter.getWidth(), options, formatter.getLeftPadding(), formatter.getDescPadding()); helpOptionsGiven = true; } if (line.hasOption(helpConfig.getLongOpt())) { if (helpOptionsGiven) { System.out.println(); } GameConfiguration.printTemplate(); helpOptionsGiven = true; } if (helpOptionsGiven) { exitCode = 0; return true; } /* Parse the real options */ /* TODO: If we get many real options, it would be useful to implement a more general system like {@link GameConfiguration#SettingBase} */ if (line.hasOption(configSetting.getLongOpt())) { configSettings = line.getOptionProperties(configSetting.getLongOpt()); } if (line.hasOption(printConfig.getLongOpt())) { printConfiguration = true; } if (line.getArgs().length > 1) { throw new ParseException("Too many arguments"); } if (line.getArgs().length == 1) { settingsFilename = line.getArgs()[0]; } return false; } catch (ParseException e) { System.err.println("Error: " + e.getMessage()); exitCode = 1; return true; } }