List of usage examples for org.apache.commons.cli CommandLine getOptions
public Option[] getOptions()
From source file:com.splunk.Command.java
public Command parse(String[] argv) { CommandLineParser parser = new PosixParser(); CommandLine cmdline = null; try {/* w ww .ja v a2 s.c om*/ 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.netflix.cc.cli.CmdLineParametersParser.java
/** * Parses cmd line arguments./*ww w . jav a 2s . com*/ * * @param args arguments from a command line * @return a command line parameter object or null if help was invoked. */ public CmdLineParameters parseCmdOptions(String[] args) throws ParseException { // create the parser CommandLineParser parser = new DefaultParser(); CommandLine line = parser.parse(options, args); // --help if (line.hasOption(help.getLongOpt())) { // automatically generate the help statement HelpFormatter formatter = new HelpFormatter(); formatter.setWidth(120); formatter.printHelp("ttml-to-stl", options); return null; } CmdLineParameters result = new CmdLineParameters(); // --ttml parameters for (Option option : line.getOptions()) { if (option.equals(ttmlFile)) { TtmlInDescriptor ttmlInDescriptor = new TtmlInDescriptor(); try { ttmlInDescriptor.setFile(option.getValue(0)); ttmlInDescriptor.setOffsetMS(parseTtmlParameter(option, 1, "offsetMS")); ttmlInDescriptor.setStartMS(parseTtmlParameter(option, 2, "startMS")); ttmlInDescriptor.setEndMS(parseTtmlParameter(option, 3, "endMS")); } catch (IndexOutOfBoundsException e) { //It is error only if don't have file name //For required file it may not be thrown. We will check it later. } if (ttmlInDescriptor.getFile() == null) { throw new ParseException("--ttml parameter must have at least <file> attribute defined."); } result.getTtmlInDescriptors().add(ttmlInDescriptor); } } if (result.getTtmlInDescriptors().isEmpty()) { throw new ParseException("At least one input TTML file must be provided"); } // TTML mode parameters boolean doOutputTTML = line.hasOption(outputTtml.getLongOpt()); if (doOutputTTML) { result.setDoOuputTtml(true); result.setOutputTtmlFile(line.getOptionValue(outputTtml.getLongOpt())); } // SCC mode parameters boolean doOutputScc = line.hasOption(outputScc.getLongOpt()); if (doOutputScc) { result.setDoOutputScc(true); result.setOutputSccFile(line.getOptionValue(outputScc.getLongOpt())); } return result; }
From source file:com.antsdb.saltedfish.storage.HBaseUtilMain.java
private void run(String[] args) throws Exception { CommandLine line = parse(getOptions(), args); if (line.getOptions().length == 0 || line.hasOption('h')) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("hbase-util", getOptions()); return;/*w w w . j av a2s. c o m*/ } // Connecting if (line.hasOption("config")) { connectUseConfig(line.getOptionValue("config")); } else { String zkserver = "localhost"; if (line.hasOption("server")) { zkserver = line.getOptionValue("server"); } connect(zkserver); } // connect to hbase try { // options this.noversion = line.hasOption("noversion"); // commands if (line.hasOption("clean")) { delete_all(); } else if (line.hasOption("list-ns")) { list_ns(); } else if (line.hasOption("list-table")) { list_table(); } else if (line.hasOption("dump")) { if (line.getArgList().size() >= 1) { dump(line.getArgList().get(0)); } else { println("error: table name is missing"); } } else if (line.hasOption("link")) { link(); } else if (line.hasOption("get-sp")) { // read current SP read_sp(); } else if (line.hasOption("update-sp")) { // update current sp to specified value String updateSpValue = line.getOptionValue("update-sp", ""); try { long currentSp = Long.parseLong(updateSpValue); update_sp(currentSp); } catch (Exception ex) { println("Invalid current SP value - " + updateSpValue + "\n"); } } else if (line.hasOption("update-sp-db")) { // udpate current sp from antsdb File home = checkAntsDBHome(line); if (home != null) { update_sp(home); } } else if (line.hasOption("sync")) { File home = checkAntsDBHome(line); if (home != null) { boolean ignoreError = line.hasOption("ignore-error"); int cores = Runtime.getRuntime().availableProcessors(); int threads = cores; if (line.hasOption("threads")) { threads = Integer.parseInt(line.getOptionValue("threads")); if (threads <= 0 || threads > 200) { threads = cores; } } String skipList = line.getOptionValue("skip", "").trim(); String syncList = line.getOptionValue("tables", "").trim(); String[] skipTables = null; String[] syncTables = null; if (skipList != null && !skipList.isEmpty()) { skipTables = skipList.split(","); } if (syncList != null && !syncList.isEmpty()) { syncTables = syncList.split(","); } sync_antsdb(home, skipTables, syncTables, ignoreError, threads); } } else if (line.hasOption("compare")) { // udpate current sp from antsdb File home = checkAntsDBHome(line); if (home != null) { boolean ignoreError = line.hasOption("ignore-error"); String skipList = line.getOptionValue("skip", "").trim(); String syncList = line.getOptionValue("tables", "").trim(); String[] skipTables = null; String[] syncTables = null; if (skipList != null && !skipList.isEmpty()) { skipTables = skipList.split(","); } if (syncList != null && !syncList.isEmpty()) { syncTables = syncList.split(","); } // update current sp to specified value int rows = 200; String s = line.getOptionValue("compare", ""); try { rows = Integer.parseInt(s); if (rows < 0) throw new Exception(); } catch (Exception ex) { println("Invalid compare rows count - " + s + "\n"); } compare_hbase_rows(home, rows, skipTables, syncTables, ignoreError); } } else if (line.hasOption("checkrow")) { // udpate current sp from antsdb File home = checkAntsDBHome(line); if (home != null) { String table = line.getOptionValue("tables", "").trim(); String key = line.getOptionValue("checkrow", "").trim(); if (table == null || table.isEmpty()) { println("No talbe specified."); } else if (key == null || key.isEmpty()) { println("No row key specified,"); } else { checkRow(home, table, key); } } } else { println("error: command is missing"); } } finally { // alway disconnect from hbase disconnect(); } }
From source file:com.netflix.imfutility.ttmltostl.inputparameters.CmdLineParametersParser.java
/** * Parses cmd line arguments.//from www.j av a 2 s .com * * @param args arguments from a command line * @return a command line parameter object or null if help was invoked. */ public CmdLineParameters parseCmdOptions(String[] args) throws ParseException { // create the parser CommandLineParser parser = new DefaultParser(); CommandLine line = parser.parse(options, args); // --help if (line.hasOption(help.getLongOpt())) { // automatically generate the help statement HelpFormatter formatter = new HelpFormatter(); formatter.setWidth(120); formatter.printHelp("ttml-to-stl", options); return null; } CmdLineParameters result = new CmdLineParameters(); // --ttml parameters for (Option option : line.getOptions()) { if (option.equals(ttmlFile)) { TtmlInDescriptor ttmlInDescriptor = new TtmlInDescriptor(); try { ttmlInDescriptor.setFile(option.getValue(0)); ttmlInDescriptor.setOffsetMS(parseTtmlParameter(option, 1, "offsetMS")); ttmlInDescriptor.setStartMS(parseTtmlParameter(option, 2, "startMS")); ttmlInDescriptor.setEndMS(parseTtmlParameter(option, 3, "endMS")); } catch (IndexOutOfBoundsException e) { //It is error only if don't have file name //For required file it may not be thrown. We will check it later. } if (ttmlInDescriptor.getFile() == null) { throw new ParseException("--ttml parameter must have at least <file> attribute defined."); } result.getTtmlInDescriptors().add(ttmlInDescriptor); } } if (result.getTtmlInDescriptors().size() == 0) { throw new ParseException("At least one input TTML file must be provided"); } // TTML mode parameters boolean doOutputTTML = line.hasOption(outputTTML.getLongOpt()); if (doOutputTTML) { result.setDoOuputTTML(true); result.setOutputTTMLFile(line.getOptionValue(outputTTML.getLongOpt())); } // STL mode parameters boolean doOutputSTL = line.hasOption(outputSTL.getLongOpt()); if (doOutputSTL) { result.setDoOutputSTL(true); result.setOutputSTLFile(line.getOptionValue(outputSTL.getLongOpt())); if (!line.hasOption(metadataOpt.getLongOpt())) { throw new ParseException("A metadata.xml must be specified for STL mode"); } String metadataXml = line.getOptionValue(metadataOpt.getLongOpt()); if (!new File(metadataXml).isFile()) { throw new ParseException("A metadata.xml must be an existing file."); } result.setMetadataXml(metadataXml); } return result; }
From source file:fr.gouv.finances.cp.xemelios.importers.batch.BatchRealImporter.java
public BatchRealImporter(PropertiesExpansion applicationConfiguration, String[] args) throws Exception { super();/*w w w .j a v a 2 s. co m*/ this.applicationConfiguration = applicationConfiguration; this.files = new ArrayList<File>(); this.filesToDrop = new ArrayList<File>(); this.opts = new Options(); arguments = args; createLogger(); setCommandLineOptions(); posixparser = new PosixParser(); CommandLine cm = posixparser.parse(opts, arguments); Option[] s = cm.getOptions(); cmopts = new Vector<String>(); for (int i = 0; i < s.length; i++) { cmopts.add(s[i].getOpt()); } if (!cmopts.contains("h")) { // Chargement des fichiers de configuration if (cmopts.contains("g")) { for (int i = 0; i < args.length; i++) { if (args[i].matches("-g")) { documentsDefDir = args[i + 1]; logger.debug("documents-def.dir =" + documentsDefDir); } } } loadConfig(); // Type de document dans la ligne de commande? if (cmopts.contains("d")) { // Recupration du type de document for (int i = 0; i < args.length; i++) { if (args[i].matches("-d")) { documentid = args[i + 1]; logger.debug("docId =" + documentid); } else if (args[i].matches("-r")) { String rulesFileName = args[i + 1]; RulesParser rp = new RulesParser(FactoryProvider.getSaxParserFactory()); rp.parse(new File(rulesFileName)); RulesModel rules = (RulesModel) rp.getMarshallable(); setArchiveRules(rules); } } if (cmopts.contains("f")) { Vector<String> fil = new Vector<String>(); for (int i = 0; i < args.length; i++) { if (args[i].matches("-f")) { for (int j = i + 1; j < args.length; j++) { fil.add(args[j]); } } } setFilesToImport(fil.toArray()); } // Option fichier(s) prsent(s) dans la ligne de commande? if (cmopts.contains("f") && cmopts.contains("i")) { Vector<String> fil = new Vector<String>(); for (int i = 0; i < args.length; i++) { if (args[i].matches("-i")) { if (args[i + 1].matches("yes")) { budgIsInterractif = true; } if (args[i + 2].matches("yes")) { collIsInterractif = true; } } } setFilesToImport(fil.toArray()); } else { System.err.println( "L'option fichier(s) est obligatoire dans la ligne de commande lorsque le mode interractif est declar."); System.exit(SYNTAX_ERROR); } if (cmopts.contains("u")) { for (int i = 0; i < args.length; i++) { if (args[i].matches("-u")) { final String strUser = args[i + 1]; // c'est un peu violent, ok, mais on verra plus tard user = new XemeliosUser() { @Override public String getId() { return strUser; } @Override public String getDisplayName() { return getId(); } @Override public boolean hasRole(String role) { return true; } @Override public boolean hasDocument(String document) { return true; } @Override public boolean hasCollectivite(String collectivite, DocumentModel dm) { return true; } }; } } } else { System.err.println("L'option -u est obligatoire"); System.exit(SYNTAX_ERROR); } System.exit(importer(documentid)); } else { System.err.println("L'option type de document est obligatoire dans la ligne de commande."); System.exit(SYNTAX_ERROR); } } else { System.out.println("\n\nAide de l'importeur batch.\n" + "_________________________\n\n" + "Syntaxe : importerBatch -config config-dir -d typeDoc [-c code libelle] [-b code libelle] [-i (y|n budget) (y|n collectivite)] [-r fichier.regles] -f fichier [fichier [...]]\n\n" + "-config : chaine contenant le ou les rpertoires o se trouvent les fichiers de dfinition des configurations de documents\n" + " si cette option n'est pas fournie, utilise le contenu de la variable d'environnement " + Constants.SYS_PROP_DOC_DEF_DIR + "\n\n" + "-d : MODELE DU DOCUMENT importer >> Option Obligatoire.\n\n" + "-b : BUDGET DU FICHIER >> Option Facultative.\n\n" + " - Si le budget est prsent dans le fichier cette option est inutile.\n" + " - Sinon prcisez le libell puis le code du budget.\n" + " - Si pas d'argument pour le budget :\n" + " - Si prsence d'un budget par defaut dans fichier de conf, alors celui-ci sera pris.\n" + " - Sinon, abandon de l'import car le budget n'est pas dfinit.\n" + " - Si option particulire si y n alors mode interactif avec l'utilisateur dans la console." + "Pour chaque fichier sans budget, on pose la question l'utilisateur.\n\n" + "-c : COLLECTIVITE DU FICHIER >> Option Facultative.\n\n" + " - Si la collectivit est prsente dans le fichier, on l'utilise.\n" + " - Sinon on prend celui de l'argument.\n" + " - Si pas d'argument pour la collectivit, alors mode interactif avec l'utilisateur dans la console.\n" + "Pour chaque fichier sans collectivit, on pose la question l'utilisateur.\n\n" + "-i : MODE INTERACTIF >> Option Facultative.\n" + " - y ou n permet d'activer l'option interactive pour l'element en question.\n\n" + "-r : permet de spcifier le fichier de rgles appliquer l'import de l'archive ;\n\t\tuniquement si -d xemelios.archive.\n\n" + "-u : utilisateur (id ou login) utiliser opur l'import\n\n" + "-f : NOM DU/DES FICHIER(S) importer"); System.exit(SYNTAX_ERROR); } }
From source file:mitm.application.djigzo.tools.Upgrade.java
public void handleCommandline(String[] args) throws IOException, ParseException, WSProxyFactoryException, WebServiceCheckedException { CommandLineParser parser = new BasicParser(); Options options = createCommandLineOptions(); HelpFormatter formatter = new HelpFormatter(); CommandLine commandLine; try {// ww w . j a v a 2s. co m commandLine = parser.parse(options, args); } catch (ParseException e) { formatter.printHelp(COMMAND_NAME, options, true); throw e; } user = commandLine.getOptionValue("user"); password = commandLine.getOptionValue("password"); String version = commandLine.getOptionValue("version"); if (commandLine.getOptions().length == 0 || commandLine.hasOption("help")) { formatter.printHelp(COMMAND_NAME, options, true); return; } if (StringUtils.equalsIgnoreCase(version, "1.3")) { upgradeTo13(); } else { throw new IllegalArgumentException("Unsupported version."); } }
From source file:edu.umass.cs.gnsserver.utils.ParametersAndOptions.java
/** * Returns a hash map with all options including options in config file and the command line arguments * * @param className// w w w. jav a 2 s.c o m * @param commandLineOptions * @param args command line arguments given to JVM * @return hash map with KEY = parameter names, VALUE = values of parameters in String form * @throws IOException */ public static HashMap<String, String> getParametersAsHashMap(String className, Options commandLineOptions, String... args) throws IOException { CommandLine parser = null; try { parser = new GnuParser().parse(commandLineOptions, args); } catch (ParseException e) { System.err.println("Problem parsing command line:" + e); printUsage(className, commandLineOptions); System.exit(1); } if (parser.hasOption(HELP)) { printUsage(className, commandLineOptions); System.exit(0); } // load options given in config file in a java properties object Properties prop = new Properties(); if (parser.hasOption(CONFIG_FILE)) { String value = parser.getOptionValue(CONFIG_FILE); File f = new File(value); if (f.exists() == false) { System.err.println("Config file not found:" + value); System.exit(2); } InputStream input = new FileInputStream(value); // load a properties file prop.load(input); } // create a hash map with all options including options in config file and the command line arguments HashMap<String, String> allValues = new HashMap<String, String>(); // add options given in config file to hash map for (String propertyName : prop.stringPropertyNames()) { allValues.put(propertyName, prop.getProperty(propertyName)); } // add options given via command line to hashmap. these options can override options given in config file. for (Option option : parser.getOptions()) { String argName = option.getOpt(); String value = option.getValue(); // if an option has a boolean value, the command line arguments do not say true/false for some of these options // if option name is given as argument on the command line, it means the value is true. therefore, the hashmap // will also assign the value true for these options. if (value == null) { value = "true"; } allValues.put(argName, value); } return allValues; }
From source file:com.netcrest.pado.tools.pado.command.ls.java
@Override public void run(CommandLine commandLine, String command) throws Exception { String path;/*from www . j a va 2s. c o m*/ if (commandLine.getArgList().size() == 1) { path = padoShell.getCurrentPath(); } else { path = (String) commandLine.getArgList().get(1); } boolean includeHidden = commandLine.hasOption("a"); boolean longList = commandLine.hasOption("l"); boolean recursive = commandLine.hasOption("R"); Option options[] = commandLine.getOptions(); for (Option option : options) { if (includeHidden == false) { includeHidden = option.getOpt().contains("a"); } if (longList == false) { longList = option.getOpt().contains("l"); } if (recursive == false) { recursive = option.getOpt().contains("R"); } } listPaths(path, includeHidden, longList, recursive); }
From source file:com.gmarciani.gmparser.controllers.App.java
/** * <p>The app entry-point method.<p> * <p>This method is activated when no arguments neither options are specified.<p> * //from w w w .j a v a 2s.c om * @param args command-line arguments. * @throws ParseException */ public void play(String[] args) throws ParseException { CommandLineParser cmdParser = new GnuParser(); CommandLine cmd = cmdParser.parse(this.options, args); String unrecognizedArguments[] = cmd.getArgs(); if (unrecognizedArguments.length != 0) { this.getOutput().onUnrecognizedArguments(unrecognizedArguments); this.quit(); } if (cmd.getOptions().length == 0) { boolean loop = true; while (loop) { this.playMenu(); loop = this.getContinued(); } } else if (cmd.hasOption("analyze")) { final String vals[] = cmd.getOptionValues("analyze"); final String grammar = vals[0]; if (!this.validateGrammar(grammar)) return; this.analyze(grammar); } else if (cmd.hasOption("transform")) { final String vals[] = cmd.getOptionValues("transform"); final GrammarTransformation transformation = GrammarTransformation.valueOf(vals[0]); final String grammar = vals[1]; if (!this.validateGrammar(grammar)) return; this.transform(grammar, transformation); } else if (cmd.hasOption("parse")) { final String vals[] = cmd.getOptionValues("parse"); final ParserType parserType = ParserType.valueOf(vals[0]); final String word = (vals[1] == null || vals[1].equals(Grammar.EPSILON.toString())) ? "" : vals[1]; final String grammar = vals[2]; if (!this.validateGrammar(grammar)) return; this.parse(grammar, word, parserType); } else if (cmd.hasOption("help")) { this.help(); } else if (cmd.hasOption("version")) { this.version(); } this.quit(); }
From source file:mitm.application.djigzo.tools.CertManager.java
private void handleCommandline(String[] args) throws Exception { CommandLineParser parser = new BasicParser(); Options options = createCommandLineOptions(); HelpFormatter formatter = new HelpFormatter(); CommandLine commandLine; try {/* w w w .j av a2s. c o m*/ commandLine = parser.parse(options, args); } catch (ParseException e) { formatter.printHelp(COMMAND_NAME, options, true); throw e; } initLogging(commandLine.hasOption(loggingOption.getOpt())); soapUser = soapUserOption.getValue(); soapPassword = soapPasswordOption.getValue(); keyStorePassword = keyStorePasswordOption.getValue(); if (commandLine.getOptions().length == 0 || commandLine.hasOption(helpOption.getOpt())) { formatter.printHelp(COMMAND_NAME, options, true); System.exit(1); return; } if (commandLine.hasOption(importOption.getOpt())) { if (commandLine.hasOption(cerOption.getOpt())) { importCertificates(); } else if (commandLine.hasOption(pfxOption.getOpt())) { importKeyStore(); } } else if (commandLine.hasOption(syncOption.getOpt())) { syncKeyAndCertStore(); } }