List of usage examples for org.apache.commons.cli Option getLongOpt
public String getLongOpt()
From source file:com.zimbra.cs.volume.VolumeCLI.java
private void printOpt(String optStr, int leftPad) { Options options = getOptions();/*from www . j a v a2s .c o m*/ 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:ch.cyberduck.cli.TerminalOptionsInputValidator.java
public boolean validate(final CommandLine input) { for (Option o : input.getOptions()) { if (Option.UNINITIALIZED == o.getArgs()) { continue; }// w ww . j a va 2 s .c o m if (o.hasOptionalArg()) { continue; } if (o.getArgs() != o.getValuesList().size()) { console.printf("Missing argument for option %s%n", o.getLongOpt()); return false; } } final TerminalAction action = TerminalActionFinder.get(input); if (null == action) { console.printf("%s%n", "Missing argument"); return false; } if (input.hasOption(TerminalOptionsBuilder.Params.existing.name())) { final String arg = input.getOptionValue(TerminalOptionsBuilder.Params.existing.name()); if (null == TransferAction.forName(arg)) { final Set<TransferAction> actions = new HashSet<TransferAction>( TransferAction.forTransfer(Transfer.Type.download)); actions.add(TransferAction.cancel); console.printf("Invalid argument '%s' for option %s. Must be one of %s%n", arg, TerminalOptionsBuilder.Params.existing.name(), Arrays.toString(actions.toArray())); return false; } switch (action) { case download: if (!validate(arg, Transfer.Type.download)) { return false; } break; case upload: if (!validate(arg, Transfer.Type.upload)) { return false; } break; case synchronize: if (!validate(arg, Transfer.Type.sync)) { return false; } break; case copy: if (!validate(arg, Transfer.Type.copy)) { return false; } break; } } // Validate arguments switch (action) { case list: case download: if (!validate(input.getOptionValue(action.name()))) { return false; } break; case upload: case copy: case synchronize: if (!validate(input.getOptionValue(action.name()))) { return false; } break; } return true; }
From source file:com.emc.vipr.sync.ViPRSync.java
/** * Loads and configures plugins based on command line options. *///from ww w.j ava 2 s. co m protected static ViPRSync cliBootstrap(String[] args) throws ParseException { ViPRSync sync = new ViPRSync(); List<SyncPlugin> plugins = new ArrayList<>(); CommandLine line = gnuParser.parse(mainOptions(), args, true); // find a plugin that can read from the source String sourceUri = line.getOptionValue(SOURCE_OPTION); if (sourceUri != null) { for (SyncSource source : sourceLoader) { if (source.canHandleSource(sourceUri)) { source.setSourceUri(sourceUri); sync.setSource(source); plugins.add(source); LogMF.info(l4j, "source: {0} ({1})", source.getName(), source.getClass()); break; } } } String targetUri = line.getOptionValue(TARGET_OPTION); // find a plugin that can write to the target if (targetUri != null) { for (SyncTarget target : targetLoader) { if (target.canHandleTarget(targetUri)) { target.setTargetUri(targetUri); sync.setTarget(target); plugins.add(target); LogMF.info(l4j, "target: {0} ({1})", target.getName(), target.getClass()); break; } } } // load filters List<SyncFilter> filters = new ArrayList<>(); String filtersParameter = line.getOptionValue(FILTERS_OPTION); if (filtersParameter != null) { for (String filterName : filtersParameter.split(",")) { for (SyncFilter filter : filterLoader) { if (filter.getActivationName().equals(filterName)) { filters.add(filter); plugins.add(filter); LogMF.info(l4j, "filter: {0} ({1})", filter.getName(), filter.getClass()); break; } } } sync.setFilters(filters); } // configure thread counts if (line.hasOption(QUERY_THREADS_OPTION)) sync.setQueryThreadCount(Integer.parseInt(line.getOptionValue(QUERY_THREADS_OPTION))); if (line.hasOption(SYNC_THREADS_OPTION)) sync.setSyncThreadCount(Integer.parseInt(line.getOptionValue(SYNC_THREADS_OPTION))); // configure timings display if (line.hasOption(TIMINGS_OPTION)) sync.setTimingsEnabled(true); if (line.hasOption(TIMING_WINDOW_OPTION)) { sync.setTimingWindow(Integer.parseInt(line.getOptionValue(TIMING_WINDOW_OPTION))); } // configure recursive behavior if (line.hasOption(NON_RECURSIVE_OPTION)) sync.setRecursive(false); // configure failed object tracking if (line.hasOption(FORGET_FAILED_OPTION)) sync.setRememberFailed(false); // configure whether to delete source objects after they are successfully synced if (line.hasOption(DELETE_SOURCE_OPTION)) sync.setDeleteSource(true); // logging options if (line.hasOption(DEBUG_OPTION)) { sync.setLogLevel(DEBUG_OPTION); } if (line.hasOption(VERBOSE_OPTION)) { sync.setLogLevel(VERBOSE_OPTION); } if (line.hasOption(QUIET_OPTION)) { sync.setLogLevel(QUIET_OPTION); } if (line.hasOption(SILENT_OPTION)) { sync.setLogLevel(SILENT_OPTION); } // Quick check for no-args if (sync.getSource() == null) { throw new ConfigurationException("source must be specified"); } if (sync.getTarget() == null) { throw new ConfigurationException("target must be specified"); } // Let the plugins parse their own options // 1. add common options and all the options from the plugins Options options = mainOptions(); for (Object o : CommonOptions.getOptions().getOptions()) { options.addOption((Option) o); } for (SyncPlugin plugin : plugins) { for (Object o : plugin.getCustomOptions().getOptions()) { Option option = (Option) o; if (options.hasOption(option.getOpt())) { System.err.println( "WARNING: The option " + option.getOpt() + " is being used by more than one plugin"); } options.addOption(option); } } // 2. re-parse the command line based on these options line = gnuParser.parse(options, args); if (l4j.isDebugEnabled()) { for (Option option : line.getOptions()) { if (option.hasArg()) LogMF.debug(l4j, "parsed option {0}: {1}", option.getLongOpt(), line.getOptionValue(option.getLongOpt())); else LogMF.debug(l4j, "parsed option {0}", option.getLongOpt()); } } // 3. pass the result to each plugin separately for (SyncPlugin plugin : plugins) { plugin.parseOptions(line); } return sync; }
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(", "); }/* w ww . j a v a 2s . com*/ s.append(option.getLongOpt()); if (option.hasArg()) { s.append("=").append(_cmdLine.getOptionValue(option.getOpt())); } } } return "command line options: " + s.toString(); }
From source file:com.buildml.main.BMLAdminMain.java
/** * Display a set of options (as defined by the Options class). This methods is used * in displaying the help text./* www . j a v a 2 s .c om*/ * @param opts A set of command line options, as defined by the Options class. */ @SuppressWarnings("unchecked") private void displayOptions(Options opts) { /* obtain a list of all the options */ Collection<Option> optList = opts.getOptions(); /* if there are no options for this command ... */ if (optList.size() == 0) { System.err.println(" No options available."); } /* * Else, we have options to display. Show them in a nicely tabulated * format, with the short option name (e.g. -p) and the long option name * (--show-pkgs) first, followed by a text description of the option. */ else { for (Iterator<Option> iterator = optList.iterator(); iterator.hasNext();) { Option thisOpt = iterator.next(); String shortOpt = thisOpt.getOpt(); String longOpt = thisOpt.getLongOpt(); String line = " "; if (shortOpt != null) { line += "-" + shortOpt; } else { line += " "; } if (shortOpt != null && longOpt != null) { line += " | "; } else { line += " "; } if (longOpt != null) { line += "--" + thisOpt.getLongOpt(); } if (thisOpt.hasArg()) { line += " <" + thisOpt.getArgName() + ">"; } formattedDisplayLine(line, thisOpt.getDescription()); } } }
From source file:com.google.api.codegen.GeneratorMain.java
public static void discoGapicMain(String[] args) throws Exception { Options options = new Options(); options.addOption("h", "help", false, "show usage"); // TODO make required after artman passes this in options.addOption(LANGUAGE_NONREQUIRED_OPTION); options.addOption(DISCOVERY_DOC_OPTION); // TODO add this option back // options.addOption(SERVICE_YAML_OPTION); options.addOption(GAPIC_YAML_OPTION); options.addOption(PACKAGE_YAML2_OPTION); options.addOption(OUTPUT_OPTION);/*from ww w . j a v a 2s. c o m*/ Option enabledArtifactsOption = Option.builder().longOpt("enabled_artifacts") .desc("Optional. Artifacts enabled for the generator. " + "Currently supports 'surface' and 'test'.") .hasArg().argName("ENABLED_ARTIFACTS").required(false).build(); options.addOption(enabledArtifactsOption); CommandLine cl = (new DefaultParser()).parse(options, args); if (cl.hasOption("help")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("DiscoGapicGeneratorTool", options); } ToolOptions toolOptions = ToolOptions.create(); toolOptions.set(DiscoGapicGeneratorApp.LANGUAGE, cl.getOptionValue(LANGUAGE_NONREQUIRED_OPTION.getLongOpt())); toolOptions.set(DiscoGapicGeneratorApp.DISCOVERY_DOC, cl.getOptionValue(DISCOVERY_DOC_OPTION.getLongOpt())); toolOptions.set(GapicGeneratorApp.OUTPUT_FILE, cl.getOptionValue(OUTPUT_OPTION.getLongOpt(), "")); toolOptions.set(GapicGeneratorApp.GENERATOR_CONFIG_FILES, Lists.newArrayList(cl.getOptionValues(GAPIC_YAML_OPTION.getLongOpt()))); toolOptions.set(GapicGeneratorApp.PACKAGE_CONFIG2_FILE, cl.getOptionValue(PACKAGE_YAML2_OPTION.getLongOpt())); if (cl.getOptionValues(enabledArtifactsOption.getLongOpt()) != null) { toolOptions.set(GapicGeneratorApp.ENABLED_ARTIFACTS, Lists.newArrayList(cl.getOptionValues(enabledArtifactsOption.getLongOpt()))); } DiscoGapicGeneratorApp codeGen = new DiscoGapicGeneratorApp(toolOptions); int exitCode = codeGen.run(); System.exit(exitCode); }
From source file:lcmc.ArgumentParser.java
public void parseClusterOptionsAndCreateClusterButton(final CommandLine cmd) throws ParseException { String clusterName = null;/*from ww w.j a v a 2 s.c o m*/ List<HostOptions> hostsOptions = null; final Map<String, List<HostOptions>> clusters = new LinkedHashMap<String, List<HostOptions>>(); for (final Option option : cmd.getOptions()) { final String op = option.getLongOpt(); if (CLUSTER_OP.equals(op)) { clusterName = option.getValue(); if (clusterName == null) { throw new ParseException("could not parse " + CLUSTER_OP + " option"); } clusters.put(clusterName, new ArrayList<HostOptions>()); } else if (HOST_OP.equals(op)) { final String[] hostNames = option.getValues(); if (clusterName == null) { clusterName = "default"; clusters.put(clusterName, new ArrayList<HostOptions>()); } if (hostNames == null) { throw new ParseException("could not parse " + HOST_OP + " option"); } hostsOptions = new ArrayList<HostOptions>(); for (final String hostNameEntered : hostNames) { final String hostName; String port = null; if (hostNameEntered.indexOf(':') > 0) { final String[] he = hostNameEntered.split(":"); hostName = he[0]; port = he[1]; if (port != null && port.isEmpty() || !lcmc.common.domain.util.Tools.isNumber(port)) { throw new ParseException("could not parse " + HOST_OP + " option"); } } else { hostName = hostNameEntered; } final HostOptions ho = new HostOptions(hostName); if (port != null) { ho.setPort(port); } hostsOptions.add(ho); clusters.get(clusterName).add(ho); } } else if (SUDO_OP.equals(op)) { if (hostsOptions == null) { throw new ParseException(SUDO_OP + " must be defined after " + HOST_OP); } for (final HostOptions ho : hostsOptions) { ho.setUseSudo(true); } } else if (USER_OP.equals(op)) { if (hostsOptions == null) { throw new ParseException(USER_OP + " must be defined after " + HOST_OP); } final String userName = option.getValue(); if (userName == null) { throw new ParseException("could not parse " + USER_OP + " option"); } for (final HostOptions ho : hostsOptions) { ho.setLoginUser(userName); } } else if (PORT_OP.equals(op)) { if (hostsOptions == null) { throw new ParseException(PORT_OP + " must be defined after " + HOST_OP); } final String port = option.getValue(); if (port == null) { throw new ParseException("could not parse " + PORT_OP + " option"); } for (final HostOptions ho : hostsOptions) { ho.setPort(port); } } else if (PCMKTEST_OP.equals(op)) { final String index = option.getValue(); if (index != null && !index.isEmpty()) { application.setAutoTest(new Test(StartTests.Type.PCMK, index.charAt(0))); } } else if (DRBDTEST_OP.equals(op)) { final String index = option.getValue(); if (index != null && !index.isEmpty()) { application.setAutoTest(new Test(StartTests.Type.DRBD, index.charAt(0))); } } else if (VMTEST_OP.equals(op)) { final String index = option.getValue(); if (index != null && !index.isEmpty()) { application.setAutoTest(new Test(StartTests.Type.VM, index.charAt(0))); } } else if (GUITEST_OP.equals(op)) { final String index = option.getValue(); if (index != null && !index.isEmpty()) { application.setAutoTest(new Test(StartTests.Type.GUI, index.charAt(0))); } } } for (final Map.Entry<String, List<HostOptions>> clusterEntry : clusters.entrySet()) { final List<HostOptions> hostOptions = clusterEntry.getValue(); if (hostOptions.size() < 1 || (hostOptions.size() == 1 && !application.isOneHostCluster())) { throw new ParseException("not enough hosts for cluster: " + clusterEntry.getKey()); } } final String failedHost = setUserConfigFromOptions(clusters); if (failedHost != null) { LOG.appWarning("parseClusterOptions: could not resolve host \"" + failedHost + "\" skipping"); } }
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();//from w w w . java 2s .c om 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; }
From source file:net.sf.clichart.main.FixedHelpFormatter.java
protected StringBuffer renderOptions(StringBuffer sb, int width, Options options, int leftPad, int descPad) { final String lpad = createPadding(leftPad); final String dpad = createPadding(descPad); //first create list containing only <lpad>-a,--aaa where -a is opt and --aaa is //long opt; in parallel look for the longest opt string //this list will be then used to sort options ascending int max = 0;/*from ww w. j a v a 2 s . c o m*/ StringBuffer optBuf; List prefixList = new ArrayList(); Option option; //List optList = options.helpOptions(); Collection optionsCollection = options.getOptions(); List optList = new ArrayList(optionsCollection); Collections.sort(optList, new StringBufferComparator()); for (Iterator i = optList.iterator(); i.hasNext();) { option = (Option) i.next(); optBuf = new StringBuffer(8); if (option.getOpt().equals(" ")) { optBuf.append(lpad).append(" " + defaultLongOptPrefix).append(option.getLongOpt()); } else { optBuf.append(lpad).append(defaultOptPrefix).append(option.getOpt()); if (option.hasLongOpt()) { optBuf.append(',').append(defaultLongOptPrefix).append(option.getLongOpt()); } } if (option.hasArg()) { if (option.hasArgName()) { optBuf.append(" <").append(option.getArgName()).append('>'); } else { optBuf.append(' '); } } prefixList.add(optBuf); max = optBuf.length() > max ? optBuf.length() : max; } int x = 0; for (Iterator i = optList.iterator(); i.hasNext();) { option = (Option) i.next(); optBuf = new StringBuffer(prefixList.get(x++).toString()); if (optBuf.length() < max) { optBuf.append(createPadding(max - optBuf.length())); } optBuf.append(dpad); int nextLineTabStop = max + descPad; renderWrappedText(sb, width, nextLineTabStop, optBuf.append(option.getDescription()).toString()); if (i.hasNext()) { sb.append(defaultNewLine); } } return sb; }
From source file:com.bc.fiduceo.matchup.MatchupToolTest.java
@Test public void testGetOptions() { final Options options = MatchupTool.getOptions(); assertNotNull(options);//from w ww . jav a 2s . c o m final Option helpOption = options.getOption("h"); assertNotNull(helpOption); assertEquals("h", helpOption.getOpt()); assertEquals("help", helpOption.getLongOpt()); assertEquals("Prints the tool usage.", helpOption.getDescription()); assertFalse(helpOption.hasArg()); final Option configOption = options.getOption("config"); assertNotNull(configOption); assertEquals("c", configOption.getOpt()); assertEquals("config", configOption.getLongOpt()); assertEquals("Defines the configuration directory. Defaults to './config'.", configOption.getDescription()); assertTrue(configOption.hasArg()); final Option startOption = options.getOption("start"); assertNotNull(startOption); assertEquals("start", startOption.getOpt()); assertEquals("start-date", startOption.getLongOpt()); assertEquals("Defines the processing start-date, format 'yyyy-DDD'", startOption.getDescription()); assertTrue(startOption.hasArg()); final Option endOption = options.getOption("end"); assertNotNull(endOption); assertEquals("end", endOption.getOpt()); assertEquals("end-date", endOption.getLongOpt()); assertEquals("Defines the processing end-date, format 'yyyy-DDD'", endOption.getDescription()); assertTrue(endOption.hasArg()); final Option useCaseOption = options.getOption("usecase"); assertNotNull(useCaseOption); assertEquals("u", useCaseOption.getOpt()); assertEquals("usecase", useCaseOption.getLongOpt()); assertEquals( "Defines the path to the use-case configuration file. Path is relative to the configuration directory.", useCaseOption.getDescription()); assertTrue(useCaseOption.hasArg()); }