List of usage examples for org.apache.commons.cli GnuParser parse
public CommandLine parse(Options options, String[] arguments) throws ParseException
arguments
based on the specifed Options . From source file:de.dmarcini.submatix.pclogger.gui.MainCommGUI.java
/** * CLI-Optionen einlesen Project: SubmatixBTConfigPC Package: de.dmarcini.submatix.pclogger.gui * /*from w w w .j a v a 2 s .c om*/ * @author Dirk Marciniak (dirk_marciniak@arcor.de) Stand: 28.01.2012 * @param args * @return * @throws Exception */ @SuppressWarnings("null") private static boolean parseCliOptions(String[] args) throws Exception { CommandLine cmdLine = null; String argument; // Optionenobjet anlegen Options options = new Options(); Option optLogLevel; Option optLogFile; Option optDatabaseDir; Option optExportDir; Option optLangTwoLetter; Option optConsoleLog; Option optHelp; Option optDeveloperDebug; GnuParser parser; // // Optionen fr das Parsing anlegen und zu den Optionen zufgen // // Hilfe optHelp = new Option("help", "give help..."); // Logleven festlegen OptionBuilder.withArgName("loglevel"); OptionBuilder.hasArg(); OptionBuilder.withDescription("Loglevel (ALL|DEBUG|INFO|WARN|ERROR|FATAL|OFF)"); optLogLevel = OptionBuilder.create("loglevel"); // Logfile abgefragt? OptionBuilder.withArgName("logfile"); OptionBuilder.hasArg(); OptionBuilder.withDescription("custom logfile (directory must exist)"); optLogFile = OptionBuilder.create("logfile"); // Daternverzeichnis? OptionBuilder.withArgName("databasedir"); OptionBuilder.hasArg(); OptionBuilder.withDescription("directory for create ans saving database"); optDatabaseDir = OptionBuilder.create("databasedir"); // Exportverzeichnis? OptionBuilder.withArgName("exportdir"); OptionBuilder.hasArg(); OptionBuilder.withDescription("directory for export UDDF files"); optExportDir = OptionBuilder.create("exportdir"); // Landescode vorgeben? OptionBuilder.withArgName("langcode"); OptionBuilder.hasArg(); OptionBuilder.withDescription("language code for overridign system default (eg. 'en' or 'de' etc.)"); optLangTwoLetter = OptionBuilder.create("langcode"); // Log auf console? optConsoleLog = new Option("console", "logging to console for debugging purposes..."); // Entwicklerdebug optDeveloperDebug = new Option("developer", "for programmers..."); // Optionen zufgen options.addOption(optHelp); options.addOption(optLogLevel); options.addOption(optLogFile); options.addOption(optDatabaseDir); options.addOption(optExportDir); options.addOption(optLangTwoLetter); options.addOption(optConsoleLog); options.addOption(optDeveloperDebug); // Parser anlegen parser = new GnuParser(); try { cmdLine = parser.parse(options, args); if (cmdLine == null) { throw new Exception("can't build cmdline parser"); } } catch (ParseException e) { System.out.println(e.getLocalizedMessage()); System.exit(-1); } // // auswerten der Argumente // // // hilfe? // if (cmdLine.hasOption("help")) { HelpFormatter formatter = new HelpFormatter(); formatter.setWidth(120); formatter.printHelp(ProjectConst.CREATORPROGRAM, options); System.out.println("ENDE nach HELP..."); System.exit(0); } // // Loglevel // if (cmdLine.hasOption("loglevel")) { argument = cmdLine.getOptionValue("loglevel").toLowerCase(); // ALL | DEBU G | INFO | WARN | ERROR | FATAL | OFF if (argument.equalsIgnoreCase("all")) SpxPcloggerProgramConfig.logLevel = Level.ALL; else if (argument.equalsIgnoreCase("debug")) SpxPcloggerProgramConfig.logLevel = Level.DEBUG; else if (argument.equalsIgnoreCase("info")) SpxPcloggerProgramConfig.logLevel = Level.INFO; else if (argument.equalsIgnoreCase("warn")) SpxPcloggerProgramConfig.logLevel = Level.WARN; else if (argument.equalsIgnoreCase("error")) SpxPcloggerProgramConfig.logLevel = Level.ERROR; else if (argument.equalsIgnoreCase("fatal")) SpxPcloggerProgramConfig.logLevel = Level.FATAL; else if (argument.equalsIgnoreCase("off")) SpxPcloggerProgramConfig.logLevel = Level.OFF; else { // Ausgabe der Hilfe, wenn da was unverstndliches passierte System.err.println("unbekanntes Argument bei --loglevel <" + argument + ">"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(ProjectConst.CREATORPROGRAM, options); System.out.println("ENDE nach DEBUGLEVEL/HELP..."); System.exit(-1); } SpxPcloggerProgramConfig.wasCliLogLevel = true; } // // Logfile // if (cmdLine.hasOption("logfile")) { argument = cmdLine.getOptionValue("logfile"); File tempLogFile, tempParentDir; try { tempLogFile = new File(argument); tempParentDir = tempLogFile.getParentFile(); if (tempParentDir.exists() && tempParentDir.isDirectory()) { SpxPcloggerProgramConfig.logFile = tempLogFile; SpxPcloggerProgramConfig.wasCliLogfile = true; } } catch (NullPointerException ex) { System.err.println("logfile was <null>"); } } // // database Directory // if (cmdLine.hasOption("databasedir")) { argument = cmdLine.getOptionValue("databasedir"); File tempDataDir; try { tempDataDir = new File(argument); if (tempDataDir.exists() && tempDataDir.isDirectory()) { SpxPcloggerProgramConfig.databaseDir = tempDataDir; SpxPcloggerProgramConfig.wasCliDatabaseDir = true; } } catch (NullPointerException ex) { System.err.println("dataDir was <null>"); } } // // Export Directory // if (cmdLine.hasOption("exportdir")) { argument = cmdLine.getOptionValue("exportdir"); File tempExportDir; try { tempExportDir = new File(argument); if (tempExportDir.exists() && tempExportDir.isDirectory()) { SpxPcloggerProgramConfig.exportDir = tempExportDir; SpxPcloggerProgramConfig.wasCliExportDir = true; } } catch (NullPointerException ex) { System.err.println("dataDir was <null>"); } } // // Sprachcode (abweichend vom lokelen) // if (cmdLine.hasOption("langcode")) { argument = cmdLine.getOptionValue("langcode"); if (argument.length() >= 2) { SpxPcloggerProgramConfig.langCode = argument; SpxPcloggerProgramConfig.wasCliLangCode = true; } } // // Console // if (cmdLine.hasOption("console")) { SpxPcloggerProgramConfig.consoleLog = true; SpxPcloggerProgramConfig.wasCliConsoleLog = true; } // // Entwicklerdebug // if (cmdLine.hasOption("developer")) { SpxPcloggerProgramConfig.developDebug = true; } return (true); }
From source file:org.apache.eagle.storage.hbase.tools.CoprocessorTool.java
@Override public int run(String[] args) throws Exception { Options cmdOptions = new Options(); cmdOptions.addOption(new Option("register", false, "Register coprocessor")); cmdOptions.addOption(new Option("unregister", false, "Unregister coprocessor")); cmdOptions.addOption("table", true, "HBase table name, separated with comma, for example, table1,table2,.."); cmdOptions.addOption("jar", true, "Coprocessor target jar path"); cmdOptions.addOption("localJar", true, "Coprocessor local source jar path"); cmdOptions.addOption("config", true, "Configuration file"); cmdOptions.getOption("table").setType(String.class); cmdOptions.getOption("table").setRequired(true); cmdOptions.getOption("jar").setType(String.class); cmdOptions.getOption("jar").setRequired(false); cmdOptions.getOption("localJar").setType(String.class); cmdOptions.getOption("localJar").setRequired(false); cmdOptions.getOption("config").setType(String.class); cmdOptions.getOption("config").setRequired(false); GnuParser parser = new GnuParser(); CommandLine cmdCli = parser.parse(cmdOptions, args); String tableName = cmdCli.getOptionValue("table"); String configFile = cmdCli.getOptionValue("config"); if (configFile != null) { Configuration.addDefaultResource(configFile); }/*from www.j a v a 2s . c o m*/ if (cmdCli.hasOption("register")) { if (args.length < 3) { System.err.println("Error: coprocessor jar path is missing"); System.err.println("Usage: java " + CoprocessorTool.class.getName() + " enable " + tableName + " [jarOnHdfs] [jarOnLocal]"); return 1; } String jarPath = cmdCli.getOptionValue("jar"); LOGGER.info("Table name: {}", tableName); LOGGER.info("Coprocessor jar on hdfs: {}", jarPath); String localJarPath = cmdCli.getOptionValue("localJar"); LOGGER.info("Coprocessor jar on local: {}", localJarPath); String[] tableNames = tableName.split(",\\s*"); for (String table : tableNames) { LOGGER.info("Registering coprocessor for table {}", table); registerCoprocessor(jarPath, table, localJarPath); } } else if (cmdCli.hasOption("unregister")) { unregisterCoprocessor(tableName); } else { System.err.println("command is required, --register/--unregister"); printHelpMessage(cmdOptions); } return 0; }
From source file:org.apache.gora.goraci.Generator.java
@Override public int run(String[] args) throws Exception { Options options = new Options(); options.addOption("c", "concurrent", false, "update secondary table with information that allows verification to run concurrently"); GnuParser parser = new GnuParser(); CommandLine cmd = null;//from w w w . j a v a2 s. c o m try { cmd = parser.parse(options, args); if (cmd.getArgs().length != 2) { throw new ParseException("Did not see expected # of arguments, saw " + cmd.getArgs().length); } } catch (ParseException e) { LOG.error("Failed to parse command line {}", e.getMessage()); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(getClass().getSimpleName() + " <num mappers> <num nodes per map>", options); System.exit(-1); } int numMappers = Integer.parseInt(cmd.getArgs()[0]); long numNodes = Long.parseLong(cmd.getArgs()[1]); return run(numMappers, numNodes, cmd.hasOption("c")); }
From source file:org.apache.gora.goraci.Loop.java
@Override public int run(String[] args) throws Exception { Options options = new Options(); options.addOption("c", "concurrent", false, "run generation and verification and concurrently"); GnuParser parser = new GnuParser(); CommandLine cmd = null;//www . ja va 2s. c o m try { cmd = parser.parse(options, args); if (cmd.getArgs().length != 5) { throw new ParseException("Did not see expected # of arguments, saw " + cmd.getArgs().length); } } catch (ParseException e) { LOG.error("Failed to parse command line {}", e.getMessage()); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp( getClass().getSimpleName() + " <num iterations> <num mappers> <num nodes per mapper> <output dir> <num reducers>", options); System.exit(-1); } LOG.info("Running Loop with args:" + Arrays.deepToString(cmd.getArgs())); boolean concurrent = cmd.hasOption("c"); int numIterations = Integer.parseInt(cmd.getArgs()[0]); int numMappers = Integer.parseInt(cmd.getArgs()[1]); long numNodes = Long.parseLong(cmd.getArgs()[2]); String outputDir = cmd.getArgs()[3]; int numReducers = Integer.parseInt(cmd.getArgs()[4]); if (numNodes % Generator.WRAP != 0) { throw new RuntimeException("Number of node per mapper is not a multiple of " + String.format(Locale.getDefault(), "%,d", Generator.WRAP)); } long expectedNumNodes = 0; if (numIterations < 0) { numIterations = Integer.MAX_VALUE; //run indefinitely (kind of) } Verify verify = null; long verifyNodes = 0; for (int i = 0; i < numIterations; i++) { LOG.info("Starting iteration = {}", i); runGenerator(numMappers, numNodes, concurrent); expectedNumNodes += numMappers * numNodes; if (concurrent) { if (verify != null) { if (verify.isComplete()) { checkSuccess(verify, verifyNodes); verify = startVerify(outputDir, numReducers, true); verifyNodes = expectedNumNodes; } } else { verify = startVerify(outputDir, numReducers, true); verifyNodes = expectedNumNodes; } } else { runVerify(outputDir, numReducers, expectedNumNodes); } } if (verify != null) { verify.waitForCompletion(); checkSuccess(verify, verifyNodes); if (verifyNodes != expectedNumNodes) runVerify(outputDir, numReducers, expectedNumNodes); } return 0; }
From source file:org.apache.gora.goraci.Print.java
public int run(String[] args) throws Exception { Options options = new Options(); options.addOption("s", "start", true, "start key"); options.addOption("e", "end", true, "end key"); options.addOption("l", "limit", true, "number to print"); GnuParser parser = new GnuParser(); CommandLine cmd = null;//from w w w .j av a 2s .c om try { cmd = parser.parse(options, args); if (cmd.getArgs().length != 0) { throw new ParseException("Command takes no arguments"); } } catch (ParseException e) { LOG.error("Failed to parse command line {}", e.getMessage()); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(getClass().getSimpleName(), options); System.exit(-1); } DataStore<Long, CINode> store = DataStoreFactory.getDataStore(Long.class, CINode.class, new Configuration()); Query<Long, CINode> query = store.newQuery(); if (cmd.hasOption("s")) query.setStartKey(new BigInteger(cmd.getOptionValue("s"), 16).longValue()); if (cmd.hasOption("e")) query.setEndKey(new BigInteger(cmd.getOptionValue("e"), 16).longValue()); if (cmd.hasOption("l")) query.setLimit(Integer.parseInt(cmd.getOptionValue("l"))); else query.setLimit(100); Result<Long, CINode> rs = store.execute(query); while (rs.next()) { CINode node = rs.get(); LOG.info("%016x:%016x:%012d:%s\n {} {} {} {}", new Object[] { rs.getKey(), node.getPrev(), node.getCount(), node.getClient() }); } store.close(); return 0; }
From source file:org.apache.gora.goraci.Verify.java
@Override public int run(String[] args) throws Exception { Options options = new Options(); options.addOption("c", "concurrent", false, "run concurrently with generation"); GnuParser parser = new GnuParser(); CommandLine cmd = null;/*w w w . j a va 2 s . co m*/ try { cmd = parser.parse(options, args); if (cmd.getArgs().length != 2) { throw new ParseException("Did not see expected # of arguments, saw " + cmd.getArgs().length); } } catch (ParseException e) { LOG.error("Failed to parse command line {}", e.getMessage()); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(getClass().getSimpleName() + " <output dir> <num reducers>", options); System.exit(-1); } String outputDir = cmd.getArgs()[0]; int numReducers = Integer.parseInt(cmd.getArgs()[1]); return run(outputDir, numReducers, cmd.hasOption("c")); }
From source file:org.apache.gora.goraci.Walker.java
public int run(String[] args) throws IOException { Options options = new Options(); options.addOption("n", "num", true, "number of queries"); GnuParser parser = new GnuParser(); CommandLine cmd = null;/*w ww .j a v a 2s.c om*/ try { cmd = parser.parse(options, args); if (cmd.getArgs().length != 0) { throw new ParseException("Command takes no arguments"); } } catch (ParseException e) { LOG.error("Failed to parse command line {}", e.getMessage()); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(getClass().getSimpleName(), options); System.exit(-1); } long maxQueries = Long.MAX_VALUE; if (cmd.hasOption('n')) { maxQueries = Long.parseLong(cmd.getOptionValue("n")); } DataStore<Long, CINode> store = DataStoreFactory.getDataStore(Long.class, CINode.class, new Configuration()); Random rand = new Random(); long numQueries = 0; while (numQueries < maxQueries) { CINode node = findStartNode(rand, store); numQueries++; while (node != null && node.getPrev() >= 0 && numQueries < maxQueries) { long prev = node.getPrev(); long t1 = System.currentTimeMillis(); node = store.get(prev, PREV_FIELD); long t2 = System.currentTimeMillis(); LOG.info("CQ %d %016x \n {}", new Object[] { t2 - t1, prev }); numQueries++; t1 = System.currentTimeMillis(); node = store.get(prev, PREV_FIELD); t2 = System.currentTimeMillis(); LOG.info("HQ %d %016x \n {}", new Object[] { t2 - t1, prev }); numQueries++; } } store.close(); return 0; }
From source file:org.apache.wink.example.googledocs.CLIHelper.java
public void init(String[] args) throws ParseException { GnuParser parser = new GnuParser(); commandLine = parser.parse(options, args); boolean hasHostOption = commandLine.hasOption(PROXY_HOST_ORT); boolean hasPortOption = commandLine.hasOption(PROXY_PORT_OPT); if (hasHostOption && !hasPortOption) { throw new ParseException("Proxy host was specified, but proxy port was not."); }/* w ww . ja v a 2 s . c om*/ if (!hasHostOption && hasPortOption) { throw new ParseException("Proxy port was specified, but proxy host was not."); } if (hasHostOption && hasPortOption) { hasProxy = true; } }
From source file:org.cellcore.code.exec.AbstractExec.java
protected final void execute(String[] args) { GnuParser parser = new GnuParser(); Options options = new Options(); for (Option option : getOptions()) { options.addOption(option);// w ww . ja v a 2s. com } options.addOption(new Option("h", "help", false, "display this menu")); try { CommandLine commandLine = parser.parse(options, args); if (commandLine.hasOption("help")) { displayHelp(options); return; } displayArgs(args); execute(commandLine); displayMemoryUsageAndExit(); } catch (ParseException e) { displayHelp(options); } }
From source file:org.dspace.eperson.EPerson.java
/** Command to create an EPerson. */ private static int cmdAdd(Context context, String[] argv) { Options options = new Options(); options.addOption(VERB_ADD);//from www .j av a2 s. c o m final OptionGroup identityOptions = new OptionGroup(); identityOptions.addOption(OPT_EMAIL); identityOptions.addOption(OPT_NETID); options.addOptionGroup(identityOptions); options.addOption(OPT_GIVENNAME); options.addOption(OPT_SURNAME); options.addOption(OPT_PHONE); options.addOption(OPT_LANGUAGE); options.addOption(OPT_REQUIRE_CERTIFICATE); Option option = new Option("p", "password", true, "password to match the EPerson name"); options.addOption(option); options.addOption("h", "help", false, "explain --add options"); // Rescan the command for more details. GnuParser parser = new GnuParser(); CommandLine command; try { command = parser.parse(options, argv); } catch (ParseException e) { System.err.println(e.getMessage()); return 1; } if (command.hasOption('h')) { new HelpFormatter().printHelp("user --add [options]", options); return 0; } // Check that we got sufficient credentials to define a user. if ((!command.hasOption(OPT_EMAIL.getOpt())) && (!command.hasOption(OPT_NETID.getOpt()))) { System.err.println("You must provide an email address or a netid to identify the new user."); return 1; } if (!command.hasOption('p')) { System.err.println("You must provide a password for the new user."); return 1; } // Create! EPerson eperson = null; try { eperson = create(context); } catch (SQLException ex) { context.abort(); System.err.println(ex.getMessage()); return 1; } catch (AuthorizeException ex) { /* XXX SNH */ } eperson.setCanLogIn(true); eperson.setSelfRegistered(false); eperson.setEmail(command.getOptionValue(OPT_EMAIL.getOpt())); eperson.setFirstName(command.getOptionValue(OPT_GIVENNAME.getOpt())); eperson.setLastName(command.getOptionValue(OPT_SURNAME.getOpt())); eperson.setLanguage(command.getOptionValue(OPT_LANGUAGE.getOpt(), Locale.getDefault().getLanguage())); eperson.setMetadata("phone", command.getOptionValue(OPT_PHONE.getOpt())); eperson.setNetid(command.getOptionValue(OPT_NETID.getOpt())); eperson.setPassword(command.getOptionValue('p')); if (command.hasOption(OPT_REQUIRE_CERTIFICATE.getOpt())) { eperson.setRequireCertificate( Boolean.valueOf(command.getOptionValue(OPT_REQUIRE_CERTIFICATE.getOpt()))); } else { eperson.setRequireCertificate(false); } try { eperson.update(); context.commit(); System.out.printf("Created EPerson %d\n", eperson.getID()); } catch (SQLException ex) { context.abort(); System.err.println(ex.getMessage()); return 1; } catch (AuthorizeException ex) { /* XXX SNH */ } return 0; }