List of usage examples for org.apache.commons.cli Option getOpt
public String getOpt()
From source file:org.kyupi.apps.App.java
protected void printOptionHelp() { for (Object oo : options.getOptions()) { Option op = (Option) oo; log.info(" -" + op.getOpt() + "\t" + op.getDescription()); }//from www . j av a 2 s . co m }
From source file:org.ldaptive.cli.AbstractCli.java
/** * Reads the options from the supplied command line and returns a properties * containing those options./*from w w w. j a v a2s . com*/ * * @param domain to place property names in * @param line command line * * @return properties for each option and value */ protected Properties getPropertiesFromOptions(final String domain, final CommandLine line) { final Properties props = new Properties(); for (Option o : line.getOptions()) { if (o.hasArg()) { // if provider property, split the value // else add the domain to the ldaptive properties if (o.getOpt().equals(OPT_PROVIDER_PROPERTIES)) { final String[] s = o.getValue().split("="); props.setProperty(s[0], s[1]); } else { props.setProperty(domain + o.getOpt(), o.getValue()); } } } return props; }
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 w w .j a v a 2 s . c o m*/ @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; } }
From source file:org.ldp4j.tutorial.client.ContactsShell.java
protected void debug(String command, CommandLine commandLine) { this.console.message("- Command: ").metadata(command).message("%n"); for (Option opt : options.getOptions()) { if (commandLine.hasOption(opt.getOpt())) { if (!opt.hasArg()) { this.console.metadata(" + %s%n", opt.getOpt()); } else { if (!opt.hasArgs()) { this.console.metadata(" + %s: ", opt.getOpt()).data("%s%n", commandLine.getOptionValue(opt.getOpt())); } else { this.console.metadata(" + %s: ", opt.getOpt()).data("%s%n", Arrays.toString(commandLine.getOptionValues(opt.getOpt()))); }/*from w w w. j a va 2 s. c o m*/ } } } List<String> argList = commandLine.getArgList(); if (!argList.isEmpty()) { this.console.metadata(" + Arguments:%n"); for (String arg : argList) { this.console.metadata(" * ").data("%s%n", arg); } } }
From source file:org.lilyproject.cli.OptionUtil.java
public static int getIntOption(CommandLine cmd, Option option, int defaultValue) { String opt = option.getOpt() == null ? option.getLongOpt() : option.getOpt(); if (cmd.hasOption(opt)) { try {/*from ww w . j av a2 s.c o m*/ return Integer.parseInt(cmd.getOptionValue(opt)); } catch (NumberFormatException e) { throw new CliException( "Invalid value for option " + option.getLongOpt() + ": " + cmd.getOptionValue(opt)); } } return defaultValue; }
From source file:org.lilyproject.cli.OptionUtil.java
public static long getLongOption(CommandLine cmd, Option option, long defaultValue) { String opt = option.getOpt() == null ? option.getLongOpt() : option.getOpt(); if (cmd.hasOption(opt)) { try {//from w w w . j a v a 2s. com return Long.parseLong(cmd.getOptionValue(opt)); } catch (NumberFormatException e) { throw new CliException( "Invalid value for option " + option.getLongOpt() + ": " + cmd.getOptionValue(opt)); } } return defaultValue; }
From source file:org.lilyproject.cli.OptionUtil.java
public static String getStringOption(CommandLine cmd, Option option, String defaultValue) { String opt = option.getOpt() == null ? option.getLongOpt() : option.getOpt(); if (cmd.hasOption(opt)) { return cmd.getOptionValue(opt); } else {/*from ww w . j ava2s . c om*/ return defaultValue; } }
From source file:org.lilyproject.cli.OptionUtil.java
public static String getStringOption(CommandLine cmd, Option option) { String opt = option.getOpt() == null ? option.getLongOpt() : option.getOpt(); if (cmd.hasOption(opt)) { return cmd.getOptionValue(opt); } else {/*w ww . j a v a 2 s . c o m*/ throw new CliException("Missing value for option " + opt); } }
From source file:org.lilyproject.runtime.cli.LilyRuntimeCli.java
private void run(String[] args) throws Exception { // Forward JDK logging to SLF4J LogManager.getLogManager().reset(); LogManager.getLogManager().getLogger("").addHandler(new SLF4JBridgeHandler()); LogManager.getLogManager().getLogger("").setLevel(Level.ALL); Options cliOptions = new Options(); Option confDirsOption = OptionBuilder.withArgName("confdir").hasArg() .withDescription("The Lily runtime configuration directory. Can be multiple paths separated by " + File.pathSeparator) .withLongOpt("confdir").create('c'); cliOptions.addOption(confDirsOption); Option repositoryLocationOption = OptionBuilder.withArgName("maven-repo-path").hasArg() .withDescription(//w w w. j av a 2 s . com "Location of the (Maven-style) artifact repository. Use comma-separated entries to " + "specify multiple locations which will be searched in the order as specified.") .withLongOpt("repository").create('r'); cliOptions.addOption(repositoryLocationOption); Option disabledModulesOption = OptionBuilder.withArgName("mod-id1,mod-id2,...").hasArg() .withDescription("Comma-separated list of modules that should be disabled.") .withLongOpt("disable-modules").create('i'); cliOptions.addOption(disabledModulesOption); Option disableClassSharingOption = OptionBuilder .withDescription("Disable optional sharing of classes between modules") .withLongOpt("disable-class-sharing").create('d'); cliOptions.addOption(disableClassSharingOption); Option consoleLoggingOption = OptionBuilder.withArgName("loglevel").hasArg() .withDescription("Enable logging to console for the root log category with specified loglevel " + "(debug, info, warn, error)") .withLongOpt("console-logging").create('l'); cliOptions.addOption(consoleLoggingOption); Option consoleLogCatOption = OptionBuilder.withArgName("logcategory").hasArg() .withDescription("Enable console logging only for this category") .withLongOpt("console-log-category").create('m'); cliOptions.addOption(consoleLogCatOption); Option logConfigurationOption = OptionBuilder.withArgName("config").hasArg() .withDescription("Log4j configuration file (properties or .xml)").withLongOpt("log-configuration") .create("o"); cliOptions.addOption(logConfigurationOption); Option classLoadingLoggingOption = OptionBuilder .withDescription("Print information about the classloader setup (at startup).") .withLongOpt("classloader-log").create("z"); cliOptions.addOption(classLoadingLoggingOption); Option verboseOption = OptionBuilder.withDescription("Prints lots of information.").withLongOpt("verbose") .create("v"); cliOptions.addOption(verboseOption); Option quietOption = OptionBuilder.withDescription("Suppress normal output.").withLongOpt("quiet") .create("q"); cliOptions.addOption(quietOption); Option sourceLocationsOption = OptionBuilder.withArgName("sourcelocationfile").hasArg() .withDescription( "Path to property file containing alternate source location directory for artifacts.") .withLongOpt("source-locations").create("s"); cliOptions.addOption(sourceLocationsOption); Option modeOption = OptionBuilder.withArgName("modename").hasArg() .withDescription("The runtime mode: prototype, production").withLongOpt("runtime-mode").create("p"); cliOptions.addOption(modeOption); Option versionOption = OptionBuilder.withDescription( "Don't start the service, only dump the version info string for the module defined with -Dlilyruntime.info.module") .withLongOpt("version").create("V"); cliOptions.addOption(versionOption); Option helpOption = new Option("h", "help", false, "Shows help"); cliOptions.addOption(helpOption); CommandLineParser parser = new PosixParser(); CommandLine cmd = null; boolean showHelp = false; try { cmd = parser.parse(cliOptions, args); } catch (ParseException e) { showHelp = true; } if (showHelp || cmd.hasOption(helpOption.getOpt())) { printHelp(cliOptions); System.exit(1); } Logging.setupLogging(cmd.hasOption(verboseOption.getOpt()), cmd.hasOption(quietOption.getOpt()), cmd.hasOption(classLoadingLoggingOption.getOpt()), cmd.getOptionValue(logConfigurationOption.getOpt()), cmd.getOptionValue(consoleLoggingOption.getOpt()), cmd.getOptionValue(consoleLogCatOption.getOpt())); try { Logging.registerLog4jMBeans(); } catch (JMException e) { infolog.error("Unable to register log4j JMX control", e); } infolog.info("Starting the Lily Runtime."); List<File> confDirs = new ArrayList<File>(); if (!cmd.hasOption(confDirsOption.getOpt())) { File confDir = new File(DEFAULT_CONF_DIR).getAbsoluteFile(); if (!confDir.exists()) { System.out.println("Default configuration directory " + DEFAULT_CONF_DIR + " not found in current directory: " + confDir.getAbsolutePath()); System.out .println("To specify another location, use the -" + confDirsOption.getOpt() + " argument"); System.exit(1); } confDirs.add(confDir); } else { String confPathArg = cmd.getOptionValue(confDirsOption.getOpt()); String[] confPaths = confPathArg.split(File.pathSeparator); for (String confPath : confPaths) { confPath = confPath.trim(); if (confPath.length() == 0) { continue; } File confDir = new File(confPath); if (!confDir.exists()) { System.out.println( "Specified configuration directory does not exist: " + confDir.getAbsolutePath()); System.exit(1); } confDirs.add(confDir); } } ArtifactRepository artifactRepository; if (cmd.hasOption(repositoryLocationOption.getOpt())) { artifactRepository = new ChainedMaven2StyleArtifactRepository( cmd.getOptionValue(repositoryLocationOption.getOpt())); } else { File maven2Repository = findLocalMavenRepository(); infolog.info("Using local Maven repository at " + maven2Repository.getAbsolutePath()); artifactRepository = new Maven2StyleArtifactRepository(maven2Repository); } Set<String> disabledModuleIds = getDisabledModuleIds(cmd.getOptionValue(disabledModulesOption.getOpt())); SourceLocations sourceLocations; if (cmd.hasOption(sourceLocationsOption.getOpt())) { File file = new File(cmd.getOptionValue(sourceLocationsOption.getOpt())).getAbsoluteFile(); if (!file.exists()) { System.out.println( "The specified source locations property file does not exist: " + file.getAbsolutePath()); System.exit(1); } InputStream is = null; try { is = new FileInputStream(file); sourceLocations = new SourceLocations(is, file.getParent()); } catch (Throwable t) { throw new LilyRTException("Problem reading source locations property file.", t); } finally { IOUtils.closeQuietly(is); } } else { sourceLocations = new SourceLocations(); } LilyRuntimeSettings settings = new LilyRuntimeSettings(); settings.setConfManager(new ConfManagerImpl(confDirs)); settings.setDisabledModuleIds(disabledModuleIds); settings.setRepository(artifactRepository); settings.setSourceLocations(sourceLocations); settings.setEnableArtifactSharing(!cmd.hasOption(disableClassSharingOption.getOpt())); LilyRuntime runtime = new LilyRuntime(settings); if (cmd.hasOption(modeOption.getOpt())) { String optionValue = cmd.getOptionValue(modeOption.getOpt()); Mode mode = Mode.byName(optionValue); runtime.setMode(mode); } if (cmd.hasOption(versionOption.getOpt())) { System.out.println(runtime.buildModel().moduleInfo(System.getProperty("lilyruntime.info.module"))); System.exit(0); } try { runtime.start(); Runtime.getRuntime().addShutdownHook(new Thread(new ShutdownHandler(runtime))); printStartedMessage(); } catch (Throwable e) { e.printStackTrace(); System.err.println("Startup failed. Will try to shutdown and exit."); try { runtime.stop(); } finally { System.exit(1); } } }
From source file:org.linqs.psl.cli.Launcher.java
private static HelpFormatter getHelpFormatter() { HelpFormatter helpFormatter = new HelpFormatter(); // Hack the option ordering to put argumentions without options first and then required options first. // infer and learn go first, then required, then just normal. helpFormatter.setOptionComparator(new Comparator<Option>() { @Override/*from w w w . j av a 2s. c om*/ public int compare(Option o1, Option o2) { String name1 = o1.getOpt(); if (name1 == null) { name1 = o1.getLongOpt(); } String name2 = o2.getOpt(); if (name2 == null) { name2 = o2.getLongOpt(); } if (name1.equals(OPERATION_INFER)) { return -1; } if (name2.equals(OPERATION_INFER)) { return 1; } if (name1.equals(OPERATION_LEARN)) { return -1; } if (name2.equals(OPERATION_LEARN)) { return 1; } if (o1.isRequired() && !o2.isRequired()) { return -1; } if (!o1.isRequired() && o2.isRequired()) { return 1; } return name1.compareTo(name2); } }); helpFormatter.setWidth(100); return helpFormatter; }