Java Code Examples for org.apache.commons.cli.Option#getOpt()

The following examples show how to use org.apache.commons.cli.Option#getOpt() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ExecutePlatformCommandCommand.java    From incubator-retired-blur with Apache License 2.0 6 votes vote down vote up
private BlurObject createBlurObject(CommandLine commandLine, CommandDescriptor descriptor) throws CommandException {
  Map<String, ArgumentDescriptor> arguments = new TreeMap<String, ArgumentDescriptor>(
      descriptor.getOptionalArguments());
  arguments.putAll(descriptor.getRequiredArguments());
  BlurObject blurObject = new BlurObject();
  if (commandLine == null) {
    return null;
  }
  Option[] options = commandLine.getOptions();
  for (Option option : options) {
    String name = option.getOpt();
    String value = option.getValue();
    ArgumentDescriptor argumentDescriptor = arguments.get(name);
    String type = argumentDescriptor.getType();
    blurObject.put(name, convertIfNeeded(value, type));
  }
  return blurObject;
}
 
Example 2
Source File: KeywordOptimizer.java    From keyword-optimizer with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the only specified 'seed' option or an exception if no or more than one is specified.
 *
 * @param cmdLine the parsed command line parameters
 * @return the 'seed' {@link Option}
 * @throws KeywordOptimizerException in case there is no or more than one 'seed' parameter
 *         specified
 */
private static Option getOnlySeedOption(CommandLine cmdLine) throws KeywordOptimizerException {
  Option seedOption = null;

  for (Option option : cmdLine.getOptions()) {
    if (option.getOpt().startsWith("s")) {
      if (seedOption != null) {
        throw new KeywordOptimizerException("Only one 'seed' option is allowed "
            + "(remove either " + seedOption.getOpt() + " or " + option.getOpt() + ")");
      }

      seedOption = option;
    }
  }

  if (seedOption == null) {
    throw new KeywordOptimizerException("You must specify a 'seed' parameter");
  }

  return seedOption;
}
 
Example 3
Source File: CliUtil.java    From termsuite-core with Apache License 2.0 6 votes vote down vote up
/**
 * Displays all command line options in log messages.
 * @param line
 */
public static void logCommandLineOptions(Logger logger, CommandLine line) {
	for (Option myOption : line.getOptions()) {
		String message;
		String opt = "";
		if(myOption.getOpt() != null) {
			opt+="-"+myOption.getOpt();
			if(myOption.getLongOpt() != null) 
				opt+=" (--"+myOption.getLongOpt()+")";
		} else
			opt+="--"+myOption.getLongOpt()+"";
			
		if(myOption.hasArg()) 
		    message = opt + " " + myOption.getValue();
		else
			message = opt;
			
		
		logger.info("with option: " + message);
	}
}
 
Example 4
Source File: MkDocs.java    From rug-cli with GNU General Public License v3.0 6 votes vote down vote up
protected static int compareOptions(Option a, Option b) {
    String aShort = a.getOpt();
    String bShort = b.getOpt();
    String aLong = a.getLongOpt();
    String bLong = b.getLongOpt();
    if (aShort != null && aShort.length() > 0 && bShort != null && bShort.length() > 0) {
        return aShort.compareToIgnoreCase(bShort);
    } else if (aLong != null && aLong.length() > 0 && bLong != null && bLong.length() > 0) {
        return aLong.compareToIgnoreCase(bLong);
    } else if (aShort != null && aShort.length() > 0 && bLong != null && bLong.length() > 0) {
        return aShort.compareToIgnoreCase(bLong);
    } else if (aLong != null && aLong.length() > 0 && bShort != null && bShort.length() > 0) {
        return aLong.compareToIgnoreCase(bShort);
    } else {
        return 0;
    }
}
 
Example 5
Source File: OptimizerOptions.java    From incubator-hivemall with Apache License 2.0 5 votes vote down vote up
public static void processOptions(@Nullable CommandLine cl,
        @Nonnull Map<String, String> options) {
    if (cl == null) {
        return;
    }
    for (Option opt : cl.getOptions()) {
        String optName = opt.getLongOpt();
        if (optName == null) {
            optName = opt.getOpt();
        }
        options.put(optName, opt.getValue());
    }
}
 
Example 6
Source File: CommandCompleter.java    From attic-stratos with Apache License 2.0 5 votes vote down vote up
public CommandCompleter(Map<String, Command<StratosCommandContext>> commands) {
    if (logger.isDebugEnabled()) {
        logger.debug("Creating auto complete for {} commands", commands.size());
    }
    fileNameCompleter = new StratosFileNameCompleter();
    argumentMap = new HashMap<String, Collection<String>>();
    defaultCommandCompleter = new StringsCompleter(commands.keySet());
    helpCommandCompleter = new ArgumentCompleter(new StringsCompleter(CliConstants.HELP_ACTION),
            defaultCommandCompleter);
    for (String action : commands.keySet()) {

        Command<StratosCommandContext> command = commands.get(action);
        Options commandOptions = command.getOptions();
        if (commandOptions != null) {
            if (logger.isDebugEnabled()) {
                logger.debug("Creating argument completer for command: {}", action);
            }
            List<String> arguments = new ArrayList<String>();
            Collection<?> allOptions = commandOptions.getOptions();
            for (Object o : allOptions) {
                Option option = (Option) o;
                String longOpt = option.getLongOpt();
                String opt = option.getOpt();
                if (StringUtils.isNotBlank(longOpt)) {
                    arguments.add("--" + longOpt);
                } else if (StringUtils.isNotBlank(opt)) {
                    arguments.add("-" + opt);
                }
            }

            argumentMap.put(action, arguments);
        }
    }
}
 
Example 7
Source File: MarkdownExtensions.java    From sarl with Apache License 2.0 5 votes vote down vote up
private static String getKey(Option opt) {
	final String val = opt.getLongOpt();
	if (val == null) {
		return opt.getOpt();
	}
	return val;
}
 
Example 8
Source File: GfxdHelpFormatter.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * Appends the usage clause for an Option to a StringBuffer.
 * 
 * @param buff
 *          the StringBuffer to append to
 * @param option
 *          the Option to append
 * @param required
 *          whether the Option is required or not
 */
protected void appendOption(final StringBuilder buff, final Option option,
    final boolean required) {
  if (!required) {
    buff.append('[');
  }

  if (option.getOpt() != null) {
    buff.append(getOptPrefix()).append(option.getOpt());
  }
  else {
    buff.append(getLongOptPrefix()).append(option.getLongOpt());
  }

  // if the Option has a value
  if (option.hasArg() && option.hasArgName()) {
    if (option.hasOptionalArg()) {
      buff.append('[');
    }
    if (option.hasValueSeparator()) {
      buff.append(option.getValueSeparator());
    }
    else {
      buff.append(' ');
    }
    buff.append('<').append(option.getArgName()).append('>');
    if (option.hasOptionalArg()) {
      buff.append(']');
    }
  }

  // if the Option is not a required option
  if (!required) {
    buff.append(']');
  }
}
 
Example 9
Source File: MkDocs.java    From rug-cli with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Oh yeah?  It's not as bad as this!
 *
 * @param o  Option to be formatted.
 * @return   Markdown formatted documentation string.
 */
protected static String formatOption(Option o) {
    String shortString = "";
    String shortOpt = o.getOpt();
    if (shortOpt != null && shortOpt.length() > 0) {
        shortString = "-" + shortOpt;
    }
    String longString = "";
    String longOpt = o.getLongOpt();
    if (longOpt != null && longOpt.length() > 0) {
        longString = "--" + longOpt;
    }
    String joinString = "";
    if (shortString.length() > 0 && longString.length() > 0) {
        joinString = ", ";
    }
    String argName = o.getArgName();
    if (argName != null && argName.length() > 0) {
        if (shortString.length() > 0) {
            shortString += " " + argName;
        }
        if (longString.length() > 0) {
            longString += "=" + argName;
        }
    }
    if (shortString.length() > 0) {
        shortString = "`" + shortString + "`";
    }
    if (longString.length() > 0) {
        longString = "`" + longString + "`";
    }
    // This formatting uses the MkDocs def_list markdown extension
    return String.format("%s%s%s\n:   %s\n\n", shortString, joinString, longString, o.getDescription());
}
 
Example 10
Source File: WorkerConf.java    From uReplicator with Apache License 2.0 5 votes vote down vote up
public static WorkerConf getWorkerConf(CommandLine cmd) {
  WorkerConf workerConf = new WorkerConf();
  for (Option option : constructWorkerOptions().getOptions()) {
    String opt = option.getOpt();
    if (cmd.hasOption(opt)) {
      workerConf.setProperty(opt, cmd.getOptionValue(opt));
    }
  }
  return workerConf;
}
 
Example 11
Source File: GfxdHelpFormatter.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * Appends the usage clause for an Option to a StringBuffer.
 * 
 * @param buff
 *          the StringBuffer to append to
 * @param option
 *          the Option to append
 * @param required
 *          whether the Option is required or not
 */
protected void appendOption(final StringBuilder buff, final Option option,
    final boolean required) {
  if (!required) {
    buff.append('[');
  }

  if (option.getOpt() != null) {
    buff.append(getOptPrefix()).append(option.getOpt());
  }
  else {
    buff.append(getLongOptPrefix()).append(option.getLongOpt());
  }

  // if the Option has a value
  if (option.hasArg() && option.hasArgName()) {
    if (option.hasOptionalArg()) {
      buff.append('[');
    }
    if (option.hasValueSeparator()) {
      buff.append(option.getValueSeparator());
    }
    else {
      buff.append(' ');
    }
    buff.append('<').append(option.getArgName()).append('>');
    if (option.hasOptionalArg()) {
      buff.append(']');
    }
  }

  // if the Option is not a required option
  if (!required) {
    buff.append(']');
  }
}
 
Example 12
Source File: CommandlineOption.java    From marklogic-contentpump with Apache License 2.0 5 votes vote down vote up
public CommandlineOption(Option opt)
        throws IllegalArgumentException {
    super(opt.getOpt(), opt.hasArg(), opt.getDescription());

    this.setLongOpt(opt.getLongOpt());
    this.setRequired(opt.isRequired());
    this.setArgName(opt.getArgName());
    this.setArgs(opt.getArgs());
    this.setOptionalArg(opt.hasOptionalArg());
    this.setType(opt.getType());
    this.setValueSeparator(opt.getValueSeparator());
}
 
Example 13
Source File: CommandLineApplication.java    From validator with Apache License 2.0 5 votes vote down vote up
private static boolean checkOptionWithValue(final Option option, final CommandLine cmd) {
    final String opt = option.getOpt();
    if (cmd.hasOption(opt)) {
        final String value = cmd.getOptionValue(opt);
        if (StringUtils.isNoneBlank(value)) {
            return true;
        } else {
            throw new IllegalArgumentException(String.format("Option value required for Option '%s'", option.getLongOpt()));
        }
    } else if (option.isRequired()) {

        throw new IllegalArgumentException(String.format("Option '%s' required ", option.getLongOpt()));
    }
    return false;
}
 
Example 14
Source File: TableReporter.java    From hbase-operator-tools with Apache License 2.0 4 votes vote down vote up
public static void main(String [] args)
throws ParseException, IOException, ExecutionException, InterruptedException {
  Options options = new Options();
  Option help = Option.builder("h").longOpt("help").
      desc("output this help message").build();
  options.addOption(help);
  Option limitOption = Option.builder("l").longOpt("limit").hasArg().build();
  options.addOption(limitOption);
  Option fractionOption = Option.builder("f").longOpt("fraction").hasArg().build();
  options.addOption(fractionOption);
  Option regionOption = Option.builder("r").longOpt("region").hasArg().build();
  options.addOption(regionOption);
  Option threadsOption = Option.builder("t").longOpt("threads").hasArg().build();
  options.addOption(threadsOption);
  Option configOption = Option.builder("D").valueSeparator().argName("property=value").
      hasArgs().build();
  options.addOption(configOption);
  // Parse command-line.
  CommandLineParser parser = new DefaultParser();
  CommandLine commandLine = parser.parse(options, args);

  // Process general options.
  if (commandLine.hasOption(help.getOpt()) || commandLine.getArgList().isEmpty()) {
    usage(options);
    System.exit(0);
  }

  int limit = -1;
  String opt = limitOption.getOpt();
  if (commandLine.hasOption(opt)) {
    limit = Integer.parseInt(commandLine.getOptionValue(opt));
  }
  double fraction = 1.0;
  opt = fractionOption.getOpt();
  if (commandLine.hasOption(opt)) {
    fraction = Double.parseDouble(commandLine.getOptionValue(opt));
    if (fraction > 1 || fraction <= 0) {
      usage(options, "Bad fraction: " + fraction + "; fraction must be > 0 and < 1");
      System.exit(0);
    }
  }
  int threads = 1;
  opt = threadsOption.getOpt();
  if (commandLine.hasOption(opt)) {
    threads = Integer.parseInt(commandLine.getOptionValue(opt));
    if (threads > 1000 || threads <= 0) {
      usage(options, "Bad thread count: " + threads + "; must be > 0 and < 1000");
      System.exit(0);
    }
  }

  String encodedRegionName = null;
  opt = regionOption.getOpt();
  if (commandLine.hasOption(opt)) {
    encodedRegionName = commandLine.getOptionValue(opt);
  }

  Configuration configuration = HBaseConfiguration.create();
  opt = configOption.getOpt();
  if (commandLine.hasOption(opt)) {
    // If many options, they all show up here in the keyValues
    // array, one after the other.
    String [] keyValues = commandLine.getOptionValues(opt);
    for (int i = 0; i < keyValues.length;) {
      configuration.set(keyValues[i], keyValues[i + 1]);
      i += 2; // Skip over this key and value to next one.
    }
  }

  // Now process commands.
  String [] commands = commandLine.getArgs();
  if (commands.length < 1) {
    usage(options, "No TABLENAME: " + Arrays.toString(commands));
    System.exit(1);
  }

  String now = Instant.now().toString();
  for (String command : commands) {
    sketch(configuration, command, limit, fraction, threads, now, encodedRegionName);
  }
}
 
Example 15
Source File: CLIHelpFormatter.java    From kieker with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
protected StringBuffer renderOptions(final StringBuffer sb, final int width, final Options options, final int leftPad, final int descPad) {
	final String lpad = this.createPadding(leftPad);
	final String dpad = this.createPadding(8); // we use a fixed value instead of descPad

	StringBuilder optBuf;

	final List<Option> optList = new ArrayList<Option>(options.getOptions());
	Collections.sort(optList, this.getOptionComparator());

	for (final Iterator<Option> i = optList.iterator(); i.hasNext();) {
		final Option option = i.next();

		optBuf = new StringBuilder(8);

		if (option.getOpt() == null) {
			optBuf.append(lpad).append("   ").append(this.getLongOptPrefix()).append(option.getLongOpt());
		} else {
			optBuf.append(lpad).append(this.getOptPrefix()).append(option.getOpt());

			if (option.hasLongOpt()) {
				optBuf.append(',').append(this.getLongOptPrefix()).append(option.getLongOpt());
			}
		}

		if (option.hasArg()) {
			if (option.hasArgName()) {
				optBuf.append(" <").append(option.getArgName()).append('>');
			} else {
				optBuf.append(' ');
			}
		}

		sb.append(optBuf.toString()).append(this.getNewLine());

		optBuf = new StringBuilder();
		optBuf.append(dpad);

		if (option.getDescription() != null) {
			optBuf.append(option.getDescription());
		}

		this.renderWrappedText(sb, width, dpad.length(), optBuf.toString());

		if (i.hasNext()) {
			sb.append(this.getNewLine());
			sb.append(this.getNewLine());
		}
	}

	return sb;
}
 
Example 16
Source File: CommandLineOptions.java    From LiquidDonkey with MIT License 4 votes vote down vote up
public String opt(Option option) {
    return option.hasLongOpt()
            ? option.getLongOpt()
            : option.getOpt();
}
 
Example 17
Source File: MarkdownExtensions.java    From sarl with Apache License 2.0 4 votes vote down vote up
/** Render the option help to a Markdown table.
 *
 * @param options the options.
 * @return the markdown table.
 */
protected static String _renderToMarkdown(Options options) {
	if (options == null) {
		return ""; //$NON-NLS-1$
	}
	final List<Option> optList = new ArrayList<>(options.getOptions());
	if (optList.isEmpty()) {
		return ""; //$NON-NLS-1$
	}
	Collections.sort(optList, new OptionComparator());

	final StringBuilder buffer = new StringBuilder();
	for (final Option option : optList) {
		buffer.append("| `"); //$NON-NLS-1$
		if (option.getOpt() == null) {
			buffer.append(DEFAULT_LONG_OPT_PREFIX).append(option.getLongOpt());
		} else {
			buffer.append(DEFAULT_OPT_PREFIX).append(option.getOpt());
			if (option.hasLongOpt()) {
				buffer.append("`, `"); //$NON-NLS-1$
				buffer.append(DEFAULT_LONG_OPT_PREFIX).append(option.getLongOpt());
			}
		}

		if (option.hasArg()) {
			if (option.hasArgName()) {
				buffer.append(" <").append(option.getArgName()).append(">"); //$NON-NLS-1$ //$NON-NLS-2$
			}
		}

		buffer.append("` | "); //$NON-NLS-1$

		if (option.getDescription() != null) {
			String text = option.getDescription().replaceAll("[ \t\n\r\f]+", " "); //$NON-NLS-1$ //$NON-NLS-2$
			text = text.replaceAll("\\<", "&lt;");  //$NON-NLS-1$//$NON-NLS-2$
			text = text.replaceAll("\\>", "&gt;");  //$NON-NLS-1$//$NON-NLS-2$
			buffer.append(text);
		}

		buffer.append(" |\n"); //$NON-NLS-1$
	}

	return buffer.toString();
}