List of usage examples for org.apache.commons.cli Option hasArg
public boolean hasArg()
From source file:com.splunk.Command.java
public Command parse(String[] argv) { CommandLineParser parser = new PosixParser(); CommandLine cmdline = null;/*from www . jav a2s.c o m*/ try { cmdline = parser.parse(this.rules, argv); } catch (ParseException e) { error(e.getMessage()); } // Unpack the cmdline into a simple Map of options and optionally // assign values to any corresponding fields found in the Command class. for (Option option : cmdline.getOptions()) { String name = option.getLongOpt(); Object value = option.getValue(); // Figure out the type of the option and convert the value. if (!option.hasArg()) { // If it has no arg, then its implicitly boolean and presence // of the argument indicates truth. value = true; } else { Class type = (Class) option.getType(); if (type == null) { // Null implies String, no conversion necessary } else if (type == Integer.class) { value = Integer.parseInt((String) value); } else { assert false; // Unsupported type } } this.opts.put(name, value); // Look for a field of the Command class (or subclass) that // matches the long name of the option and, if found, assign the // corresponding option value in order to provide simplified // access to command options. try { java.lang.reflect.Field field = this.getClass().getField(name); field.set(this, value); } catch (NoSuchFieldException e) { continue; } catch (IllegalAccessException e) { throw new RuntimeException(e.getMessage(), e); } } String[] orig = this.args; String[] more = cmdline.getArgs(); this.args = new String[orig.length + more.length]; System.arraycopy(orig, 0, this.args, 0, orig.length); System.arraycopy(more, 0, this.args, orig.length, more.length); if (this.help) { printHelp(); System.exit(0); } return this; }
From source file:com.github.lindenb.jvarkit.util.command.CommandFactory.java
public int instanceMain(final String args[]) { /* create a new empty Command */ Command cmd = null;/* w w w .ja va 2 s.c o m*/ try { /* cmd line */ final StringBuilder sb = new StringBuilder(); for (String s : args) { if (sb.length() != 0) sb.append(" "); sb.append(s); } /* create new options */ final Options options = new Options(); /* get all options and add it to options */ fillOptions(options); /* create a new CLI parser */ final CommandLineParser parser = new DefaultParser(); final CommandLine cli = parser.parse(options, args); /* loop over the processed options */ for (final Option opt : cli.getOptions()) { if (opt.hasArg() && !opt.hasOptionalArg() && opt.getValue() == null) { LOG.warn("OPTION ####" + opt); } final Status status = visit(opt); switch (status) { case EXIT_FAILURE: return -1; case EXIT_SUCCESS: return 0; default: break; } } cmd = createCommand(); final Date startDate = new Date(); LOG.info("Starting JOB at " + startDate + " " + getClass().getName() + " version=" + getVersion() + " " + " built=" + getCompileDate()); LOG.info("Command Line args : " + (cmd.getProgramCommandLine().isEmpty() ? "(EMPTY/NO-ARGS)" : cmd.getProgramCommandLine())); String hostname = ""; try { hostname = InetAddress.getLocalHost().getHostName(); } catch (Exception err) { hostname = "host"; } LOG.info("Executing as " + System.getProperty("user.name") + "@" + hostname + " on " + System.getProperty("os.name") + " " + System.getProperty("os.version") + " " + System.getProperty("os.arch") + "; " + System.getProperty("java.vm.name") + " " + System.getProperty("java.runtime.version")); LOG.debug("initialize " + cmd); final Collection<Throwable> initErrors = cmd.initializeKnime(); if (!(initErrors == null || initErrors.isEmpty())) { for (Throwable err : initErrors) { LOG.error(err); } LOG.fatal("Command initialization failed "); return -1; } LOG.debug("calling " + cmd); final Collection<Throwable> errors = cmd.call(); if (!(errors == null || errors.isEmpty())) { for (Throwable err : errors) { LOG.error(err); } LOG.fatal("Command failed "); return -1; } LOG.debug("success " + cmd); cmd.disposeKnime(); final Date endDate = new Date(); final double elapsedMinutes = (endDate.getTime() - startDate.getTime()) / (1000d * 60d); final String elapsedString = new DecimalFormat("#,##0.00").format(elapsedMinutes); LOG.info("End JOB [" + endDate + "] " + getName() + " done. Elapsed time: " + elapsedString + " minutes."); return 0; } catch (org.apache.commons.cli.UnrecognizedOptionException err) { LOG.fatal("Unknown command (" + err.getOption() + ") , please check your input.", err); return -1; } catch (Throwable err) { LOG.fatal("cannot build command", err); return -1; } finally { if (cmd != null) cmd.cleanup(); } }
From source file:com.zimbra.cs.volume.VolumeCLI.java
private void printOpt(String optStr, int leftPad) { Options options = getOptions();/* w w w . ja v a 2 s. c om*/ Option opt = options.getOption(optStr); StringBuilder buf = new StringBuilder(); buf.append(Strings.repeat(" ", leftPad)); buf.append('-').append(opt.getOpt()).append(",--").append(opt.getLongOpt()); if (opt.hasArg()) { buf.append(" <arg>"); } buf.append(Strings.repeat(" ", 35 - buf.length())); buf.append(opt.getDescription()); System.err.println(buf.toString()); }
From source file:com.bc.fiduceo.post.PostProcessingToolTest.java
@Test public void testOptions() { final Options options = PostProcessingTool.getOptions(); assertEquals(6, options.getOptions().size()); Option o; o = options.getOption("c"); assertNotNull(o);/*from ww w . j a va 2 s .c o m*/ assertEquals("config", o.getLongOpt()); assertEquals("Defines the configuration directory. Defaults to './config'.", o.getDescription()); assertEquals(true, o.hasArg()); assertEquals(false, o.isRequired()); o = options.getOption("i"); assertNotNull(o); assertEquals("input-dir", o.getLongOpt()); assertEquals("Defines the path to the input mmd files directory.", o.getDescription()); assertEquals(true, o.hasArg()); assertEquals(true, o.isRequired()); o = options.getOption("end"); assertNotNull(o); assertEquals("end-date", o.getLongOpt()); assertEquals("Defines the processing end-date, format 'yyyy-DDD'. DDD = Day of year.", o.getDescription()); assertEquals(true, o.hasArg()); assertEquals(true, o.isRequired()); o = options.getOption("h"); assertNotNull(o); assertEquals("help", o.getLongOpt()); assertEquals("Prints the tool usage.", o.getDescription()); assertEquals(false, o.hasArg()); assertEquals(false, o.isRequired()); o = options.getOption("j"); assertNotNull(o); assertEquals("job-config", o.getLongOpt()); assertEquals( "Defines the path to post processing job configuration file. Path is relative to the configuration directory.", o.getDescription()); assertEquals(true, o.hasArg()); assertEquals(true, o.isRequired()); o = options.getOption("start"); assertNotNull(o); assertEquals("start-date", o.getLongOpt()); assertEquals("Defines the processing start-date, format 'yyyy-DDD'. DDD = Day of year.", o.getDescription()); assertEquals(true, o.hasArg()); assertEquals(true, o.isRequired()); }
From source file:edu.harvard.med.screensaver.io.CommandLineApplication.java
public String toString() { StringBuilder s = new StringBuilder(); for (Option option : (Collection<Option>) _options.getOptions()) { if (_cmdLine.hasOption(option.getOpt())) { if (s.length() > 0) { s.append(", "); }//from ww w.j a va 2 s . co m s.append(option.getLongOpt()); if (option.hasArg()) { s.append("=").append(_cmdLine.getOptionValue(option.getOpt())); } } } return "command line options: " + s.toString(); }
From source file:com.github.lindenb.jvarkit.util.command.Command.java
public int instanceMainWithExceptions(final String args[], final List<Throwable> putExceptionsHere) { try {/*from w ww. j av a 2 s. c o m*/ /* cmd line */ final StringBuilder sb = new StringBuilder(); for (String s : args) { if (sb.length() != 0) sb.append(" "); sb.append(s); } this.programCommandLine = sb.toString().replace('\n', ' ').replace('\t', ' ').replace('\"', ' ') .replace('\'', ' '); /* create new options */ final Options options = new Options(); /* get all options and add it to options */ LOG.debug("creating options"); fillOptions(options); /* create a new CLI parser */ LOG.debug("parsing options"); final CommandLineParser parser = new DefaultParser(); this._cliCommand = parser.parse(options, args); this.setInputFiles(this._cliCommand.getArgList()); /* loop over the processed options */ for (final Option opt : this._cliCommand.getOptions()) { if (opt.hasArg() && !opt.hasOptionalArg() && opt.getValue() == null) { LOG.info("WARNING OPTION ####" + opt + " with null value ??"); } final Status status = visit(opt); switch (status) { case EXIT_FAILURE: return -1; case EXIT_SUCCESS: return 0; default: break; } } final Date startDate = new Date(); LOG.info("Starting JOB at " + startDate + " " + getClass().getName() + " version=" + getVersion() + " " + " built=" + getCompileDate()); LOG.info("Command Line args : " + (this.getProgramCommandLine().isEmpty() ? "(EMPTY/NO-ARGS)" : this.getProgramCommandLine())); String hostname = ""; try { hostname = InetAddress.getLocalHost().getHostName(); } catch (Exception err) { hostname = "host"; } LOG.info("Executing as " + System.getProperty("user.name") + "@" + hostname + " on " + System.getProperty("os.name") + " " + System.getProperty("os.version") + " " + System.getProperty("os.arch") + "; " + System.getProperty("java.vm.name") + " " + System.getProperty("java.runtime.version")); LOG.debug("initialize"); final Collection<Throwable> initErrors = this.initializeKnime(); if (!(initErrors == null || initErrors.isEmpty())) { putExceptionsHere.addAll(initErrors); for (Throwable err : initErrors) { LOG.error(err.getMessage()); } LOG.error("Command initialization failed "); return -1; } LOG.debug("calling"); final Collection<Throwable> errors = this.call(); if (!(errors == null || errors.isEmpty())) { putExceptionsHere.addAll(initErrors); for (Throwable err : errors) { LOG.error(err.getMessage()); } LOG.error("Command failed "); return -1; } LOG.debug("success "); this.disposeKnime(); final Date endDate = new Date(); final double elapsedMinutes = (endDate.getTime() - startDate.getTime()) / (1000d * 60d); final String elapsedString = new DecimalFormat("#,##0.00").format(elapsedMinutes); LOG.info("End JOB [" + endDate + "] " + getName() + " done. Elapsed time: " + elapsedString + " minutes."); return 0; } catch (org.apache.commons.cli.UnrecognizedOptionException err) { LOG.error("Unknown command (" + err.getOption() + ") , please check your input.", err); return -1; } catch (Throwable err) { LOG.error("cannot execute command", err); return -1; } finally { this.disposeKnime(); } }
From source file:kieker.tools.util.CLIHelpFormatter.java
@SuppressWarnings("unchecked") @Override//from w ww.j av a2 s . c o m 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; }
From source file:com.spectralogic.ds3cli.Arguments.java
private String[] filterRootArguments() { // Returns only arguments in rootArguments // After the command is instantiated, the full parse will be run against the complete Options list. final List<String> rootArguments = new ArrayList<>(); for (int i = 0; i < this.args.length; i++) { final String token = this.args[i]; // special case: --help can have an arg or not if (matchesOption(COMMAND_HELP, token)) { rootArguments.add(token);/* w w w.jav a 2 s.c om*/ // might or might not have arg if (i + 1 < this.args.length && !this.args[i + 1].startsWith("-")) { rootArguments.add(this.args[++i]); } break; } for (final Option rootArg : rootArgs) { if (matchesOption(rootArg, token)) { // add the option token rootArguments.add(token); if (rootArg.hasArg()) { // add its argument rootArguments.add(this.args[++i]); } } } } // create a String[] of only valid root parse args. return rootArguments.toArray(new String[rootArguments.size()]); }
From source file:com.hablutzel.cmdline.CommandLineApplication.java
/** * This method scans the subclass for annotations * that denote the command line options and arguments, * and configures the systems so that the members that * have been annotated in that way are set up for calling * at command line processing time/*w w w . j ava 2s . c om*/ * */ private final void configure() throws CommandLineException { // Find all the fields in our subclass for (Method method : this.getClass().getDeclaredMethods()) { // If this method is marked with a command line option, then configure // a corresponding commons-cli command line option here if (method.isAnnotationPresent(CommandLineOption.class)) { CommandLineOption commandLineOption = method.getDeclaredAnnotation(CommandLineOption.class); if (commandLineOption != null) { // Get the basic information about the option - the name and description String shortName = commandLineOption.shortForm().equals("") ? null : commandLineOption.shortForm(); String longName = commandLineOption.longForm().equals("") ? null : commandLineOption.longForm(); String description = commandLineOption.usage(); // If both the short and long name are null, then use the field name as the long name if (shortName == null && longName == null) { longName = method.getName(); } // The signature of the method determines what kind of command line // option is allowed. Basically, if the method does not take an argument, // then the option does not take arguments either. In this case, the // method is just called when the option is present. // // If the method does take argument, there are restrictions on the arguments // that are allowed. If there is a single argument, then the method will be // called for each argument supplied to the option. Generally in this case you // want the maximum number of option arguments to be 1, and you are just getting // the value of the argument. On the other hand, if the single argument is either // and array or a List<>, then the arguments will be passed in as an argument // or list respectively. // // Methods with more than 1 argument are not allowed. Methods with return types // other than boolean are not allowed. Methods that throw an exception other than // org.apache.commons.cli.CommandLineException are not allowed, // // If the method returns a boolean, and calling that method returns FALSE, then the // command line main function will not be called. // // The class of the argument has to be convertable using common-beanutils // conversion facilities CommandLineMethodHelper helper = getHelperForCommandOption(method, commandLineOption); // Now create and configure an option based on what the method is capable of handling // and the command line option parameters boolean allowsArguments = helper.methodType != MethodType.Boolean; Option option = new Option(shortName, longName, allowsArguments, description); // Configure it option.setRequired(commandLineOption.required()); if (option.hasArg()) { option.setType(helper.elementType); option.setArgs(commandLineOption.maximumArgumentCount()); option.setValueSeparator(commandLineOption.argumentSeparator()); option.setOptionalArg(commandLineOption.optionalArgument()); } // Remember it, both in the commons-cli options set and // in our list of elements for later post-processing options.addOption(option); optionHelperMap.put(option, helper); } // This was not a command line option method - is it the main command line method? } else if (method.isAnnotationPresent(CommandLineMain.class)) { // Make sure we only have one if (mainHelper != null) { throw new CommandLineException("Cannot have two main methods specified"); } else { mainHelper = getHelperForCommandLineMain(method); } } } }
From source file:com.cloudbees.sdk.commands.Command.java
protected boolean parseCommandLine() throws Exception { boolean ok = true; // parse the command line arguments line = getParser().parse(getOptions(true), getArgs()); for (Option option : line.getOptions()) { // System.out.println("Option: " + option); String str = option.getLongOpt(); if (str == null) str = option.getOpt();/* w ww . j a va2 s . c o m*/ str = str.replace("-", ""); if (option.hasArg()) { Class[] types = { String.class }; Method method = getMethod(str, "", types); if (method == null) { method = getMethod(str, "Option", types); } method.invoke(this, option.getValue()); } else { Class[] types = { Boolean.class }; Method method = getMethod(str, "", types); if (method == null) { method = getMethod(str, "Option", types); } method.invoke(this, Boolean.TRUE); } } return ok; }