List of usage examples for org.apache.commons.cli HelpFormatter setWidth
public void setWidth(int width)
From source file:eu.stratosphere.client.CliFrontend.java
private void printHelpForList() { HelpFormatter formatter = new HelpFormatter(); formatter.setLeftPadding(5);//from w ww . ja v a 2 s. c o m formatter.setWidth(80); System.out.println("\nAction \"list\" lists running and finished programs."); formatter.setSyntaxPrefix(" \"list\" action arguments:"); formatter.printHelp(" ", getListOptions(new Options())); }
From source file:eu.stratosphere.client.CliFrontend.java
private void printHelpForCancel() { HelpFormatter formatter = new HelpFormatter(); formatter.setLeftPadding(5);/*from w ww . j a v a2 s . com*/ formatter.setWidth(80); System.out.println("\nAction \"cancel\" cancels a running program."); formatter.setSyntaxPrefix(" \"cancel\" action arguments:"); formatter.printHelp(" ", getCancelOptions(new Options())); }
From source file:eu.stratosphere.client.CliFrontend.java
private void printHelpForRun() { HelpFormatter formatter = new HelpFormatter(); formatter.setLeftPadding(5);/*from ww w . j a v a 2 s . c o m*/ formatter.setWidth(80); System.out.println("\nAction \"run\" compiles and runs a program."); System.out.println("\n Syntax: run [OPTIONS] <jar-file> <arguments>"); formatter.setSyntaxPrefix(" \"run\" action arguments:"); formatter.printHelp(" ", getRunOptionsWithoutDeprecatedOptions(new Options())); }
From source file:cycronix.ctudp.CTudp.java
public CTudp(String[] arg) { String[] chanName = new String[32]; String defaultChanName = "udpchan"; String[] csvChanNames = null; int ssNum[] = new int[32]; int defaultPort = 4445; double dt[] = new double[32]; double defaultDT = 0.0; int numChan = 0; // For communicating with UDP server; we send a "keep alive" heartbeat message to this server // and will receive UDP packets from this server DatagramSocket clientSocket = null; // This socket will be shared by UDPread and UDPHeartbeatTask classes InetAddress udpserverIP = null; int udpserverPort = -1; int heartbeatPeriod_msec = -1; boolean bCSVTest = false; // If the "-csvtest" option has been specified along with the "-udpserver" option, then the heartbeat message itself is a CSV string that can be used for testing CTudp in loopback mode. // Optional local UDP server that can be started to serve test data int testserverPort = -1; int testserverPeriod_msec = -1; ////from ww w . j a v a 2s .c o m // Argument processing using Apache Commons CLI // // 1. Setup command line options Options options = new Options(); options.addOption("h", "help", false, "Print this message."); options.addOption("pack", false, "Blocks of data should be packed? default = " + Boolean.toString(packMode) + "."); options.addOption(Option.builder("s").argName("source name").hasArg() .desc("Name of source to write packets to; default = \"" + srcName + "\".").build()); options.addOption(Option.builder("c").argName("channel name").hasArg() .desc("Name of channel to write packets to; default = \"" + defaultChanName + "\".").build()); options.addOption(Option.builder("csplit").argName("channel name(s)").hasArg().desc( "Comma-separated list of channel names; split an incoming CSV string into a series of channels with the given names; supported channel name suffixes and their associated data types: .txt (string), .csv or no suffix (numeric), .f32 (32-bit floating point), .f64 (64-bit floating point).") .build()); options.addOption(Option.builder("e").argName("exception val").hasArg().desc( "If a CSV string is being parsed (using the -csplit option) and there is an error saving a string component as a floating point value, use this \"exception value\" in its place; default = " + Double.toString(exceptionVal) + ".") .build()); options.addOption(Option.builder("m").argName("multicast address").hasArg() .desc("Multicast UDP address (224.0.0.1 to 239.255.255.255).").build()); options.addOption(Option.builder("p").argName("UDP port").hasArg() .desc("Port number to listen for UDP packets on; default = " + Integer.toString(defaultPort) + ".") .build()); options.addOption(Option.builder("d").argName("delta-Time").hasArg() .desc("Fixed delta-time (msec) between frames; specify 0 to use arrival-times; default = " + Double.toString(defaultDT) + ".") .build()); options.addOption(Option.builder("f").argName("autoFlush").hasArg().desc( "Flush interval (sec); amount of data per zipfile; default = " + Double.toString(autoFlush) + ".") .build()); options.addOption(Option.builder("t").argName("trim-Time").hasArg() .desc("Trim (ring-buffer loop) time (sec); specify 0 for indefinite; default = " + Double.toString(trimTime) + ".") .build()); options.addOption(Option.builder("udpserver").argName("IP,port,period_msec").hasArg().desc( "Talk to a UDP server; send a periodic keep-alive message to the given IP:port at the specified period and receive packets from this server; not to be used with the \"-p\" option.") .build()); options.addOption(Option.builder("testserver").argName("port,period_msec").hasArg().desc( "Start a UDP server on the local machine to serve CSV strings at the specified period with the format specified by the \"-csplit\" option (if no \"-csplit\" option has been specified, a simple text message is output). The test server waits for a message from the client before starting packet flow. This feature can be used along with the \"-udpserver\" option for local/loopback testing (NOTE: make sure the server ports match).") .build()); options.addOption(Option.builder("bps").argName("blocks_per_seg").hasArg() .desc("Number of blocks per segment; specify 0 for no segments; default = " + Long.toString(blocksPerSegment) + ".") .build()); options.addOption("w", false, "Split the captured string on white space rather than commas."); options.addOption("x", "debug", false, "Debug mode."); // 2. Parse command line options CommandLineParser parser = new DefaultParser(); CommandLine line = null; try { line = parser.parse(options, arg); } catch (ParseException exp) { // oops, something went wrong System.err.println("Command line argument parsing failed: " + exp.getMessage()); return; } // 3. Retrieve the command line values if (line.hasOption("help")) { // Display help message and quit HelpFormatter formatter = new HelpFormatter(); formatter.setWidth(120); formatter.printHelp("CTudp", options); return; } srcName = line.getOptionValue("s", srcName); String chanNameL = line.getOptionValue("c", defaultChanName); chanName = chanNameL.split(","); numChan = chanName.length; if (line.hasOption("csplit")) { chanNameL = line.getOptionValue("csplit"); csvChanNames = chanNameL.split(","); if (numChan > 1) { System.err.println( "Error: don't use the \"-csplit\" option when receiving packets from multiple UDP ports."); System.exit(0); } // Make sure that the channel names either have no suffix or will end in .txt, .csv, .f32, .f64 for (int i = 0; i < csvChanNames.length; ++i) { int dotIdx = csvChanNames[i].lastIndexOf('.'); if ((dotIdx > -1) && (!csvChanNames[i].endsWith(".txt")) && (!csvChanNames[i].endsWith(".csv")) && (!csvChanNames[i].endsWith(".f32")) && (!csvChanNames[i].endsWith(".f64"))) { System.err.println( "Error: illegal channel name specified in the \"-csplit\" list: " + csvChanNames[i]); System.err.println( "\tAccepted channel names: channels with no suffix or with .txt, .csv, .f32 or .f64 suffixes."); System.exit(0); } } } String exceptionValStr = line.getOptionValue("e", Double.toString(exceptionVal)); try { exceptionVal = Double.parseDouble(exceptionValStr); } catch (NumberFormatException nfe) { System.err.println("Error parsing the given exception value (\"-e\" flag)."); System.exit(0); } multiCast = line.getOptionValue("m", multiCast); String nss = line.getOptionValue("p", Integer.toString(defaultPort)); String[] ssnums = nss.split(","); numSock = ssnums.length; for (int i = 0; i < numSock; i++) ssNum[i] = Integer.parseInt(ssnums[i]); String sdt = line.getOptionValue("d", Double.toString(defaultDT)); String[] ssdt = sdt.split(","); for (int i = 0; i < ssdt.length; i++) dt[i] = Double.parseDouble(ssdt[i]); autoFlush = Double.parseDouble(line.getOptionValue("f", "" + autoFlush)); trimTime = Double.parseDouble(line.getOptionValue("t", Double.toString(trimTime))); blocksPerSegment = Long.parseLong(line.getOptionValue("bps", Long.toString(blocksPerSegment))); if (line.hasOption("pack")) { packMode = true; } bSplitOnWhiteSpace = line.hasOption("w"); debug = line.hasOption("debug"); // Parameters when talking to a UDP server // Can't specify both "-p" and "-udpserver" if (line.hasOption("p") && line.hasOption("udpserver")) { System.err.println( "Specify either \"-p\" (to listen on the given port(s)) or \"-udpserver\" (to talk to UDP server), not both."); System.exit(0); } if (line.hasOption("udpserver")) { String udpserverStr = line.getOptionValue("udpserver"); // Parse the server,port,period_msec from this string String[] udpserverConfigCSV = udpserverStr.split(","); if (udpserverConfigCSV.length != 3) { System.err.println( "Error: the \"-udpserver\" argument must contain 3 parameters: IP,port,period_msec"); System.exit(0); } try { udpserverIP = InetAddress.getByName(udpserverConfigCSV[0]); } catch (UnknownHostException e) { System.err.println("Error processing the \"-udpserver\" server name:\n" + e); System.exit(0); } try { udpserverPort = Integer.parseInt(udpserverConfigCSV[1]); if (udpserverPort <= 0) { throw new Exception("Invalid port number"); } } catch (Exception e) { System.err.println("Error: the \"-udpserver\" port must be an integer greater than 0."); System.exit(0); } try { heartbeatPeriod_msec = Integer.parseInt(udpserverConfigCSV[2]); if (heartbeatPeriod_msec <= 0) { throw new Exception("Invalid period"); } } catch (Exception e) { System.err.println("Error: the \"-udpserver\" period_msec must be an integer greater than 0."); System.exit(0); } } if (line.hasOption("testserver")) { String testserverStr = line.getOptionValue("testserver"); // Parse the port,period_msec from this string String[] testserverConfigCSV = testserverStr.split(","); if (testserverConfigCSV.length != 2) { System.err .println("Error: the \"-testserver\" argument must contain 2 parameters: port,period_msec"); System.exit(0); } try { testserverPort = Integer.parseInt(testserverConfigCSV[0]); if (testserverPort <= 0) { throw new Exception("Invalid port number"); } } catch (Exception e) { System.err.println("Error: the \"-testserver\" port must be an integer greater than 0."); System.exit(0); } try { testserverPeriod_msec = Integer.parseInt(testserverConfigCSV[1]); if (testserverPeriod_msec <= 0) { throw new Exception("Invalid period"); } } catch (Exception e) { System.err.println("Error: the \"-testserver\" period_msec must be an integer greater than 0."); System.exit(0); } } if (numSock != numChan) { System.err.println("Error: must specify same number of channels and ports!"); System.exit(0); } if (multiCast != null && numSock > 1) { System.err.println("Error: can only have one multicast socket!"); System.exit(0); } if (numSock == 0) numSock = 1; // use defaults System.err.println("Source name: " + srcName); if (udpserverIP == null) { for (int i = 0; i < numSock; i++) { System.err.println("Channel[" + i + "]: " + chanName[i]); System.err.println("UDPport[" + i + "]: " + ssNum[i]); } } if (csvChanNames != null) { System.err.println("\nIncoming csv strings will be split into the following channels:"); for (int i = 0; i < (csvChanNames.length - 1); ++i) { System.err.print(csvChanNames[i] + ","); } System.err.println(csvChanNames[csvChanNames.length - 1]); } // // If user has requested it, start the test UDP server // if (testserverPort > -1) { UDPserver svr = null; try { svr = new UDPserver(testserverPort, testserverPeriod_msec, csvChanNames); } catch (SocketException se) { System.err.println("Error: caught exception trying to start test server:\n" + se); System.exit(0); } svr.start(); } // // If user requested it, initialize communication with the UDP server // if (udpserverIP != null) { try { // This DatagramSocket will be shared by UDPread and UDPHeartbeatTask classes clientSocket = new DatagramSocket(); } catch (SocketException e) { System.err.println("Error creating DatagramSocket:\n" + e); System.exit(0); } Timer time = new Timer(); UDPHeartbeatTask heartbeatTask = new UDPHeartbeatTask(clientSocket, udpserverIP, udpserverPort); time.schedule(heartbeatTask, 0, heartbeatPeriod_msec); } // // setup CTwriter // try { ctw = new CTwriter(srcName, trimTime); ctw.setBlockMode(packMode, zipMode); CTinfo.setDebug(debug); ctw.autoSegment(blocksPerSegment); autoFlushMillis = (long) (autoFlush * 1000.); // ctw.autoFlush(autoFlush); // auto flush to zip once per interval (sec) of data } catch (Exception e) { e.printStackTrace(); System.exit(0); } // // start a thread for each port // if we are talking to a UDP server, there is only 1 instance of UDPread // if (clientSocket != null) { System.err.println("Talk to UDP server at " + udpserverIP + ":" + udpserverPort); new UDPread(clientSocket, chanName[0], csvChanNames, dt[0]).start(); } else { for (int i = 0; i < numSock; i++) { System.err.println("start thread for port: " + ssNum[i] + ", chan: " + chanName[i]); new UDPread(ssNum[i], chanName[i], csvChanNames, dt[i]).start(); } } }
From source file:erigo.filewatch.FileWatch.java
/** * Creates a WatchService and registers the given directory *//* w ww . ja va2s .c om*/ // FileWatch(Path watchDir, String outputFilename, Path outputDirI) throws IOException { FileWatch(String[] argsI) throws IOException { // // Parse command line arguments // // 1. Setup command line options // Options options = new Options(); // Boolean options (only the flag, no argument) options.addOption("h", "help", false, "Print this message."); options.addOption("a", "adjust_latency", false, "Divide latency results by 2 because test data files are from a recaster (round-trip)."); options.addOption("d", "disp_recaster", false, "Display results when operating in recaster mode."); // Command line options that include an argument Option nextOption = Option.builder("i").argName("watchdir").hasArg().desc( "Directory to watch for incoming test data files (must be an existing directory); default = \"" + DEFAULT_WATCH_DIR + "\".") .build(); options.addOption(nextOption); nextOption = Option.builder("o").argName("outfilename").hasArg() .desc("Name of the output metrics data file; must be a new file.").build(); options.addOption(nextOption); nextOption = Option.builder("p").argName("pollinterval_msec").hasArg().desc( "Watch for new files by polling (don't use Java WatchService); sleep for <pollinterval_msec> (milliseconds) between scans.") .build(); options.addOption(nextOption); nextOption = Option.builder("r").argName("recasterdir").hasArg() .desc("Recast test data files to the specified output directory (must be an existing directory).") .build(); options.addOption(nextOption); nextOption = Option.builder("t").argName("plottitle").hasArg() .desc("Custom title for throughput and latency plots.").build(); options.addOption(nextOption); // // 2. Parse command line options // CommandLineParser parser = new DefaultParser(); CommandLine line = null; try { line = parser.parse(options, argsI); } catch (ParseException exp) { // oops, something went wrong System.err.println("Command line argument parsing failed: " + exp.getMessage()); return; } // // 3. Retrieve the command line values // if (line.hasOption("h")) { // Display help message and quit HelpFormatter formatter = new HelpFormatter(); formatter.setWidth(100); formatter.printHelp("FileWatch", options); return; } bAdjustLatencyMetrics = line.hasOption("a"); bOutputResultsInRecastMode = line.hasOption("d"); // Watch directory String watchDirName = line.getOptionValue("i", DEFAULT_WATCH_DIR); Path watchDir = Paths.get(watchDirName); if (!watchDir.toFile().isDirectory()) { System.err.println("\nThe given watch directory does not exist."); System.exit(-1); } // Recaster directory Path outputDirPath = null; String outputDirName = line.getOptionValue("r"); if (outputDirName != null) { outputDirPath = Paths.get(outputDirName); if (!outputDirPath.toFile().isDirectory()) { System.err.println("\nThe given recaster output directory does not exist."); System.exit(-1); } // Make sure watchDir and outputDir aren't the same if (watchDir.toAbsolutePath().compareTo(outputDirPath.toAbsolutePath()) == 0) { System.err.println("\nThe recaster output directory cannot be the same as the watch directory."); System.exit(-1); } bRecast = true; outputDir = outputDirPath.toFile(); } // Output filename String outputFilename = line.getOptionValue("o"); if ((outputFilename == null) && (!bRecast || bOutputResultsInRecastMode)) { System.err.println("\nMust specify the name of the output data file."); System.exit(-1); } if (outputFilename != null) { File outputFile = new File(outputFilename); if (outputFile.isDirectory()) { System.err.println( "\nThe given output data file is the name of a directory; must specify an output filename."); System.exit(-1); } else if (outputFile.isFile()) { System.err.println( "\nThe given output data file is the name of an existing file; must specify a new filename."); System.exit(-1); } } // Use polling to check for new files? String pollIntervalStr = line.getOptionValue("p"); if (pollIntervalStr != null) { try { pollInterval = Integer.parseInt(pollIntervalStr); if ((pollInterval <= 0) || (pollInterval > 1000)) { throw new NumberFormatException("Illegal value"); } } catch (NumberFormatException nfe) { System.err.println("\nPoll interval must be an integer in the range 0 < x <= 1000"); System.exit(-1); } } // Title for the throughput and latency plots customPlotTitle = line.getOptionValue("t", ""); // Make sure "end.txt" doesn't already exist in the directory; this file is our signal // that we're done processing File endFile = new File(watchDir.toFile(), "end.txt"); if (endFile.exists()) { System.err.println("\nMust delete \"" + endFile + "\" before running test."); System.exit(-1); } // If we are recasting, make sure "end.txt" doesn't exist in the output directory either if (outputDirPath != null) { endFile = new File(outputDirPath.toFile(), "end.txt"); if (endFile.exists()) { System.err.println("\nMust delete \"" + endFile + "\" in output directory before running test."); System.exit(-1); } } if (pollInterval > 0) { System.err .println("\nWatching directory \"" + watchDir + "\" for incoming files; using polling method"); processEvents_polling(watchDir.toFile()); } else { // Register the directory with the WatchService // Only collect data for ENTRY_CREATE events. Even if a file is just // copied into a directory, several ENTRY_MODIFY events can be // triggered because the file's content and its parameters (such as // timestamp) are independently set. watchDir.register(watcher, new WatchEvent.Kind[] { StandardWatchEventKinds.ENTRY_CREATE }, SensitivityWatchEventModifier.HIGH); System.err.println( "\nWatching directory \"" + watchDir + "\" for incoming files; using WatchService events"); processEvents_watchservice(); watcher.close(); } if (!bRecast || bOutputResultsInRecastMode) { System.err.println("\nWrite data to file \"" + outputFilename + "\"..."); } processData(outputFilename); System.err.println( "\nFileWatch received a total of " + num_received_files + " files (not including \"end.txt\")"); System.err .println("In processing, " + num_skipped_files + " files were skipped (due to wrong name format)"); int num_files_processed = num_received_files - num_skipped_files; System.err.println( "Thus, a total of " + num_files_processed + " files with properly formatted names were processed"); System.err.println("\nTest is complete."); }
From source file:bdsup2sub.cli.CommandLineParser.java
public void printHelp() { HelpFormatter formatter = new HelpFormatter(); formatter.setOptionComparator(new Comparator() { @Override//w w w .j av a 2s.co m public int compare(Object o1, Object o2) { Option opt1 = (Option) o1; Option opt2 = (Option) o2; int opt1Index = OPTION_ORDER.indexOf(opt1.getOpt()); int opt2Index = OPTION_ORDER.indexOf(opt2.getOpt()); return (int) Math.signum(opt1Index - opt2Index); } }); formatter.setWidth(79); String command = System.getProperty("wrapper") == null ? "java -jar BDSup2Sub" : "bdsup2sub"; formatter.printHelp(command + " [options] -o <output> <input>", options); }
From source file:gov.llnl.lc.smt.command.SmtCommand.java
/** * Describe the method here//from ww w . j a va 2 s. co m * * @see describe related java objects * * @param options ***********************************************************/ public void printUsage() { if (options == null) { logger.severe("The options object was null, initialize the command!"); System.err.println("No help or options for " + this.getClass().getName()); return; } int w = Console.getScreenWidth(); int width = w < 32 ? 32 : w - 2; HelpFormatter helpFormatter = new HelpFormatter(); helpFormatter.setWidth(width); // override this method, or just the static strings in your command helpFormatter.printHelp(USAGE, SmtConstants.NEW_LINE + HEADER + SmtConstants.NEW_LINE + ".", options, SmtConstants.NEW_LINE + EXAMPLE + SmtConstants.NEW_LINE + FOOTER); }
From source file:de.dmarcini.submatix.pclogger.gui.MainCommGUI.java
/** * CLI-Optionen einlesen Project: SubmatixBTConfigPC Package: de.dmarcini.submatix.pclogger.gui * //from ww w . j a v a 2 s . 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:erigo.ctstream.CTstream.java
/** * //ww w. ja v a2 s . c o m * CTstream constructor * * @param argsI Command line arguments */ public CTstream(String[] argsI) { // Create a String version of FPS_VALUES String FPS_VALUES_STR = new String(FPS_VALUES[0].toString()); for (int i = 1; i < FPS_VALUES.length; ++i) { FPS_VALUES_STR = FPS_VALUES_STR + "," + FPS_VALUES[i].toString(); } // Create a String version of CTsettings.flushIntervalLongs String FLUSH_VALUES_STR = String.format("%.1f", CTsettings.flushIntervalLongs[0] / 1000.0); for (int i = 1; i < CTsettings.flushIntervalLongs.length; ++i) { // Except for the first flush value (handled above, first item in the string) the rest of these // are whole numbers, so we will print them out with no decimal places FLUSH_VALUES_STR = FLUSH_VALUES_STR + "," + String.format("%.0f", CTsettings.flushIntervalLongs[i] / 1000.0); } // // Parse command line arguments // // 1. Setup command line options // Options options = new Options(); // Boolean options (only the flag, no argument) options.addOption("h", "help", false, "Print this message."); options.addOption("nm", "no_mouse_cursor", false, "Don't include mouse cursor in output screen capture images."); options.addOption("nz", "no_zip", false, "Turn off ZIP output."); options.addOption("x", "debug", false, "Turn on debug output."); options.addOption("cd", "change_detect", false, "Save only changed images."); options.addOption("fs", "full_screen", false, "Capture the full screen."); options.addOption("p", "preview", false, "Display live preview image"); options.addOption("T", "UI_on_top", false, "Keep CTstream on top of all other windows."); options.addOption("sc", "screencap", false, "Capture screen images"); options.addOption("w", "webcam", false, "Capture webcam images"); options.addOption("a", "audio", false, "Record audio."); options.addOption("t", "text", false, "Capture text."); // Command line options that include a flag // For example, the following will be for "-outputfolder <folder> (Location of output files...)" Option option = Option.builder("o").longOpt("outputfolder").argName("folder").hasArg() .desc("Location of output files (source is created under this folder); default = \"" + outputFolder + "\".") .build(); options.addOption(option); option = Option.builder("fps").argName("framespersec").hasArg().desc( "Image rate (images/sec); default = " + DEFAULT_FPS + "; accepted values = " + FPS_VALUES_STR + ".") .build(); options.addOption(option); option = Option.builder("f").argName("autoFlush").hasArg() .desc("Flush interval (sec); amount of data per block; default = " + Double.toString(AUTO_FLUSH_DEFAULT) + "; accepted values = " + FLUSH_VALUES_STR + ".") .build(); options.addOption(option); option = Option.builder("s").argName("source name").hasArg() .desc("Name of output source; default = \"" + sourceName + "\".").build(); options.addOption(option); option = Option.builder("sc_chan").argName("screencap_chan_name").hasArg() .desc("Screen capture image channel name (must end in \".jpg\" or \".jpeg\"); default = \"" + screencapStreamName + "\".") .build(); options.addOption(option); option = Option.builder("webcam_chan").argName("webcam_chan_name").hasArg() .desc("Web camera image channel name (must end in \".jpg\" or \".jpeg\"); default = \"" + webcamStreamName + "\".") .build(); options.addOption(option); option = Option.builder("audio_chan").argName("audio_chan_name").hasArg() .desc("Audio channel name (must end in \".wav\"); default = \"" + audioStreamName + "\".").build(); options.addOption(option); option = Option.builder("text_chan").argName("text_chan_name").hasArg() .desc("Text channel name (must end in \".txt\"); default = \"" + textStreamName + "\".").build(); options.addOption(option); option = Option.builder("q").argName("imagequality").hasArg() .desc("Image quality, 0.00 - 1.00 (higher numbers are better quality); default = " + Float.toString(imageQuality) + ".") .build(); options.addOption(option); // // 2. Parse command line options // CommandLineParser parser = new DefaultParser(); CommandLine line = null; try { line = parser.parse(options, argsI); } catch (ParseException exp) { // oops, something went wrong System.err.println("Command line argument parsing failed: " + exp.getMessage()); return; } // // 3. Retrieve the command line values // if (line.hasOption("help")) { // Display help message and quit HelpFormatter formatter = new HelpFormatter(); formatter.setWidth(160); formatter.printHelp("CTstream", options); System.exit(0); } bPreview = line.hasOption("preview"); bScreencap = line.hasOption("screencap"); bWebcam = line.hasOption("webcam"); bAudio = line.hasOption("audio"); bText = line.hasOption("text"); // Source name sourceName = line.getOptionValue("s", sourceName); // Where to write the files to outputFolder = line.getOptionValue("outputfolder", outputFolder); // Channel names; check filename extensions screencapStreamName = line.getOptionValue("sc_chan", screencapStreamName); webcamStreamName = line.getOptionValue("webcam_chan", webcamStreamName); audioStreamName = line.getOptionValue("audio_chan", audioStreamName); textStreamName = line.getOptionValue("text_chan", textStreamName); try { checkFilenames(); } catch (Exception e) { System.err.println(e.getMessage()); return; } // Auto-flush time try { double autoFlush = Double.parseDouble(line.getOptionValue("f", "" + AUTO_FLUSH_DEFAULT)); flushMillis = (long) (autoFlush * 1000.); boolean bGotMatch = false; for (int i = 0; i < CTsettings.flushIntervalLongs.length; ++i) { if (flushMillis == CTsettings.flushIntervalLongs[i]) { bGotMatch = true; break; } } if (!bGotMatch) { throw new NumberFormatException("bad input value"); } } catch (NumberFormatException nfe) { System.err.println("\nAuto flush time must be one of the following values: " + FLUSH_VALUES_STR); return; } // ZIP output files? (the only way to turn off ZIP is using this command line flag) bZipMode = !line.hasOption("no_zip"); // Include cursor in output screen capture images? bIncludeMouseCursor = !line.hasOption("no_mouse_cursor"); // How many frames (screen or webcam images) to capture per second try { framesPerSec = Double.parseDouble(line.getOptionValue("fps", "" + DEFAULT_FPS)); if (framesPerSec <= 0.0) { throw new NumberFormatException("value must be greater than 0.0"); } // Make sure framesPerSec is one of the accepted values Double userVal = framesPerSec; if (!Arrays.asList(FPS_VALUES).contains(userVal)) { throw new NumberFormatException(new String("framespersec value must be one of: " + FPS_VALUES_STR)); } } catch (NumberFormatException nfe) { System.err.println( "\nError parsing \"fps\"; it must be one of the accepted floating point values:\n" + nfe); return; } // Run CT in debug mode? bDebugMode = line.hasOption("debug"); // changeDetect mode? MJM bChangeDetect = line.hasOption("change_detect"); // Capture the full screen? bFullScreen = line.hasOption("full_screen"); // Keep CTstream UI on top of all other windows? bStayOnTop = line.hasOption("UI_on_top"); // Image quality String imageQualityStr = line.getOptionValue("q", "" + imageQuality); try { imageQuality = Float.parseFloat(imageQualityStr); if ((imageQuality < 0.0f) || (imageQuality > 1.0f)) { throw new NumberFormatException(""); } } catch (NumberFormatException nfe) { System.err.println("\nimage quality must be a number in the range 0.0 <= x <= 1.0"); return; } // // Specify a shutdown hook to catch Ctrl+c // final CTstream temporaryCTS = this; Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { if (bCallExitFromShutdownHook) { temporaryCTS.exit(true); } } }); // For now, we are going to assume that shaped windows (PERPIXEL_TRANSPARENT) are supported. // For a discussion of translucent and shaped windows see https://docs.oracle.com/javase/tutorial/uiswing/misc/trans_shaped_windows.html // This includes examples on how to check if TRANSLUCENT and PERPIXEL_TRANSPARENT are supported by the graphics. // For thread safety: Schedule a job for the event-dispatching thread to create and show the GUI SwingUtilities.invokeLater(new Runnable() { public void run() { temporaryCTS.createAndShowGUI(true); } }); }
From source file:opendap.ppt.OPeNDAPClient.java
/** * * @param args Command line arguments as defined by createCmdLineOptions() *///from w w w. ja v a 2 s . c o m public static void main(String[] args) { Logger log = LoggerFactory.getLogger("OPeNDAPClient-MAIN"); String besCmdFileName = "bes.cmd"; String cmdString; int reps = 1; int maxCmds = 1; OutputStream besOut = System.out; OutputStream besErr = System.err; String hostName = "localhost"; int portNum = 10022; try { Options options = createCmdLineOptions(); CommandLineParser parser = new PosixParser(); CommandLine cmd = parser.parse(options, args); //--------------------------- // Command File if (cmd.hasOption("h")) { HelpFormatter formatter = new HelpFormatter(); formatter.setWidth(120); formatter.printHelp("OPeNDAPClient", options); return; } //--------------------------- // Command File if (cmd.hasOption("i")) { besCmdFileName = cmd.getOptionValue("i"); } log.info("BES Command Filename: " + besCmdFileName); Document cmdDoc = Util.getDocument(besCmdFileName); cmdString = new XMLOutputter(Format.getPrettyFormat()).outputString(cmdDoc); log.info("BES command has been read and parsed."); //--------------------------- // Command reps if (cmd.hasOption("r")) { reps = Integer.parseInt(cmd.getOptionValue("r")); } log.info("BES command will sent " + reps + " time" + (reps > 1 ? "s." : ".")); //--------------------------- // Max commands per client if (cmd.hasOption("c")) { maxCmds = Integer.parseInt(cmd.getOptionValue("c")); } log.info("The connection to the BES will be dropped and a new one opened after every " + maxCmds + " command" + (maxCmds > 1 ? "s." : ".")); //--------------------------- // BES output file if (cmd.hasOption("o")) { File besOutFile = new File(cmd.getOptionValue("o")); besOut = new FileOutputStream(besOutFile); log.info("BES output will be written to " + besOutFile.getAbsolutePath()); } else { log.info("BES output will be written to stdout"); } //--------------------------- // BES error file if (cmd.hasOption("e")) { File besErrFile = new File(cmd.getOptionValue("e")); besErr = new FileOutputStream(besErrFile); log.info("BES errors will be written to " + besErrFile.getAbsolutePath()); } else { log.info("BES errors will be written to stderr"); } //--------------------------- // Hostname if (cmd.hasOption("n")) { hostName = cmd.getOptionValue("n"); } //--------------------------- // Port Number if (cmd.hasOption("p")) { portNum = Integer.parseInt(cmd.getOptionValue("p")); } log.info("Using BES at " + hostName + ":" + portNum); } catch (Throwable t) { log.error("OUCH! Caught " + t.getClass().getName() + " Message: " + t.getMessage()); log.error("STACK TRACE: \n" + org.apache.commons.lang.exception.ExceptionUtils.getStackTrace(t)); return; } int cmdsSent = 0; int connectionsMade = 0; try { log.info("-------------------------------------------------------------------------------"); log.info("-------------------------------------------------------------------------------"); log.info("Starting... \n\n\n"); OPeNDAPClient oc = new OPeNDAPClient(); oc.startClient(hostName, portNum); connectionsMade++; for (int r = 0; reps == 0 || r < reps; r++) { if (r > 0 && r % maxCmds == 0) { oc.shutdownClient(); boolean done = false; while (!done) { oc = new OPeNDAPClient(); try { oc.startClient(hostName, portNum); done = true; } catch (PPTEndOfStreamException e) { log.error( "Caught PPTEndOfStreamException - This BES connection is screwed. Retrying..."); } } connectionsMade++; } oc.executeCommand(cmdString, besOut, besErr); cmdsSent++; } } catch (Throwable t) { log.error("OUCH! Caught " + t.getClass().getName() + " Message: " + t.getMessage()); try { log.error("STACK TRACE: \n" + org.apache.commons.lang.exception.ExceptionUtils.getStackTrace(t)); } catch (Throwable tt) { log.error("**** FAILED TO GENERATE STACK TRACE! ****"); } } finally { log.info("BES Command Filename: " + besCmdFileName); log.info("BES command will sent " + reps + " time" + (reps > 1 ? "s." : ".")); log.info("The connection to the BES will be dropped and a new one opened after every " + maxCmds + " command" + (maxCmds > 1 ? "s." : ".")); log.info("Using BES at " + hostName + ":" + portNum); log.info("Sent a total of " + cmdsSent + " command" + (connectionsMade > 1 ? "s." : ".")); log.info("Made a total of " + connectionsMade + " connection" + (connectionsMade > 1 ? "s" : "") + " to the BES."); } }