List of usage examples for org.apache.commons.cli ParseException getLocalizedMessage
public String getLocalizedMessage()
From source file:com.mapd.utility.SQLImporter.java
void doWork(String[] args) { // create Options object Options options = new Options(); // add r option options.addOption("r", true, "Row Load Limit"); Option driver = Option.builder("d").hasArg().desc("JDBC driver class").longOpt("driver").build(); Option sqlStmt = Option.builder("ss").hasArg().desc("SQL Select statement").longOpt("sqlStmt").required() .build();//from w w w . j av a 2 s . c om Option jdbcConnect = Option.builder("c").hasArg().desc("JDBC Connection string").longOpt("jdbcConnect") .required().build(); Option user = Option.builder("u").hasArg().desc("MapD User").longOpt("user").build(); Option sourceUser = Option.builder("su").hasArg().desc("Source User").longOpt("sourceUser").required() .build(); Option sourcePasswd = Option.builder("sp").hasArg().desc("Source Password").longOpt("sourcePasswd") .required().build(); Option passwd = Option.builder("p").hasArg().desc("MapD Password").longOpt("passwd").build(); Option server = Option.builder("s").hasArg().desc("MapD Server").longOpt("server").build(); Option targetTable = Option.builder("t").hasArg().desc("MapD Target Table").longOpt("targetTable") .required().build(); Option port = Option.builder().hasArg().desc("MapD Port").longOpt("port").build(); Option bufferSize = Option.builder("b").hasArg().desc("transfer buffer size").longOpt("bufferSize").build(); Option fragmentSize = Option.builder("f").hasArg().desc("table fragment size").longOpt("fragmentSize") .build(); Option database = Option.builder("db").hasArg().desc("MapD Database").longOpt("database").build(); Option truncate = Option.builder("tr").desc("Truncate table if it exists").longOpt("truncate").build(); options.addOption(driver); options.addOption(sqlStmt); options.addOption(jdbcConnect); options.addOption(user); options.addOption(server); options.addOption(passwd); options.addOption(port); options.addOption(sourceUser); options.addOption(sourcePasswd); options.addOption(targetTable); options.addOption(database); options.addOption(bufferSize); options.addOption(fragmentSize); options.addOption(truncate); CommandLineParser parser = new DefaultParser(); try { cmd = parser.parse(options, args); } catch (ParseException ex) { LOGGER.error(ex.getLocalizedMessage()); help(options); exit(0); } executeQuery(); }
From source file:com.github.errantlinguist.latticevisualiser.ArgParser.java
/** * /*from w ww . j av a 2 s. co m*/ * @param args * The command-line arguments. * @throws IOException * If the given input path for a non-word label file does not * refer to a valid file or another I/O error occurs. * @throws com.github.errantlinguist.parsers.ParseException * If there is an error parsing the contents of a given input * non-word label file path. */ public void parseArgs(final String[] args) { CommandLine cl = null; try { // parse the command line arguments cl = OPTION_PARSER.parse(OPTIONS, args); } catch (final ParseException e) { System.out.println(e.getLocalizedMessage()); notifyBadArgs(); } final String latticeInfilePath = cl.getOptionValue(LATTICE_INFILE_KEY); latticeInfile = new File(latticeInfilePath); if (!latticeInfile.exists()) { System.err.println("Invalid path: " + latticeInfilePath); notifyBadArgs(); } windowDimension = parseDimensionArgs(cl); if (cl.hasOption(STATE_SIZE_MULTIPLIER_KEY)) { stateSizeMultiplier = Double.parseDouble(cl.getOptionValue(STATE_SIZE_MULTIPLIER_KEY)); } else { stateSizeMultiplier = DEFAULT_STATE_SIZE_MULTIPLIER; } if (cl.hasOption(MIN_STATE_SIZE_KEY)) { minStateSize = Integer.parseInt(cl.getOptionValue(MIN_STATE_SIZE_KEY)); } else { minStateSize = DEFAULT_MIN_STATE_SIZE; } if (cl.hasOption(NONWORD_INFILE_KEY)) { final String infilePath = cl.getOptionValue(NONWORD_INFILE_KEY); nonwordsInfile = new File(infilePath); } }
From source file:dk.alexandra.fresco.framework.configuration.CmdLineUtil.java
public CommandLine parse(String[] args) { try {//from ww w .j a v a 2s . c om CommandLineParser parser = new DefaultParser(); Options helpOpt = new Options(); helpOpt.addOption(Option.builder("h").desc("Displays this help message").longOpt("help").required(false) .hasArg(false).build()); cmd = parser.parse(helpOpt, args, true); if (cmd.hasOption("h")) { displayHelp(); System.exit(0); } Options allOpts = new Options(); for (Option o : options.getOptions()) { allOpts.addOption(o); } for (Option o : appOptions.getOptions()) { allOpts.addOption(o); } cmd = parser.parse(allOpts, args); validateStandardOptions(); // TODO: Do this without hardcoding the protocol suite names here. switch (this.sceConf.getProtocolSuiteName()) { case "bgw": this.psConf = BgwConfiguration.fromCmdLine(this.sceConf, cmd); break; case "dummy": this.psConf = DummyConfiguration.fromCmdLine(this.sceConf, cmd); break; case "spdz": this.psConf = SpdzConfiguration.fromCmdLine(this.sceConf, cmd); break; case "tinytablesprepro": this.psConf = TinyTablesPreproConfiguration.fromCmdLine(this.sceConf, cmd); break; case "tinytables": this.psConf = TinyTablesConfiguration.fromCmdLine(this.sceConf, cmd); break; default: throw new ParseException( "Unknown protocol suite: " + this.getSCEConfiguration().getProtocolSuiteName()); } } catch (ParseException e) { System.out.println("Error while parsing arguments: " + e.getLocalizedMessage()); System.out.println(); displayHelp(); System.exit(-1); // TODO: Consider moving to top level. } return this.cmd; }
From source file:net.nicholaswilliams.java.licensing.licensor.interfaces.cli.ConsoleRSAKeyPairGenerator.java
protected void processCommandLineOptions(String[] arguments) { Options firstParseOptions = new Options(); firstParseOptions.addOption(HELP).addOption(INTERACTIVE).addOption(GENERATE_CLASSES); Options options = new Options(); options.addOption(HELP).addOption(INTERACTIVE).addOption(GENERATE_CLASSES).addOption(PRIVATE_FILE) .addOption(PRIVATE_PACKAGE).addOption(PUBLIC_FILE).addOption(PUBLIC_PACKAGE).addOption(PASSWORD) .addOption(PASSWORD_CLASS).addOption(PASSWORD_PACKAGE).addOption(PRIVATE_PASSWORD) .addOption(PRIVATE_PASSWORD_CLASS).addOption(PRIVATE_PASSWORD_PACKAGE); try {// www . j a v a 2 s .co m this.cli = this.cliParser.parse(firstParseOptions, arguments, true); if (this.cli.hasOption("help")) { HelpFormatter formatter = new HelpFormatter(); this.printHelp(formatter, options); this.device.exit(0); } else if (this.cli.hasOption("interactive")) { this.cli = null; this.interactive = true; } else { this.cli = this.cliParser.parse(options, arguments); } } catch (ParseException e) { this.device.printErrLn(e.getLocalizedMessage()); HelpFormatter formatter = new HelpFormatter(); this.printHelp(formatter, options); this.device.exit(1); } }
From source file:it.flavianopetrocchi.jpdfbookmarks.JPdfBookmarks.java
/** * Sets the mode by the command line arguments and initializes files to * process if passed as arguments./*from w w w .j ava2s . c o m*/ * * @param args Arguments to process */ private void setModeByCommandLine(String[] args) { Prefs userPrefs = new Prefs(); CommandLineParser parser = new PosixParser(); try { CommandLine cmd = parser.parse(options, args); if (cmd.hasOption('h')) { mode = Mode.HELP; } else if (cmd.hasOption('v')) { mode = Mode.VERSION; } else if (cmd.hasOption('w')) { mode = Mode.SHOW_ON_OPEN; showOnOpenArg = cmd.getOptionValue('w'); if (cmd.hasOption('o')) { outputFilePath = cmd.getOptionValue('o'); } else { outputFilePath = null; } } else if (cmd.hasOption('a')) { mode = Mode.APPLY; bookmarksFilePath = cmd.getOptionValue('a'); } else if (cmd.hasOption('d')) { mode = Mode.DUMP; } else { mode = Mode.GUI; if (cmd.hasOption('b')) { firstTargetString = cmd.getOptionValue('b'); } } if (cmd.hasOption('o')) { outputFilePath = cmd.getOptionValue('o'); } else { outputFilePath = null; } String[] leftOverArgs = cmd.getArgs(); if (leftOverArgs.length > 0) { inputFilePath = leftOverArgs[0]; } else if (mode == Mode.DUMP || mode == Mode.APPLY) { throw new ParseException(Res.getString("ERR_NO_INPUT_FILE")); } if (cmd.hasOption("p")) { pageSeparator = cmd.getOptionValue("p"); } else { pageSeparator = userPrefs.getPageSeparator(); } if (cmd.hasOption("i")) { indentationString = cmd.getOptionValue("i"); } else { indentationString = userPrefs.getIndentationString(); } if (cmd.hasOption("t")) { attributesSeparator = cmd.getOptionValue("t"); } else { attributesSeparator = userPrefs.getAttributesSeparator(); } if (cmd.hasOption("f")) { silentMode = true; } if (cmd.hasOption("e")) { charset = cmd.getOptionValue("e"); if (!Charset.isSupported(charset)) { throw new ParseException(Res.getString("ERR_CHARSET_NOT_SUPPORTED")); } } if (pageSeparator.equals(indentationString) || pageSeparator.equals(attributesSeparator) || indentationString.equals(attributesSeparator)) { throw new ParseException(Res.getString("ERR_OPTIONS_CONTRAST")); } } catch (ParseException ex) { mode = Mode.GUI; err.println(ex.getLocalizedMessage()); System.exit(1); } }
From source file:net.nicholaswilliams.java.licensing.licensor.interfaces.cli.ConsoleLicenseGenerator.java
protected void processCommandLineOptions(String[] arguments) { Options firstParseOptions = new Options(); firstParseOptions.addOption(HELP);// ww w . ja v a 2 s. c o m Options options = new Options(); options.addOption(HELP).addOption(CONFIG).addOption(LICENSE); try { this.cli = this.cliParser.parse(firstParseOptions, arguments, true); if (this.cli.hasOption("help")) { HelpFormatter formatter = new HelpFormatter(); this.printHelp(formatter, options); this.device.exit(0); } else { this.cli = this.cliParser.parse(options, arguments); } } catch (ParseException e) { this.device.printErrLn(e.getLocalizedMessage()); HelpFormatter formatter = new HelpFormatter(); this.printHelp(formatter, options); this.device.exit(1); } }
From source file:biomine.bmvis2.Vis.java
private void createGUI(String title) { // try { // System.setProperty("com.apple.macosx.AntiAliasedTextOn", "false"); // System.setProperty("com.apple.macosx.AntiAliasedGraphicsOn", // "false"); // } catch (Throwable t) { // // Ignore property exceptions // }/*from w w w .java2 s. co m*/ // try { // System.setProperty("sun.java2d.opengl", "true"); // } catch (Throwable t) { // // Ignore property exceptions // } this.setLayout(new GridLayout()); this.tabs = new TabbedPaneHiddenBar(); this.getContentPane().add(tabs); this.tabs.setVisible(true); tabs.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent arg0) { GraphTab tab = (GraphTab) tabs.getSelectedComponent(); if (tab == null) { Logging.info("ui", "No graphs open, creating the default menu."); Vis.this.setJMenuBar(getDefaultMenu()); } else { Vis.this.setJMenuBar(tab.getMenuBar()); } } }); if (appletContext == null) { Options opts = new Options(); CommandLineParser parser = new PosixParser(); CommandLine cmd = null; opts.addOption("h", "help", false, "Show help."); opts.addOption("s", "simple", false, "Show simple UI without side panes"); opts.addOption("logcategories", true, "Logging categories delimited by spaces, all for all"); opts.addOption("loglevel", true, "Logging level: 0 for debug, 1 for info, 2 for warning, 3 for error"); opts.addOption("d", "debug", false, "Shorthand for logcategories all, loglevel -1"); try { cmd = parser.parse(opts, args); } catch (ParseException e) { System.err.println(e.getLocalizedMessage()); System.err.println(); Vis.printCmdLineHelp(opts); System.exit(1); } if (cmd.hasOption("-h") || cmd.getArgList().size() == 0) { Vis.printCmdLineHelp(opts); System.exit(0); } if (cmd.hasOption("-s")) this.properties.put("simple", "true"); if (cmd.hasOption("-d")) { Logging.init(new ArrayList<String>(Arrays.asList("all")), -1); } else { ArrayList<String> logCategories = null; Integer logLevel = null; if (cmd.hasOption("logcategories")) logCategories = new ArrayList<String>( Arrays.asList(cmd.getOptionValue("logcategories").split(","))); if (cmd.hasOption("loglevel")) logLevel = Integer.parseInt(cmd.getOptionValue("loglevel")); if (logCategories != null || logLevel != null) Logging.init(logCategories, logLevel); } VisFrame frame = new VisFrame("BMVIS II"); this.visFrame = frame; frame.add(this); boolean noneOpened = true; for (Object arg : cmd.getArgList()) { if (this.openTab((String) arg) != null) noneOpened = false; } if (noneOpened && cmd.getArgList().size() > 0) { String message = "No files could be opened! Exiting."; Logging.error("graph_reading", message); JOptionPane.showMessageDialog(this, message); System.exit(1); } this.visFrame.setVisible(true); } else { // Applet operation goes here... this.setVisible(true); try { if (getParameter("graph") != null) { String graphFile = getParameter("graph"); URL u = new URL(getCodeBase(), graphFile); InputStream graphStream = u.openConnection().getInputStream(); BMGraph bm = BMGraphUtils.readBMGraph(graphStream); graphStream.close(); this.openTab(new FileGraphSource(bm)); } if (getParameter("json") != null) { String jsonFile = getParameter("json"); URL u = new URL(getCodeBase(), jsonFile); InputStream jsonStream = u.openConnection().getInputStream(); openJSONTab(StreamToString.convertStreamToString(jsonStream), jsonFile); } } catch (IOException e) { Logging.error("graph_reading", e.toString()); JOptionPane.showMessageDialog(this, e.getMessage()); } } }
From source file:com.diablominer.DiabloMiner.DiabloMiner.java
void execute(String[] args) throws Exception { threads.add(Thread.currentThread()); Options options = new Options(); options.addOption("u", "user", true, "bitcoin host username"); options.addOption("p", "pass", true, "bitcoin host password"); options.addOption("o", "host", true, "bitcoin host IP"); options.addOption("r", "port", true, "bitcoin host port"); options.addOption("l", "url", true, "bitcoin host url"); options.addOption("x", "proxy", true, "optional proxy settings IP:PORT<:username:password>"); options.addOption("g", "worklifetime", true, "maximum work lifetime in seconds"); options.addOption("d", "debug", false, "enable debug output"); options.addOption("dt", "debugtimer", false, "run for 1 minute and quit"); options.addOption("D", "devices", true, "devices to enable, default all"); options.addOption("f", "fps", true, "target GPU execution timing"); options.addOption("na", "noarray", false, "turn GPU kernel array off"); options.addOption("v", "vectors", true, "vector size in GPU kernel"); options.addOption("w", "worksize", true, "override GPU worksize"); options.addOption("ds", "ksource", false, "output GPU kernel source and quit"); options.addOption("h", "help", false, "this help"); PosixParser parser = new PosixParser(); CommandLine line = null;// ww w . j a va 2s .c o m try { line = parser.parse(options, args); if (line.hasOption("help")) { throw new ParseException(""); } } catch (ParseException e) { System.out.println(e.getLocalizedMessage() + "\n"); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("DiabloMiner -u myuser -p mypassword [args]\n", "", options, "\nRemember to set rpcuser and rpcpassword in your ~/.bitcoin/bitcoin.conf " + "before starting bitcoind or bitcoin --daemon"); return; } String splitUrl[] = null; String splitUser[] = null; String splitPass[] = null; String splitHost[] = null; String splitPort[] = null; if (line.hasOption("url")) splitUrl = line.getOptionValue("url").split(","); if (line.hasOption("user")) splitUser = line.getOptionValue("user").split(","); if (line.hasOption("pass")) splitPass = line.getOptionValue("pass").split(","); if (line.hasOption("host")) splitHost = line.getOptionValue("host").split(","); if (line.hasOption("port")) splitPort = line.getOptionValue("port").split(","); int networkStatesCount = 0; if (splitUrl != null) networkStatesCount = splitUrl.length; if (splitUser != null) networkStatesCount = Math.max(splitUser.length, networkStatesCount); if (splitPass != null) networkStatesCount = Math.max(splitPass.length, networkStatesCount); if (splitHost != null) networkStatesCount = Math.max(splitHost.length, networkStatesCount); if (splitPort != null) networkStatesCount = Math.max(splitPort.length, networkStatesCount); if (networkStatesCount == 0) { error("You forgot to give any bitcoin connection info, please add either -l, or -u -p -o and -r"); System.exit(-1); } int j = 0; for (int i = 0; j < networkStatesCount; i++, j++) { String protocol = "http"; String host = "localhost"; int port = 8332; String path = "/"; String user = "diablominer"; String pass = "diablominer"; byte hostChain = 0; if (splitUrl != null && splitUrl.length > i) { String[] usernameFix = splitUrl[i].split("@", 3); if (usernameFix.length > 2) splitUrl[i] = usernameFix[0] + "+++++" + usernameFix[1] + "@" + usernameFix[2]; URL url = new URL(splitUrl[i]); if (url.getProtocol() != null && url.getProtocol().length() > 1) protocol = url.getProtocol(); if (url.getHost() != null && url.getHost().length() > 1) host = url.getHost(); if (url.getPort() != -1) port = url.getPort(); if (url.getPath() != null && url.getPath().length() > 1) path = url.getPath(); if (url.getUserInfo() != null && url.getUserInfo().length() > 1) { String[] userPassSplit = url.getUserInfo().split(":"); user = userPassSplit[0].replace("+++++", "@"); if (userPassSplit.length > 1 && userPassSplit[1].length() > 1) pass = userPassSplit[1]; } } if (splitUser != null && splitUser.length > i) user = splitUser[i]; if (splitPass != null && splitPass.length > i) pass = splitPass[i]; if (splitHost != null && splitHost.length > i) host = splitHost[i]; if (splitPort != null && splitPort.length > i) port = Integer.parseInt(splitPort[i]); NetworkState networkState; try { networkState = new JSONRPCNetworkState(this, new URL(protocol, host, port, path), user, pass, hostChain); } catch (MalformedURLException e) { throw new DiabloMinerFatalException(this, "Malformed connection paramaters"); } if (networkStateHead == null) { networkStateHead = networkStateTail = networkState; } else { networkStateTail.setNetworkStateNext(networkState); networkStateTail = networkState; } } networkStateTail.setNetworkStateNext(networkStateHead); if (line.hasOption("proxy")) { final String[] proxySettings = line.getOptionValue("proxy").split(":"); if (proxySettings.length >= 2) { proxy = new Proxy(Type.HTTP, new InetSocketAddress(proxySettings[0], Integer.valueOf(proxySettings[1]))); } if (proxySettings.length >= 3) { Authenticator.setDefault(new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(proxySettings[2], proxySettings[3].toCharArray()); } }); } } if (line.hasOption("worklifetime")) workLifetime = Integer.parseInt(line.getOptionValue("worklifetime")) * 1000; if (line.hasOption("debug")) debug = true; if (line.hasOption("debugtimer")) { debugtimer = true; } if (line.hasOption("devices")) { String devices[] = line.getOptionValue("devices").split(","); enabledDevices = new HashSet<String>(); for (String s : devices) { enabledDevices.add(s); if (Integer.parseInt(s) == 0) { error("Do not use 0 with -D, devices start at 1"); System.exit(-1); } } } if (line.hasOption("fps")) { GPUTargetFPS = Float.parseFloat(line.getOptionValue("fps")); if (GPUTargetFPS < 0.1) { error("--fps argument is too low, adjusting to 0.1"); GPUTargetFPS = 0.1; } } if (line.hasOption("noarray")) { GPUNoArray = true; } if (line.hasOption("worksize")) GPUForceWorkSize = Integer.parseInt(line.getOptionValue("worksize")); if (line.hasOption("vectors")) { String tempVectors[] = line.getOptionValue("vectors").split(","); GPUVectors = new Integer[tempVectors.length]; try { for (int i = 0; i < GPUVectors.length; i++) { GPUVectors[i] = Integer.parseInt(tempVectors[i]); if (GPUVectors[i] > 16) { error("DiabloMiner now uses comma-seperated vector layouts, use those instead"); System.exit(-1); } else if (GPUVectors[i] != 1 && GPUVectors[i] != 2 && GPUVectors[i] != 3 && GPUVectors[i] != 4 && GPUVectors[i] != 8 && GPUVectors[i] != 16) { error(GPUVectors[i] + " is not a vector length of 1, 2, 3, 4, 8, or 16"); System.exit(-1); } } Arrays.sort(GPUVectors, Collections.reverseOrder()); } catch (NumberFormatException e) { error("Cannot parse --vector argument(s)"); System.exit(-1); } } else { GPUVectors = new Integer[1]; GPUVectors[0] = 1; } if (line.hasOption("ds")) GPUDebugSource = true; info("Started"); StringBuilder list = new StringBuilder(networkStateHead.getQueryUrl().toString()); NetworkState networkState = networkStateHead.getNetworkStateNext(); while (networkState != networkStateHead) { list.append(", " + networkState.getQueryUrl()); networkState = networkState.getNetworkStateNext(); } info("Connecting to: " + list); long previousHashCount = 0; double previousAdjustedHashCount = 0.0; long previousAdjustedStartTime = startTime = (now()) - 1; StringBuilder hashMeter = new StringBuilder(80); Formatter hashMeterFormatter = new Formatter(hashMeter); int deviceCount = 0; List<List<? extends DeviceState>> allDeviceStates = new ArrayList<List<? extends DeviceState>>(); List<? extends DeviceState> GPUDeviceStates = new GPUHardwareType(this).getDeviceStates(); deviceCount += GPUDeviceStates.size(); allDeviceStates.add(GPUDeviceStates); while (running.get()) { for (List<? extends DeviceState> deviceStates : allDeviceStates) { for (DeviceState deviceState : deviceStates) { deviceState.checkDevice(); } } long now = now(); long currentHashCount = hashCount.get(); double adjustedHashCount = (double) (currentHashCount - previousHashCount) / (double) (now - previousAdjustedStartTime); double hashLongCount = (double) currentHashCount / (double) (now - startTime) / 1000.0; if (now - startTime > TIME_OFFSET * 2) { double averageHashCount = (adjustedHashCount + previousAdjustedHashCount) / 2.0 / 1000.0; hashMeter.setLength(0); if (!debug) { hashMeterFormatter.format("\rmhash: %.1f/%.1f | accept: %d | reject: %d | hw error: %d", averageHashCount, hashLongCount, blocks.get(), rejects.get(), hwErrors.get()); } else { hashMeterFormatter.format("\rmh: %.1f/%.1f | a/r/hwe: %d/%d/%d | gh: ", averageHashCount, hashLongCount, blocks.get(), rejects.get(), hwErrors.get()); double basisAverage = 0.0; for (List<? extends DeviceState> deviceStates : allDeviceStates) { for (DeviceState deviceState : deviceStates) { hashMeterFormatter.format("%.1f ", deviceState.getDeviceHashCount() / 1000.0 / 1000.0 / 1000.0); basisAverage += deviceState.getBasis(); } } basisAverage = 1000 / (basisAverage / deviceCount); hashMeterFormatter.format("| fps: %.1f", basisAverage); } System.out.print(hashMeter); } else { System.out.print("\rWaiting..."); } if (now() - TIME_OFFSET * 2 > previousAdjustedStartTime) { previousHashCount = currentHashCount; previousAdjustedHashCount = adjustedHashCount; previousAdjustedStartTime = now - 1; } if (debugtimer && now() > startTime + 60 * 1000) { System.out.print("\n"); info("Debug timer is up, quitting..."); System.exit(0); } try { if (now - startTime > TIME_OFFSET) Thread.sleep(1000); else Thread.sleep(1); } catch (InterruptedException e) { } } hashMeterFormatter.close(); }
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 2s . c o m*/ * @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:net.straylightlabs.tivolibre.DecoderApp.java
public boolean parseCommandLineArgs(String[] args) { try {/*from ww w . j av a2 s . c om*/ options = buildCliOptions(); CommandLineParser parser = new DefaultParser(); cli = parser.parse(options, args); } catch (ParseException e) { logger.error("Parsing command line options failed: {}", e.getLocalizedMessage()); showUsage(); return false; } return true; }