List of usage examples for org.apache.commons.cli MissingOptionException MissingOptionException
public MissingOptionException(List missingOptions)
MissingSelectedException
with the specified list of missing options. From source file:com.spectralogic.ds3cli.Main.java
public static void main(final String[] args) { try {/*from w w w .ja v a2 s .c o m*/ final Properties props = CliUtils.readProperties(PROPERTY_FILE); // constructor parses for command, help, version, and logging settings final Arguments arguments = new Arguments(args); // turn root log wide open, filters will be set to argument levels configureLogging(arguments.getConsoleLogLevel(), arguments.getFileLogLevel()); LOG.info("Version: {}", CliUtils.getVersion(props)); LOG.info("Build Date: {}", CliUtils.getBuildDate(props)); LOG.info("Command line args: {}", Joiner.on(", ").join(args)); LOG.info("Console log level: {}", arguments.getConsoleLogLevel().toString()); LOG.info("Log file log level: {}", arguments.getFileLogLevel().toString()); LOG.info(CliCommand.getPlatformInformation()); if (arguments.isHelp()) { printHelp(arguments); System.exit(0); } if (arguments.isPrintVersion()) { printVersion(props); System.exit(0); } // then it had better be a command try { if (arguments.getCommand() == null) { throw new MissingOptionException(COMMAND.getOpt()); } } catch (final IllegalArgumentException e) { throw new BadArgumentException("Unknown command", e); } final Ds3Client client = ClientFactory.createClient(arguments); if (!CliUtils.isVersionSupported(client)) { System.out.println(String.format("ERROR: Minimum Black Pearl supported is %s", CliUtils.MINIMUM_VERSION_SUPPORTED)); System.exit(2); } final Ds3Provider provider = new Ds3ProviderImpl(client, Ds3ClientHelpers.wrap(client)); final FileSystemProvider fileSystemProvider = new FileSystemProviderImpl(); // get command, parse args final CliCommand command = CliCommandFactory.getCommandExecutor(arguments.getCommand()) .withProvider(provider, fileSystemProvider); command.init(arguments); final CommandResponse response = command.render(); System.out.println(response.getMessage()); System.exit(response.getReturnCode()); } catch (final Exception e) { EXCEPTION.handleException(e); System.exit(2); } }
From source file:com.bytelightning.opensource.pokerface.PokerFaceApp.java
public static void main(String[] args) { if (JavaVersionAsFloat() < (1.8f - Float.MIN_VALUE)) { System.err.println("PokerFace requires at least Java v8 to run."); return;//from w w w . j a v a2s .c o m } // Configure the command line options parser Options options = new Options(); options.addOption("h", false, "help"); options.addOption("listen", true, "(http,https,secure,tls,ssl,CertAlias)=Address:Port for https."); options.addOption("keystore", true, "Filepath for PokerFace certificate keystore."); options.addOption("storepass", true, "The store password of the keystore."); options.addOption("keypass", true, "The key password of the keystore."); options.addOption("target", true, "Remote Target requestPattern=targetUri"); // NOTE: targetUri may contain user-info and if so will be interpreted as the alias of a cert to be presented to the remote target options.addOption("servercpu", true, "Number of cores the server should use."); options.addOption("targetcpu", true, "Number of cores the http targets should use."); options.addOption("trustany", false, "Ignore certificate identity errors from target servers."); options.addOption("files", true, "Filepath to a directory of static files."); options.addOption("config", true, "Path for XML Configuration file."); options.addOption("scripts", true, "Filepath for root scripts directory."); options.addOption("library", true, "JavaScript library to load into global context."); options.addOption("watch", false, "Dynamically watch scripts directory for changes."); options.addOption("dynamicTargetScripting", false, "WARNING! This option allows scripts to redirect requests to *any* other remote server."); CommandLine cmdLine = null; // parse the command line. try { CommandLineParser parser = new PosixParser(); cmdLine = parser.parse(options, args); if (args.length == 0 || cmdLine.hasOption('h')) { HelpFormatter formatter = new HelpFormatter(); formatter.setWidth(120); formatter.printHelp(PokerFaceApp.class.getSimpleName(), options); return; } } catch (ParseException exp) { System.err.println("Parsing failed. Reason: " + exp.getMessage()); return; } catch (Exception ex) { ex.printStackTrace(System.err); return; } XMLConfiguration config = new XMLConfiguration(); try { if (cmdLine.hasOption("config")) { Path tmp = Utils.MakePath(cmdLine.getOptionValue("config")); if (!Files.exists(tmp)) throw new FileNotFoundException("Configuration file does not exist."); if (Files.isDirectory(tmp)) throw new FileNotFoundException("'config' path is not a file."); // This is a bit of a pain, but but let's make sure we have a valid configuration file before we actually try to use it. config.setEntityResolver(new DefaultEntityResolver() { @Override public InputSource resolveEntity(String publicId, String systemId) throws SAXException { InputSource retVal = super.resolveEntity(publicId, systemId); if ((retVal == null) && (systemId != null)) { try { URL entityURL; if (systemId.endsWith("/PokerFace_v1Config.xsd")) entityURL = PokerFaceApp.class.getResource("/PokerFace_v1Config.xsd"); else entityURL = new URL(systemId); URLConnection connection = entityURL.openConnection(); connection.setUseCaches(false); InputStream stream = connection.getInputStream(); retVal = new InputSource(stream); retVal.setSystemId(entityURL.toExternalForm()); } catch (Throwable e) { return retVal; } } return retVal; } }); config.setSchemaValidation(true); config.setURL(tmp.toUri().toURL()); config.load(); if (cmdLine.hasOption("listen")) System.out.println("IGNORING 'listen' option because a configuration file was supplied."); if (cmdLine.hasOption("target")) System.out.println("IGNORING 'target' option(s) because a configuration file was supplied."); if (cmdLine.hasOption("scripts")) System.out.println("IGNORING 'scripts' option because a configuration file was supplied."); if (cmdLine.hasOption("library")) System.out.println("IGNORING 'library' option(s) because a configuration file was supplied."); } else { String[] serverStrs; String[] addr = { null }; String[] port = { null }; serverStrs = cmdLine.getOptionValues("listen"); if (serverStrs == null) throw new MissingOptionException("No listening addresses specified specified"); for (int i = 0; i < serverStrs.length; i++) { String addrStr; String alias = null; String protocol = null; Boolean https = null; int addrPos = serverStrs[i].indexOf('='); if (addrPos >= 0) { if (addrPos < 2) throw new IllegalArgumentException("Invalid http argument."); else if (addrPos + 1 >= serverStrs[i].length()) throw new IllegalArgumentException("Invalid http argument."); addrStr = serverStrs[i].substring(addrPos + 1, serverStrs[i].length()); String[] types = serverStrs[i].substring(0, addrPos).split(","); for (String type : types) { if (type.equalsIgnoreCase("http")) break; else if (type.equalsIgnoreCase("https") || type.equalsIgnoreCase("secure")) https = true; else if (type.equalsIgnoreCase("tls") || type.equalsIgnoreCase("ssl")) protocol = type.toUpperCase(); else alias = type; } } else addrStr = serverStrs[i]; ParseAddressString(addrStr, addr, port, alias != null ? 443 : 80); config.addProperty("server.listen(" + i + ")[@address]", addr[0]); config.addProperty("server.listen(" + i + ")[@port]", port[0]); if (alias != null) config.addProperty("server.listen(" + i + ")[@alias]", alias); if (protocol != null) config.addProperty("server.listen(" + i + ")[@protocol]", protocol); if (https != null) config.addProperty("server.listen(" + i + ")[@secure]", https); } String servercpu = cmdLine.getOptionValue("servercpu"); if (servercpu != null) config.setProperty("server[@cpu]", servercpu); String clientcpu = cmdLine.getOptionValue("targetcpu"); if (clientcpu != null) config.setProperty("targets[@cpu]", clientcpu); // Configure static files if (cmdLine.hasOption("files")) { Path tmp = Utils.MakePath(cmdLine.getOptionValue("files")); if (!Files.exists(tmp)) throw new FileNotFoundException("Files directory does not exist."); if (!Files.isDirectory(tmp)) throw new FileNotFoundException("'files' path is not a directory."); config.setProperty("files.rootDirectory", tmp.toAbsolutePath().toUri()); } // Configure scripting if (cmdLine.hasOption("scripts")) { Path tmp = Utils.MakePath(cmdLine.getOptionValue("scripts")); if (!Files.exists(tmp)) throw new FileNotFoundException("Scripts directory does not exist."); if (!Files.isDirectory(tmp)) throw new FileNotFoundException("'scripts' path is not a directory."); config.setProperty("scripts.rootDirectory", tmp.toAbsolutePath().toUri()); config.setProperty("scripts.dynamicWatch", cmdLine.hasOption("watch")); String[] libraries = cmdLine.getOptionValues("library"); if (libraries != null) { for (int i = 0; i < libraries.length; i++) { Path lib = Utils.MakePath(libraries[i]); if (!Files.exists(lib)) throw new FileNotFoundException( "Script library does not exist [" + libraries[i] + "]."); if (Files.isDirectory(lib)) throw new FileNotFoundException( "Script library is not a file [" + libraries[i] + "]."); config.setProperty("scripts.library(" + i + ")", lib.toAbsolutePath().toUri()); } } } else if (cmdLine.hasOption("watch")) System.out.println("IGNORING 'watch' option as no 'scripts' directory was specified."); else if (cmdLine.hasOption("library")) System.out.println("IGNORING 'library' option as no 'scripts' directory was specified."); } String keyStorePath = cmdLine.getOptionValue("keystore"); if (keyStorePath != null) config.setProperty("keystore", keyStorePath); String keypass = cmdLine.getOptionValue("keypass"); if (keypass != null) config.setProperty("keypass", keypass); String storepass = cmdLine.getOptionValue("storepass"); if (storepass != null) config.setProperty("storepass", keypass); if (cmdLine.hasOption("trustany")) config.setProperty("targets[@trustAny]", true); config.setProperty("scripts.dynamicTargetScripting", cmdLine.hasOption("dynamicTargetScripting")); String[] targetStrs = cmdLine.getOptionValues("target"); if (targetStrs != null) { for (int i = 0; i < targetStrs.length; i++) { int uriPos = targetStrs[i].indexOf('='); if (uriPos < 2) throw new IllegalArgumentException("Invalid target argument."); else if (uriPos + 1 >= targetStrs[i].length()) throw new IllegalArgumentException("Invalid target argument."); String patternStr = targetStrs[i].substring(0, uriPos); String urlStr = targetStrs[i].substring(uriPos + 1, targetStrs[i].length()); String alias; try { URL url = new URL(urlStr); alias = url.getUserInfo(); String scheme = url.getProtocol(); if ((!"http".equals(scheme)) && (!"https".equals(scheme))) throw new IllegalArgumentException("Invalid target uri scheme."); int port = url.getPort(); if (port < 0) port = url.getDefaultPort(); urlStr = scheme + "://" + url.getHost() + ":" + port + url.getPath(); String ref = url.getRef(); if (ref != null) urlStr += "#" + ref; } catch (MalformedURLException ex) { throw new IllegalArgumentException("Malformed target uri"); } config.addProperty("targets.target(" + i + ")[@pattern]", patternStr); config.addProperty("targets.target(" + i + ")[@url]", urlStr); if (alias != null) config.addProperty("targets.target(" + i + ")[@alias]", alias); } } // config.save(System.out); } catch (Throwable e) { e.printStackTrace(System.err); return; } // If we get here, we have a possibly valid configuration. try { final PokerFace p = new PokerFace(); p.config(config); if (p.start()) { PokerFace.Logger.warn("Started!"); Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { try { PokerFace.Logger.warn("Initiating shutdown..."); p.stop(); PokerFace.Logger.warn("Shutdown completed!"); } catch (Throwable e) { PokerFace.Logger.error("Failed to shutdown cleanly!"); e.printStackTrace(System.err); } } }); } else { PokerFace.Logger.error("Failed to start!"); System.exit(-1); } } catch (Throwable e) { e.printStackTrace(System.err); } }
From source file:net.kahowell.xsd.fuzzer.config.CommandLineArgumentsModule.java
@Override protected void configure() { if (commandLine.hasOption("nd")) { log.debug("not downloading urls"); bindConstant().annotatedWith(Names.named("offline")).to(true); }// ww w. ja v a 2 s .c o m if (commandLine.hasOption("o")) { String filename = commandLine.getOptionValue("o"); log.info("outputting to file: " + filename); bindConstant().annotatedWith(Names.named("output filename")).to(filename); } if (commandLine.hasOption("url")) { bindConstant().annotatedWith(Names.named("schema url")).to(commandLine.getOptionValue("url")); } else if (commandLine.hasOption("file")) { bindConstant().annotatedWith(Names.named("schema url")) .to(new File(commandLine.getOptionValue("file")).toURI().toString()); } else { throw new RuntimeException(new MissingOptionException("Must specify schema file or schema url.")); } }
From source file:com.spectralogic.ds3cli.ClientFactory.java
private static String getOptionOrEnv(final Arguments arguments, final Option option, final String envName) throws MissingOptionException { String value = arguments.getOptionValue(option.getOpt()); if (Guard.isStringNullOrEmpty(value)) { value = System.getenv(envName); if (Guard.isStringNullOrEmpty(value)) { throw new MissingOptionException( "Missing Endpoint: define " + envName + "or use " + option.getOpt()); }/* www .ja va 2s .c o m*/ } return value; }
From source file:ctrus.pa.bow.core.BOWOptionsImpl.java
public final String getOptionInternal(String option, boolean isInternal) throws MissingOptionException { if (hasOptionInternal(option, isInternal)) if (isInternal) return _internalOptions.get(option); else// w w w .j a va 2 s . c o m return _parsedOptions.getOptionValue(option); else throw new MissingOptionException(option + " - Option not provided"); }
From source file:com.spectralogic.ds3cli.command.GetObject.java
@Override public CliCommand init(final Arguments args) throws Exception { processCommandOptions(requiredArgs, optionalArgs, args); this.bucketName = args.getBucket(); this.priority = args.getPriority(); this.objectName = args.getObjectName(); this.prefix = args.getDirectory(); if (this.prefix == null) { this.prefix = "."; }//w w w. j ava 2s .co m this.discard = args.isDiscard(); if (this.discard && !Guard.isStringNullOrEmpty(args.getDirectory())) { throw new CommandException("Cannot set both " + DIRECTORY.getOpt() + " and " + DISCARD.getLongOpt()); } if (this.discard) { LOG.warn("Discard flag set -- all incoming data will be discarded"); } if (args.isSync()) { LOG.info("Using sync command"); this.sync = true; } this.numberOfThreads = args.getNumberOfThreads(); // if you set one, you must set both start and length if (!Guard.isStringNullOrEmpty(args.getRangeLength()) || !Guard.isStringNullOrEmpty(args.getRangeOffset())) { if (Guard.isStringNullOrEmpty(args.getRangeLength()) || Guard.isStringNullOrEmpty(args.getRangeOffset())) { throw new MissingOptionException("Partial recovery must provide values for both " + RANGE_OFFSET.getLongOpt() + " and " + RANGE_LENGTH.getLongOpt()); } else { this.rangeOffset = Long.parseLong(args.getOptionValue(RANGE_OFFSET.getLongOpt())); this.rangeLength = Long.parseLong(args.getOptionValue(RANGE_LENGTH.getLongOpt())); } } return this; }
From source file:com.spectralogic.ds3cli.command.PutBulk.java
@Override public CliCommand init(final Arguments args) throws Exception { processCommandOptions(requiredArgs, optionalArgs, args); this.bucketName = args.getBucket(); this.pipe = CliUtils.isPipe(); if (this.pipe) { if (this.isOtherArgs(args)) { throw new BadArgumentException("-d, -o and -p arguments are not supported when using piped input"); }// ww w .ja va2s. c o m this.pipedFiles = FileUtils.getPipedFilesFromStdin(getFileSystemProvider()); if (Guard.isNullOrEmpty(this.pipedFiles)) { throw new MissingOptionException("Stdin is empty"); //We should never see that since we checked isPipe } this.mapNormalizedObjectNameToObjectName = FileUtils.getNormalizedObjectNames(this.pipedFiles); } else if (!Guard.isStringNullOrEmpty(args.getDirectory())) { final String srcDir = args.getDirectory(); this.inputDirectory = Paths.get(srcDir); this.prefix = args.getPrefix(); } else { throw new BadArgumentException("-d argument required unless using piped input"); } this.priority = args.getPriority(); this.writeOptimization = args.getWriteOptimization(); this.checksum = args.isChecksum(); this.force = args.isForce(); if (args.isSync()) { if (!SyncUtils.isSyncSupported(getClient())) { throw new SyncNotSupportedException( "The sync command is not supported with your version of BlackPearl."); } LOG.info("Using sync command"); this.sync = true; } this.numberOfThreads = args.getNumberOfThreads(); if (args.isIgnoreErrors()) { LOG.info("Ignoring files that cause errors"); this.ignoreErrors = true; } this.followSymlinks = args.isFollowSymlinks(); LOG.info("Follow symlinks has been set to: {}", this.followSymlinks); this.ignoreNamingConflicts = args.doIgnoreNamingConflicts(); LOG.info("Ignore naming conflicts has been set to: {}", this.ignoreNamingConflicts); return this; }
From source file:ctrus.pa.bow.DefaultBagOfWords.java
protected Collection<File> getSourceDocuments(String wildCard) throws MissingOptionException { File sourceDir = new File(_options.getOption(DefaultOptions.SOURCE_DIR)); CtrusHelper.printToConsole("Choosen source folder - " + sourceDir.getAbsolutePath()); if (sourceDir.exists()) { return FileUtils.listFiles(sourceDir, new WildcardFileFilter(wildCard), DirectoryFileFilter.DIRECTORY); } else {//from www . j a v a 2 s. com throw new MissingOptionException("Unable to find source directory!"); } }
From source file:com.ericsson.eiffel.remrem.generate.cli.CLIOptions.java
public static void checkRequiredOptions() throws MissingOptionException { OptionGroup[] groups = { typeGroup, contentGroup }; for (OptionGroup group : groups) { ArrayList<Option> groupOptions = new ArrayList<Option>(group.getOptions()); boolean groupIsGiven = false; for (Option option : groupOptions) { if (commandLine.hasOption(option.getOpt())) { groupIsGiven = true;/*from www . j a va2s. c om*/ break; } } if (!groupIsGiven) { throw new MissingOptionException(groupOptions); } } }
From source file:com.ericsson.eiffel.remrem.publish.cli.CliOptions.java
public static void checkRequiredOptions() throws MissingOptionException { OptionGroup[] groups = { contentGroup }; for (OptionGroup group : groups) { ArrayList<Option> groupOptions = new ArrayList<Option>(group.getOptions()); boolean groupIsGiven = false; for (Option option : groupOptions) { if (commandLine.hasOption(option.getOpt())) { groupIsGiven = true;/*www. java2 s. c o m*/ break; } } if (!groupIsGiven) { throw new MissingOptionException(groupOptions); } } }