List of usage examples for org.apache.commons.cli Option getOpt
public String getOpt()
From source file:com.hablutzel.cmdline.CommandLineApplication.java
/** * Method for running the command line application. * * @param args The arguments passed into main() * @throws CommandLineException//from w w w .j av a 2s . co m */ public void parseAndRun(String args[]) throws CommandLineException { // Configure our environment configure(); // Make sure there is a main helper if (mainHelper == null) { throw new CommandLineException("You must specify the main method with @CommandLineMain"); } CommandLine line = null; CommandLineParser parser = null; try { // Parse the command line parser = new DefaultParser(); line = parser.parse(options, args); } catch (ParseException e) { throw new CommandLineException("Unable to parse command line", e); } finally { parser = null; } // Assume we're continuing boolean runMain = true; // Loop through all our known options for (Map.Entry<Option, CommandLineMethodHelper> entry : optionHelperMap.entrySet()) { // See if this option was specified Option option = entry.getKey(); CommandLineMethodHelper helper = entry.getValue(); boolean present = option.getOpt() == null || option.getOpt().equals("") ? line.hasOption(option.getLongOpt()) : line.hasOption(option.getOpt()); if (present) { // The user specified this option. Now we have to handle the // values, if it has any if (option.hasArg()) { String[] arguments = option.getOpt() == null || option.getOpt().equals("") ? line.getOptionValues(option.getLongOpt()) : line.getOptionValues(option.getOpt()); runMain = helper.invokeMethod(this, arguments) && runMain; } else { runMain = helper.invokeMethod(this, new String[] {}) && runMain; } } } // Now handle all the extra arguments. In order to clean up memory, // we get rid of the structures that we needed in order to parse if (runMain) { // Get a reference to the arguments String[] arguments = line.getArgs(); // Clean up the parsing variables line = null; optionHelperMap = null; // Now call the main method. This means we have to keep // the main helper around, but that's small mainHelper.invokeMethod(this, arguments); } }
From source file:edu.harvard.med.screensaver.io.CommandLineApplication.java
public void addCommandLineOption(Option option, Object defaultValue) { _options.addOption(option);//from www . j av a 2 s . co m if (option.hasArgs()) { if (defaultValue instanceof List) { throw new IllegalArgumentException("when option takes multiple args, defaultValue must be a List"); } } _option2DefaultValue.put(option.getOpt(), defaultValue); }
From source file:com.ibm.crail.storage.rdma.RdmaStorageTier.java
public void init(CrailConfiguration conf, String[] args) throws Exception { if (args != null) { Option interfaceOption = Option.builder("i").desc("interface to start server on").hasArg().build(); Option portOption = Option.builder("p").desc("port to start server on").hasArg().build(); Options options = new Options(); options.addOption(interfaceOption); options.addOption(portOption);//from w w w. ja va2 s . c o m CommandLineParser parser = new DefaultParser(); try { CommandLine line = parser.parse(options, Arrays.copyOfRange(args, 0, args.length)); if (line.hasOption(interfaceOption.getOpt())) { String ifname = line.getOptionValue(interfaceOption.getOpt()); LOG.info("using custom interface " + ifname); conf.set(RdmaConstants.STORAGE_RDMA_INTERFACE_KEY, ifname); } if (line.hasOption(portOption.getOpt())) { String port = line.getOptionValue(portOption.getOpt()); LOG.info("using custom port " + port); conf.set(RdmaConstants.STORAGE_RDMA_PORT_KEY, port); } } catch (ParseException e) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("RDMA storage tier", options); System.exit(-1); } } RdmaConstants.updateConstants(conf); RdmaConstants.verify(); }
From source file:com.bc.fiduceo.matchup.MatchupToolTest.java
@Test public void testGetOptions() { final Options options = MatchupTool.getOptions(); assertNotNull(options);/*w w w . ja va 2 s . 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()); }
From source file:com.tito.easyyarn.appmaster.ApplicationMaster.java
/** * Parse command line options/* ww w . j a va2 s . c o m*/ * * @param args * Command line args * @return Whether init successful and run should be invoked * @throws ParseException * @throws IOException */ public boolean initAll(CommandLine cliParser) throws ParseException, IOException { if (cliParser.hasOption("help")) { printUsage(getOptions()); return false; } if (cliParser.hasOption("debug")) { dumpOutDebugInfo(); } if (!cliParser.hasOption("jar")) { throw new IllegalArgumentException("Missing Jar file for workers"); } this.jarPath = cliParser.getOptionValue("jar"); Map<String, String> envs = System.getenv(); if (!envs.containsKey(Environment.CONTAINER_ID.name())) { if (cliParser.hasOption("app_attempt_id")) { String appIdStr = cliParser.getOptionValue("app_attempt_id", ""); appAttemptID = ConverterUtils.toApplicationAttemptId(appIdStr); } else { throw new IllegalArgumentException("Application Attempt Id not set in the environment"); } } else { ContainerId containerId = ConverterUtils.toContainerId(envs.get(Environment.CONTAINER_ID.name())); appAttemptID = containerId.getApplicationAttemptId(); } if (!envs.containsKey(ApplicationConstants.APP_SUBMIT_TIME_ENV)) { throw new RuntimeException(ApplicationConstants.APP_SUBMIT_TIME_ENV + " not set in the environment"); } if (!envs.containsKey(Environment.NM_HOST.name())) { throw new RuntimeException(Environment.NM_HOST.name() + " not set in the environment"); } if (!envs.containsKey(Environment.NM_HTTP_PORT.name())) { throw new RuntimeException(Environment.NM_HTTP_PORT + " not set in the environment"); } if (!envs.containsKey(Environment.NM_PORT.name())) { throw new RuntimeException(Environment.NM_PORT.name() + " not set in the environment"); } if (envs.containsKey(YarnConstants.APP_JAR)) { jarPath = envs.get(YarnConstants.APP_JAR); if (envs.containsKey(YarnConstants.APP_JAR_TIMESTAMP)) { appJarTimestamp = Long.valueOf(envs.get(YarnConstants.APP_JAR_TIMESTAMP)); } if (envs.containsKey(YarnConstants.APP_JAR_LENGTH)) { appJarPathLen = Long.valueOf(envs.get(YarnConstants.APP_JAR_LENGTH)); } if (!jarPath.isEmpty() && (appJarTimestamp <= 0 || appJarPathLen <= 0)) { LOG.error("Illegal values in env for jar path" + ", path=" + jarPath + ", len=" + appJarPathLen + ", timestamp=" + appJarTimestamp); throw new IllegalArgumentException("Illegal values in env for jar path"); } } LOG.info("Application master for app" + ", appId=" + appAttemptID.getApplicationId().getId() + ", clustertimestamp=" + appAttemptID.getApplicationId().getClusterTimestamp() + ", attemptId=" + appAttemptID.getAttemptId()); timeLinePublisher = new TimeLinePublisher(conf); if (!init(cliParser)) { return false; } // save passed arguments for (Option op : cliParser.getOptions()) { passedArguments.put(op.getOpt(), cliParser.getOptionValue(op.getOpt())); } return true; }
From source file:bdsup2sub.cli.CommandLineParser.java
public void printHelp() { HelpFormatter formatter = new HelpFormatter(); formatter.setOptionComparator(new Comparator() { @Override//ww w .j a v a 2 s . com public int compare(Object o1, Object o2) { Option opt1 = (Option) o1; Option opt2 = (Option) o2; int opt1Index = OPTION_ORDER.indexOf(opt1.getOpt()); int opt2Index = OPTION_ORDER.indexOf(opt2.getOpt()); return (int) Math.signum(opt1Index - opt2Index); } }); formatter.setWidth(79); String command = System.getProperty("wrapper") == null ? "java -jar BDSup2Sub" : "bdsup2sub"; formatter.printHelp(command + " [options] -o <output> <input>", options); }
From source file:com.ibm.crail.storage.nvmf.NvmfStorageTier.java
public void init(CrailConfiguration crailConfiguration, String[] args) throws IOException { if (initialized) { throw new IOException("NvmfStorageTier already initialized"); }//from w ww .j a va2 s. c o m initialized = true; NvmfStorageConstants.updateConstants(crailConfiguration); if (args != null) { Options options = new Options(); Option bindIp = Option.builder("a").desc("ip address to bind to").hasArg().build(); Option port = Option.builder("p").desc("port to bind to").hasArg().type(Number.class).build(); Option pcieAddress = Option.builder("s").desc("PCIe address of NVMe device").hasArg().build(); options.addOption(bindIp); options.addOption(port); options.addOption(pcieAddress); CommandLineParser parser = new DefaultParser(); HelpFormatter formatter = new HelpFormatter(); CommandLine line = null; try { line = parser.parse(options, Arrays.copyOfRange(args, 0, args.length)); if (line.hasOption(port.getOpt())) { NvmfStorageConstants.PORT = ((Number) line.getParsedOptionValue(port.getOpt())).intValue(); } } catch (ParseException e) { System.err.println(e.getMessage()); formatter.printHelp("NVMe storage tier", options); System.exit(-1); } if (line.hasOption(bindIp.getOpt())) { NvmfStorageConstants.IP_ADDR = InetAddress.getByName(line.getOptionValue(bindIp.getOpt())); } if (line.hasOption(pcieAddress.getOpt())) { NvmfStorageConstants.PCIE_ADDR = line.getOptionValue(pcieAddress.getOpt()); } } NvmfStorageConstants.verify(); }
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(); str = str.replace("-", ""); if (option.hasArg()) { Class[] types = { String.class }; Method method = getMethod(str, "", types); if (method == null) { method = getMethod(str, "Option", types); }//from w w w .j a va 2 s . co m 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:com.inetpsa.seed.plugin.CmdMojoDelegate.java
protected Command createCommand(CommandRegistry commandRegistry, String qualifiedName, String[] args) { if (Strings.isNullOrEmpty(qualifiedName)) { throw new IllegalArgumentException("No command named " + qualifiedName); }/*from w w w . j av a2 s . c om*/ String commandScope; String commandName; if (qualifiedName.contains(":")) { String[] splitName = qualifiedName.split(":"); commandScope = splitName[0].trim(); commandName = splitName[1].trim(); } else { commandScope = null; commandName = qualifiedName.trim(); } // Build CLI options Options options = new Options(); for (org.seedstack.seed.core.spi.command.Option option : commandRegistry.getOptionsInfo(commandScope, commandName)) { options.addOption(option.name(), option.longName(), option.hasArgument(), option.description()); } // Parse the command options CommandLine cmd; try { cmd = commandLineParser.parse(options, args); } catch (ParseException e) { throw new IllegalArgumentException("Syntax error in arguments", e); } Map<String, String> optionValues = new HashMap<String, String>(); for (Option option : cmd.getOptions()) { optionValues.put(option.getOpt(), option.getValue()); } return commandRegistry.createCommand(commandScope, commandName, cmd.getArgList(), optionValues); }
From source file:de.tudarmstadt.ukp.dariah.pipeline.RunPipeline.java
@SuppressWarnings("static-access") private static boolean parseArgs(String[] args) throws ParseException { Options options = new Options(); options.addOption("help", false, "print this message"); Option lang = OptionBuilder.withArgName("lang").hasArg() .withDescription("Language code for input file (default: " + optLanguage + ")").create("language"); options.addOption(lang);/*from w w w.j a va 2 s. c om*/ Option input = OptionBuilder.withArgName("path").hasArg().withDescription("Input path").create("input"); options.addOption(input); Option output = OptionBuilder.withArgName("path").hasArg().withDescription("Output path").create("output"); options.addOption(output); Option configFile = OptionBuilder.withArgName("path").hasArg().withDescription("Config file") .create("config"); options.addOption(configFile); Option reader = OptionBuilder.withArgName("reader").hasArg().withDescription("Either text (default) or xml") .create("reader"); options.addOption(reader); Option resume = OptionBuilder.withDescription("Already processed files will be skipped").create("resume"); options.addOption(resume); CommandLineParser argParser = new BasicParser(); CommandLine cmd = argParser.parse(options, args); if (cmd.hasOption("help")) { // automatically generate the help statement HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("pipeline.jar", options); return false; } if (cmd.hasOption(input.getOpt())) { optInput = cmd.getOptionValue(input.getOpt()); } else { System.out.println("Input option required"); return false; } if (cmd.hasOption(output.getOpt())) { optOutput = cmd.getOptionValue(output.getOpt()); } else { System.out.println("Output option required"); return false; } if (cmd.hasOption(lang.getOpt())) { optLanguage = cmd.getOptionValue(lang.getOpt()); } if (cmd.hasOption(reader.getOpt())) { String readerParam = cmd.getOptionValue(reader.getOpt()).toLowerCase(); if (readerParam.equals("text") || readerParam.equals("txt") || readerParam.equals("textreader") || readerParam.equals("txtreader")) { optReader = ReaderType.Text; } else if (readerParam.equals("xml") || readerParam.equals("xmlreader")) { optReader = ReaderType.XML; } else { System.out.println("The reader parameter is unknown: " + optReader); System.out.println("Valid argument values are: text, xml"); return false; } } if (cmd.hasOption(resume.getOpt())) { optResume = true; } return true; }