List of usage examples for org.apache.commons.cli CommandLine getOptions
public Option[] getOptions()
From source file:com.entertailion.java.caster.Main.java
/** * @param args/*from w ww .j a va2 s. co m*/ */ public static void main(String[] args) { // http://commons.apache.org/proper/commons-cli/usage.html Option help = new Option("h", "help", false, "Print this help message"); Option version = new Option("V", "version", false, "Print version information"); Option list = new Option("l", "list", false, "List ChromeCast devices"); Option verbose = new Option("v", "verbose", false, "Verbose debug logging"); Option transcode = new Option("t", "transcode", false, "Transcode media; -f also required"); Option rest = new Option("r", "rest", false, "REST API server"); Option url = OptionBuilder.withLongOpt("stream").hasArg().withValueSeparator() .withDescription("HTTP URL for streaming content; -d also required").create("s"); Option server = OptionBuilder.withLongOpt("device").hasArg().withValueSeparator() .withDescription("ChromeCast device IP address").create("d"); Option id = OptionBuilder.withLongOpt("app-id").hasArg().withValueSeparator() .withDescription("App ID for whitelisted device").create("id"); Option mediaFile = OptionBuilder.withLongOpt("file").hasArg().withValueSeparator() .withDescription("Local media file; -d also required").create("f"); Option transcodingParameters = OptionBuilder.withLongOpt("transcode-parameters").hasArg() .withValueSeparator().withDescription("Transcode parameters; -t also required").create("tp"); Option restPort = OptionBuilder.withLongOpt("rest-port").hasArg().withValueSeparator() .withDescription("REST API port; default 8080").create("rp"); Options options = new Options(); options.addOption(help); options.addOption(version); options.addOption(list); options.addOption(verbose); options.addOption(url); options.addOption(server); options.addOption(id); options.addOption(mediaFile); options.addOption(transcode); options.addOption(transcodingParameters); options.addOption(rest); options.addOption(restPort); // create the command line parser CommandLineParser parser = new PosixParser(); //String[] arguments = new String[] { "-vr" }; try { // parse the command line arguments CommandLine line = parser.parse(options, args); Option[] lineOptions = line.getOptions(); if (lineOptions.length == 0) { System.out.println("caster: try 'java -jar caster.jar -h' for more information"); System.exit(0); } Log.setVerbose(line.hasOption("v")); // Custom app-id if (line.hasOption("id")) { Log.d(LOG_TAG, line.getOptionValue("id")); appId = line.getOptionValue("id"); } // Print version if (line.hasOption("V")) { System.out.println("Caster version " + VERSION); } // List ChromeCast devices if (line.hasOption("l")) { final DeviceFinder deviceFinder = new DeviceFinder(new DeviceFinderListener() { @Override public void discoveringDevices(DeviceFinder deviceFinder) { Log.d(LOG_TAG, "discoveringDevices"); } @Override public void discoveredDevices(DeviceFinder deviceFinder) { Log.d(LOG_TAG, "discoveredDevices"); TrackedDialServers trackedDialServers = deviceFinder.getTrackedDialServers(); for (DialServer dialServer : trackedDialServers) { System.out.println(dialServer.toString()); // keep system for output } } }); deviceFinder.discoverDevices(); } // Stream media from internet if (line.hasOption("s") && line.hasOption("d")) { Log.d(LOG_TAG, line.getOptionValue("d")); Log.d(LOG_TAG, line.getOptionValue("s")); try { Playback playback = new Playback(platform, appId, new DialServer(InetAddress.getByName(line.getOptionValue("d"))), new PlaybackListener() { private int time; private int duration; private int state; @Override public void updateTime(Playback playback, int time) { Log.d(LOG_TAG, "updateTime: " + time); this.time = time; } @Override public void updateDuration(Playback playback, int duration) { Log.d(LOG_TAG, "updateDuration: " + duration); this.duration = duration; } @Override public void updateState(Playback playback, int state) { Log.d(LOG_TAG, "updateState: " + state); // Stop the app if the video reaches the end if (time > 0 && time == duration && state == 0) { playback.doStop(); System.exit(0); } } public int getTime() { return time; } public int getDuration() { return duration; } public int getState() { return state; } }); playback.stream(line.getOptionValue("s")); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } // Play local media file if (line.hasOption("f") && line.hasOption("d")) { Log.d(LOG_TAG, line.getOptionValue("d")); Log.d(LOG_TAG, line.getOptionValue("f")); final String file = line.getOptionValue("f"); String device = line.getOptionValue("d"); try { Playback playback = new Playback(platform, appId, new DialServer(InetAddress.getByName(device)), new PlaybackListener() { private int time; private int duration; private int state; @Override public void updateTime(Playback playback, int time) { Log.d(LOG_TAG, "updateTime: " + time); this.time = time; } @Override public void updateDuration(Playback playback, int duration) { Log.d(LOG_TAG, "updateDuration: " + duration); this.duration = duration; } @Override public void updateState(Playback playback, int state) { Log.d(LOG_TAG, "updateState: " + state); // Stop the app if the video reaches the end if (time > 0 && time == duration && state == 0) { playback.doStop(); System.exit(0); } } public int getTime() { return time; } public int getDuration() { return duration; } public int getState() { return state; } }); if (line.hasOption("t") && line.hasOption("tp")) { playback.setTranscodingParameters(line.getOptionValue("tp")); } playback.play(file, line.hasOption("t")); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } // REST API server if (line.hasOption("r")) { final DeviceFinder deviceFinder = new DeviceFinder(new DeviceFinderListener() { @Override public void discoveringDevices(DeviceFinder deviceFinder) { Log.d(LOG_TAG, "discoveringDevices"); } @Override public void discoveredDevices(DeviceFinder deviceFinder) { Log.d(LOG_TAG, "discoveredDevices"); TrackedDialServers trackedDialServers = deviceFinder.getTrackedDialServers(); for (DialServer dialServer : trackedDialServers) { Log.d(LOG_TAG, dialServer.toString()); } } }); deviceFinder.discoverDevices(); int port = 0; if (line.hasOption("rp")) { try { port = Integer.parseInt(line.getOptionValue("rp")); } catch (NumberFormatException e) { Log.e(LOG_TAG, "invalid rest port", e); } } Playback.startWebserver(port, new WebListener() { String[] prefixes = { "/playback", "/devices" }; HashMap<String, Playback> playbackMap = new HashMap<String, Playback>(); HashMap<String, RestPlaybackListener> playbackListenerMap = new HashMap<String, RestPlaybackListener>(); final class RestPlaybackListener implements PlaybackListener { private String device; private int time; private int duration; private int state; public RestPlaybackListener(String device) { this.device = device; } @Override public void updateTime(Playback playback, int time) { Log.d(LOG_TAG, "updateTime: " + time); this.time = time; } @Override public void updateDuration(Playback playback, int duration) { Log.d(LOG_TAG, "updateDuration: " + duration); this.duration = duration; } @Override public void updateState(Playback playback, int state) { Log.d(LOG_TAG, "updateState: " + state); this.state = state; // Stop the app if the video reaches the end if (this.time > 0 && this.time == this.duration && state == 0) { playback.doStop(); playbackMap.remove(device); playbackListenerMap.remove(device); } } public int getTime() { return time; } public int getDuration() { return duration; } public int getState() { return state; } } @Override public Response handleRequest(String uri, String method, Properties header, Properties parms) { Log.d(LOG_TAG, "handleRequest: " + uri); if (method.equals("GET")) { if (uri.startsWith(prefixes[0])) { // playback String device = parms.getProperty("device"); if (device != null) { RestPlaybackListener playbackListener = playbackListenerMap.get(device); if (playbackListener != null) { // https://code.google.com/p/json-simple/wiki/EncodingExamples JSONObject obj = new JSONObject(); obj.put("time", playbackListener.getTime()); obj.put("duration", playbackListener.getDuration()); switch (playbackListener.getState()) { case 0: obj.put("state", "idle"); break; case 1: obj.put("state", "stopped"); break; case 2: obj.put("state", "playing"); break; default: obj.put("state", "idle"); break; } return new Response(HttpServer.HTTP_OK, "text/plain", obj.toJSONString()); } else { // Nothing is playing JSONObject obj = new JSONObject(); obj.put("time", 0); obj.put("duration", 0); obj.put("state", "stopped"); return new Response(HttpServer.HTTP_OK, "text/plain", obj.toJSONString()); } } } else if (uri.startsWith(prefixes[1])) { // devices // https://code.google.com/p/json-simple/wiki/EncodingExamples JSONArray list = new JSONArray(); TrackedDialServers trackedDialServers = deviceFinder.getTrackedDialServers(); for (DialServer dialServer : trackedDialServers) { JSONObject obj = new JSONObject(); obj.put("name", dialServer.getFriendlyName()); obj.put("ip_address", dialServer.getIpAddress().getHostAddress()); list.add(obj); } return new Response(HttpServer.HTTP_OK, "text/plain", list.toJSONString()); } } else if (method.equals("POST")) { if (uri.startsWith(prefixes[0])) { // playback String device = parms.getProperty("device"); if (device != null) { String stream = parms.getProperty("stream"); String file = parms.getProperty("file"); String state = parms.getProperty("state"); String transcode = parms.getProperty("transcode"); String transcodeParameters = parms.getProperty("transcode-parameters"); Log.d(LOG_TAG, "transcodeParameters=" + transcodeParameters); if (stream != null) { try { if (playbackMap.get(device) == null) { DialServer dialServer = deviceFinder.getTrackedDialServers() .findDialServer(InetAddress.getByName(device)); if (dialServer != null) { RestPlaybackListener playbackListener = new RestPlaybackListener( device); playbackMap.put(device, new Playback(platform, appId, dialServer, playbackListener)); playbackListenerMap.put(device, playbackListener); } } Playback playback = playbackMap.get(device); if (playback != null) { playback.stream(stream); return new Response(HttpServer.HTTP_OK, "text/plain", "Ok"); } } catch (Exception e1) { Log.e(LOG_TAG, "playback", e1); } } else if (file != null) { try { if (playbackMap.get(device) == null) { DialServer dialServer = deviceFinder.getTrackedDialServers() .findDialServer(InetAddress.getByName(device)); if (dialServer != null) { RestPlaybackListener playbackListener = new RestPlaybackListener( device); playbackMap.put(device, new Playback(platform, appId, dialServer, playbackListener)); playbackListenerMap.put(device, playbackListener); } } Playback playback = playbackMap.get(device); if (transcodeParameters != null) { playback.setTranscodingParameters(transcodeParameters); } if (playback != null) { playback.play(file, transcode != null); return new Response(HttpServer.HTTP_OK, "text/plain", "Ok"); } } catch (Exception e1) { Log.e(LOG_TAG, "playback", e1); } } else if (state != null) { try { if (playbackMap.get(device) == null) { DialServer dialServer = deviceFinder.getTrackedDialServers() .findDialServer(InetAddress.getByName(device)); if (dialServer != null) { RestPlaybackListener playbackListener = new RestPlaybackListener( device); playbackMap.put(device, new Playback(platform, appId, dialServer, playbackListener)); playbackListenerMap.put(device, playbackListener); } } Playback playback = playbackMap.get(device); if (playback != null) { // Handle case where current app wasn't started with caster playback.setDialServer(deviceFinder.getTrackedDialServers() .findDialServer(InetAddress.getByName(device))); // Change the playback state if (state.equals("play")) { playback.doPlay(); return new Response(HttpServer.HTTP_OK, "text/plain", "Ok"); } else if (state.equals("pause")) { playback.doPause(); return new Response(HttpServer.HTTP_OK, "text/plain", "Ok"); } else if (state.equals("stop")) { playback.doStop(); playbackMap.remove(device); playbackListenerMap.remove(device); return new Response(HttpServer.HTTP_OK, "text/plain", "Ok"); } else { Log.e(LOG_TAG, "playback invalid state: " + state); } } } catch (Exception e1) { Log.e(LOG_TAG, "playback", e1); } } } } } return new Response(HttpServer.HTTP_BADREQUEST, "text/plain", "Bad Request"); } @Override public String[] uriPrefixes() { return prefixes; } }); Log.d(LOG_TAG, "REST server ready"); // Run forever... while (true) { try { Thread.sleep(1000); } catch (InterruptedException e) { } } } // Print help if (line.hasOption("h")) { printHelp(options); } } catch (ParseException exp) { System.out.println("ERROR: " + exp.getMessage()); System.out.println(); printHelp(options); } }
From source file:com.fluidops.iwb.tools.RepositoryTool.java
public static void main(String[] args) throws IOException { // Configure logging Log4JHandler.initLogging();//from w w w . j a va 2s. com Config.getConfigWithOverride(); try { CommandLineParser parser = new BasicParser(); Options options = buildOptions(); // parse the command line arguments CommandLine line = parser.parse(options, args); // print the help if (line.getOptions().length == 0 || line.hasOption("help")) { printHelp(options); return; } @SuppressWarnings("unchecked") List<String> lArgs = line.getArgList(); File source = null, target = null; if (lArgs.size() == 0) { source = IWBFileUtil.getFileInDataFolder(Config.getConfig().getRepositoryName()); target = source; } else if (lArgs.size() == 1) { source = new File(lArgs.get(0)); target = source; } else if (lArgs.size() == 2) { source = new File(lArgs.get(0)); target = new File(lArgs.get(1)); } else { System.out.println("Unrecognized arguments."); printHelp(options); System.exit(1); } // handle different options boolean checkGhosts = line.hasOption("g"); String indices = line.hasOption("i") ? line.getOptionValue("i") : getDefaultNativeStoreIndices(); if (line.hasOption("a")) { analyze(source, checkGhosts, indices); System.exit(0); } if (line.hasOption("f")) { analyzeAndFix(source, target, checkGhosts, indices); System.exit(0); } if (line.hasOption("c")) { cleanupRepository(source, target, indices); System.exit(0); } if (line.hasOption("u")) { copyUserData(source, target, indices); System.exit(0); } } catch (Exception exp) { System.out.println("Unexpected error: " + exp.getMessage()); System.exit(1); } }
From source file:dk.alexandra.fresco.demo.PrivateSetDemo.java
/** * The main method sets up application specific command line parameters, * parses command line arguments. Based on the command line arguments it * configures the SCE, instantiates the PrivateSetDemo and runs the PrivateSetDemo on the * SCE./*from w ww. j a va2s .com*/ * */ public static void main(String[] args) { CmdLineUtil util = new CmdLineUtil(); SCEConfiguration sceConf = null; boolean[] key = null; int[] inputs = null; try { util.addOption(Option.builder("key") .desc("The key to use for encryption. " + "A " + INPUT_LENGTH + " char hex string. Required for player 1 and 2. " + "For both players this is interpreted as the AES key. ") .longOpt("key").hasArg().build()); util.addOption(Option.builder("in") .desc("The list of integers to use as input for the set intersection problem. " + "A comma separated list of integers. Required for player 1 and 2. " + "The lists must be of equal length for each player. ") .longOpt("input").hasArg().build()); CommandLine cmd = util.parse(args); sceConf = util.getSCEConfiguration(); // Get and validate the AES specific input. if (sceConf.getMyId() == 1 || sceConf.getMyId() == 2) { if (!cmd.hasOption("in") && !cmd.hasOption("key")) { throw new ParseException("Player 1 and 2 must submit inputs and keys"); } else { if (cmd.getOptionValue("key").length() != INPUT_LENGTH) { throw new IllegalArgumentException( "bad key hex string: must be hex string of length " + INPUT_LENGTH); } key = ByteArithmetic.toBoolean(cmd.getOptionValue("key")); for (Option o : cmd.getOptions()) { System.out.println("option: " + o.getValue()); } inputs = arrayFromString(cmd.getOptionValue("in")); } } else { if (cmd.hasOption("in")) throw new ParseException("Only player 1 and 2 should submit input"); } } catch (ParseException | IllegalArgumentException e) { System.out.println("Error: " + e); System.out.println(); util.displayHelp(); System.exit(-1); } // Do the secure computation using config from property files. PrivateSetDemo privateSetDemo = new PrivateSetDemo(sceConf.getMyId(), key, inputs); SCE sce = SCEFactory.getSCEFromConfiguration(sceConf); try { sce.runApplication(privateSetDemo); } catch (MPCException e) { System.out.println("Error while doing MPC: " + e.getMessage()); System.exit(-1); } // Print result. System.out.println("The resulting ciphertexts are:"); boolean[][] res = new boolean[privateSetDemo.result.length][BLOCK_SIZE]; for (int j = 0; j < privateSetDemo.result.length; j++) { for (int i = 0; i < BLOCK_SIZE; i++) { res[j][i] = privateSetDemo.result[j][i].getValue(); } System.out.println("result(" + j + "): " + ByteArithmetic.toHex(res[j])); } }
From source file:com.cc.apptroy.baksmali.main.java
/** * Run!//www. j ava 2 s . c o m */ public static void main(String[] args) throws IOException { Locale locale = new Locale("en", "US"); Locale.setDefault(locale); CommandLineParser parser = new PosixParser(); CommandLine commandLine; try { commandLine = parser.parse(options, args); } catch (ParseException ex) { usage(); return; } baksmaliOptions options = new baksmaliOptions(); boolean disassemble = true; boolean doDump = false; String dumpFileName = null; boolean setBootClassPath = false; String[] remainingArgs = commandLine.getArgs(); Option[] clOptions = commandLine.getOptions(); for (int i = 0; i < clOptions.length; i++) { Option option = clOptions[i]; String opt = option.getOpt(); switch (opt.charAt(0)) { case 'v': version(); return; case '?': while (++i < clOptions.length) { if (clOptions[i].getOpt().charAt(0) == '?') { usage(true); return; } } usage(false); return; case 'o': options.outputDirectory = commandLine.getOptionValue("o"); break; case 'p': options.noParameterRegisters = true; break; case 'l': options.useLocalsDirective = true; break; case 's': options.useSequentialLabels = true; break; case 'b': options.outputDebugInfo = false; break; case 'd': options.bootClassPathDirs.add(option.getValue()); break; case 'f': options.addCodeOffsets = true; break; case 'r': String[] values = commandLine.getOptionValues('r'); int registerInfo = 0; if (values == null || values.length == 0) { registerInfo = baksmaliOptions.ARGS | baksmaliOptions.DEST; } else { for (String value : values) { if (value.equalsIgnoreCase("ALL")) { registerInfo |= baksmaliOptions.ALL; } else if (value.equalsIgnoreCase("ALLPRE")) { registerInfo |= baksmaliOptions.ALLPRE; } else if (value.equalsIgnoreCase("ALLPOST")) { registerInfo |= baksmaliOptions.ALLPOST; } else if (value.equalsIgnoreCase("ARGS")) { registerInfo |= baksmaliOptions.ARGS; } else if (value.equalsIgnoreCase("DEST")) { registerInfo |= baksmaliOptions.DEST; } else if (value.equalsIgnoreCase("MERGE")) { registerInfo |= baksmaliOptions.MERGE; } else if (value.equalsIgnoreCase("FULLMERGE")) { registerInfo |= baksmaliOptions.FULLMERGE; } else { usage(); return; } } if ((registerInfo & baksmaliOptions.FULLMERGE) != 0) { registerInfo &= ~baksmaliOptions.MERGE; } } options.registerInfo = registerInfo; break; case 'c': String bcp = commandLine.getOptionValue("c"); if (bcp != null && bcp.charAt(0) == ':') { options.addExtraClassPath(bcp); } else { setBootClassPath = true; options.setBootClassPath(bcp); } break; case 'x': options.deodex = true; break; case 'X': options.experimental = true; break; case 'm': options.noAccessorComments = true; break; case 'a': options.apiLevel = Integer.parseInt(commandLine.getOptionValue("a")); break; case 'j': options.jobs = Integer.parseInt(commandLine.getOptionValue("j")); break; case 'i': String rif = commandLine.getOptionValue("i"); options.setResourceIdFiles(rif); break; case 't': options.useImplicitReferences = true; break; case 'e': options.dexEntry = commandLine.getOptionValue("e"); break; case 'k': options.checkPackagePrivateAccess = true; break; case 'N': disassemble = false; break; case 'D': doDump = true; dumpFileName = commandLine.getOptionValue("D"); break; case 'I': options.ignoreErrors = true; break; case 'T': options.customInlineDefinitions = new File(commandLine.getOptionValue("T")); break; default: assert false; } } if (remainingArgs.length != 1) { usage(); return; } if (options.jobs <= 0) { options.jobs = Runtime.getRuntime().availableProcessors(); if (options.jobs > 6) { options.jobs = 6; } } String inputDexFileName = remainingArgs[0]; File dexFileFile = new File(inputDexFileName); if (!dexFileFile.exists()) { System.err.println("Can't find the file " + inputDexFileName); System.exit(1); } //Read in and parse the dex file DexBackedDexFile dexFile = DexFileFactory.loadDexFile(dexFileFile, options.dexEntry, options.apiLevel, options.experimental); if (dexFile.isOdexFile()) { if (!options.deodex) { System.err.println("Warning: You are disassembling an odex file without deodexing it. You"); System.err.println("won't be able to re-assemble the results unless you deodex it with the -x"); System.err.println("option"); options.allowOdex = true; } } else { options.deodex = false; } if (!setBootClassPath && (options.deodex || options.registerInfo != 0)) { if (dexFile instanceof DexBackedOdexFile) { options.bootClassPathEntries = ((DexBackedOdexFile) dexFile).getDependencies(); } else { options.bootClassPathEntries = getDefaultBootClassPathForApi(options.apiLevel, options.experimental); } } if (options.customInlineDefinitions == null && dexFile instanceof DexBackedOdexFile) { options.inlineResolver = InlineMethodResolver .createInlineMethodResolver(((DexBackedOdexFile) dexFile).getOdexVersion()); } boolean errorOccurred = false; if (disassemble) { errorOccurred = !baksmali.disassembleDexFile(dexFile, options); } if (doDump) { if (dumpFileName == null) { dumpFileName = commandLine.getOptionValue(inputDexFileName + ".dump"); } dump.dump(dexFile, dumpFileName, options.apiLevel, options.experimental); } if (errorOccurred) { System.exit(1); } }
From source file:bogdanrechi.xmlo.Xmlo.java
/** * Main method.// w ww . j a va 2 s. c om * * @param args * Program arguments. */ @SuppressWarnings("static-access") public static void main(String[] args) { long timeStart = System.currentTimeMillis(); _log = Logger.getLogger(Xmlo.class); Options argOptions = new Options(); OptionGroup operationTypes = new OptionGroup(); operationTypes.addOption( OptionBuilder.withDescription("XPath query").hasArg().withArgName("file").create("xpath")); operationTypes.addOption( OptionBuilder.withDescription("XSLT transformation").hasArg().withArgName("file").create("xslt")); operationTypes.addOption( OptionBuilder.withDescription("XQuery (with $sourceFilePath, see XmlOperations for details)") .hasArg().withArgName("file").create("xquery")); operationTypes .addOption(OptionBuilder.withDescription("XSD verify").hasArgs().withArgName("file").create("xsd")); operationTypes .addOption(OptionBuilder.withDescription("DTD verify").hasArgs().withArgName("file").create("dtd")); argOptions.addOptionGroup(operationTypes); argOptions.addOption(OptionBuilder.withDescription("on screen information while performing") .withLongOpt("verbose").create("v")); argOptions.addOption(OptionBuilder.withDescription("output non-void or invalid-type results only") .withLongOpt("results-only").create("o")); argOptions.addOption(OptionBuilder.withDescription("replicate input structure on the destination side") .withLongOpt("keep-structure").create("k")); argOptions.addOption(OptionBuilder.withDescription("recursive browsing of the target structure") .withLongOpt("resursive").create("r")); argOptions.addOption(OptionBuilder.withDescription("XPath and XQuery results not numbered") .withLongOpt("not-numbered").create("nn")); argOptions.addOption(OptionBuilder.withDescription("destination files extension").hasArg() .withArgName("ext").withLongOpt("extension").create("x")); argOptions.addOption(OptionBuilder.withDescription("target files mask").hasArg().withArgName("files mask") .withLongOpt("target").create("t")); OptionGroup destinationGroup = new OptionGroup(); destinationGroup.addOption(OptionBuilder.withDescription("destination file").hasArg().withArgName("file") .withLongOpt("destination-file").create("df")); destinationGroup.addOption(OptionBuilder.withDescription("destination folder").hasArg() .withArgName("folder").withLongOpt("destination-directory").create("dd")); destinationGroup.addOption(OptionBuilder.withDescription("destination terminal (and verbose)") .withLongOpt("destination-terminal").create("dt")); argOptions.addOptionGroup(destinationGroup); argOptions.addOption(OptionBuilder.withDescription("file containing namespaces aliases").hasArg() .withArgName("file").withLongOpt("namespaces").create("n")); argOptions.addOption(OptionBuilder.withDescription("usage information").withLongOpt("help").create("h")); argOptions.addOption(OptionBuilder.withDescription("show examples").withLongOpt("examples").create("e")); argOptions.addOption(OptionBuilder.withDescription("keep blank nodes while printing") .withLongOpt("keep-blanks").create("b")); argOptions.addOption( OptionBuilder.withDescription("show duration for each file when the verbose option is activated") .withLongOpt("show-duration").create("d")); CommandLineParser parser = new BasicParser(); try { CommandLine cmd = parser.parse(argOptions, args); if (cmd.hasOption('h') || cmd.hasOption('e') || cmd.getOptions().length == 0) { Format.println("\n" + General.getAboutInformation("resources/xmlo/metadata.properties")); if (cmd.hasOption('h') || cmd.getOptions().length == 0) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("xmlo", "where:", argOptions, null, true); Format.println(); } if (cmd.hasOption("e")) { String examples = Files.readTextFileFromResources("resources/xmlo/examples.txt", _errorMessage); if (examples != null) Format.println(examples); else { Format.println("Internal error! Please see the log file for detalis."); _log.error(_errorMessage.get()); System.exit(1); } } System.exit(0); return; } Format.println(); // options if (cmd.hasOption('r')) _recursive = true; if (cmd.hasOption('k')) _keepStructure = true; if (cmd.hasOption('o')) _resultsOnly = true; if (cmd.hasOption('v')) _verbose = true; if (cmd.hasOption('b')) _keepBlanks = true; if (cmd.hasOption('d')) _showDuration = true; if (cmd.hasOption('x')) _extension = "." + cmd.getOptionValue('x'); if (cmd.hasOption("nn")) _notNumbered = true; if (cmd.hasOption("df")) { _destination = cmd.getOptionValue("df"); if (Files.isFolder(_destination)) printErrorAndExit("The destination is a folder!"); _destinationIsFile = true; } if (cmd.hasOption("dd")) { _destination = cmd.getOptionValue("dd"); if (!Files.exists(_destination)) printErrorAndExit("The destination folder does not exist!"); if (!Files.isFolder(_destination)) printErrorAndExit("The destination is not a folder!"); } if (cmd.hasOption("dt")) _destinationIsTerminal = _verbose = true; if (cmd.hasOption('t')) _target = cmd.getOptionValue('t'); if (cmd.hasOption('n')) { _namespaces = cmd.getOptionValue('n'); extractNamespacesAliases(); } // operations if (cmd.hasOption("xpath")) { if (_target == null) _target = Files.CURRENT_DIRECTORY + Files.FILE_SEPARATOR + "*" + EXTENSION_XPATH; doXPath(cmd.getOptionValue("xpath")); } if (cmd.hasOption("xslt")) { if (_target == null) _target = Files.CURRENT_DIRECTORY + Files.FILE_SEPARATOR + "*" + EXTENSION_XSLT; doXslt(cmd.getOptionValue("xslt")); } if (cmd.hasOption("xquery")) { if (_target == null) _target = Files.CURRENT_DIRECTORY + Files.FILE_SEPARATOR + "*" + EXTENSION_XQUERY; doXQuery(cmd.getOptionValue("xquery")); } if (cmd.hasOption("xsd")) { if (_target == null) _target = Files.CURRENT_DIRECTORY + Files.FILE_SEPARATOR + "*" + EXTENSION_XSD; doXsd(cmd.getOptionValues("xsd")); } if (cmd.hasOption("dtd")) { if (_target == null) _target = Files.CURRENT_DIRECTORY + Files.FILE_SEPARATOR + "*" + EXTENSION_DTD; doDtd(cmd.getOptionValues("dtd")); } } catch (ParseException e) { printErrorAndExit(e.getMessage()); } Format.println("Finished%s.", _showDuration ? " in " + TimeMeasure.printDuration(timeStart) : ""); if (Platform.SYSTEM_IS_LINUX) Format.println(); System.exit(0); }
From source file:com.github.helenusdriver.driver.tools.Tool.java
/** * Main point of entry for this tool// w w w . j a va2 s . c o m * * @author paouelle * * @param args the command-line arguments to the tool */ public static void main(String[] args) { Tool.setRootLogLevel(Level.OFF); // disable logging by default try { final CommandLineParser parser = new GnuParser(); final CommandLine line = parser.parse(Tool.options, args); if (line.hasOption(Tool.verbose.getOpt())) { // do this one first Tool.verbose.run(line); } if (line.hasOption(Tool.trace.getOpt())) { // do this one next Tool.trace.run(line); } for (final Option option : line.getOptions()) { // run these first if (option instanceof RunnableFirstOption) { ((RunnableFirstOption) option).run(line); } } final String server = line.getOptionValue(Tool.server.getLongOpt(), "127.0.0.1" // defaults to local host ); final boolean connect = (line.hasOption(Tool.objects.getLongOpt()) || line.hasOption(Tool.schemas.getLongOpt())); Tool.mgr = new StatementManagerImpl(Cluster.builder().addContactPoint(server).withQueryOptions(null), connect, line.getOptionValues(Tool.filters.getLongOpt())); if (line.hasOption(Tool.replicationFactor.getLongOpt())) { mgr.setDefaultReplicationFactor( Integer.parseInt(line.getOptionValue(Tool.replicationFactor.getLongOpt()))); } try { if (connect && Tool.vflag) { System.out.println(Tool.class.getSimpleName() + ": connected to Cassandra on: " + server); } for (final Option option : line.getOptions()) { if (option instanceof RunnableOption) { ((RunnableOption) option).run(line); } } } finally { Tool.mgr.close().get(); // shutdown and wait for its completion } } catch (Exception e) { System.err.print(Tool.class.getSimpleName() + ": unexpected exception: "); e.printStackTrace(System.err); System.exit(1); } }
From source file:com.ning.hfind.Find.java
public static void main(String[] origArgs) throws ParseException, IOException { PrinterConfig printerConfig = new PrinterConfig(); CommandLineParser parser = new PosixParser(); CommandLine line = parser.parse(options, origArgs); String[] args = line.getArgs(); if (args.length > 1) { // find(1) seems to complain about the first argument only, let's do the same System.out.println(String.format("hfind: %s: unknown option", args[1])); System.exit(COMMAND_LINE_ERROR); }/*from www . ja v a 2s. com*/ if (line.hasOption("help") || args.length == 0) { usage(); return; } String path = args[0]; // Optimization: check the depth on a top-level basis, not on a per-file basis // This avoids crawling files on Hadoop we don't care about int maxDepth = Integer.MAX_VALUE; if (line.hasOption("maxdepth")) { String maxDepthOptionValue = line.getOptionValue("maxdepth"); maxDepth = Integer.valueOf(maxDepthOptionValue); } if (line.hasOption("delete")) { // -delete implies -d printerConfig.setDepthMode(true); printerConfig.setDeleteMode(true); } if (line.hasOption("d")) { printerConfig.setDepthMode(true); } if (line.hasOption("print0")) { printerConfig.setEndLineWithNull(true); } if (line.hasOption("verbose")) { printerConfig.setVerbose(true); } // Ignore certain primaries Iterator<Option> optionsIterator = ExpressionFactory.sanitizeCommandLine(line.getOptions()); Expression expression = null; try { expression = ExpressionFactory .buildExpressionFromCommandLine(new PushbackIterator<Option>(optionsIterator)); //System.out.println(String.format("find %s: %s", StringUtils.join(origArgs, " "), expression)); } catch (IllegalArgumentException e) { System.err.println(e); System.exit(COMMAND_LINE_ERROR); } try { expression.run(path, maxDepth, printerConfig); System.exit(0); } catch (IOException e) { System.err.println(String.format("Error crawling HDFS: %s", e.getLocalizedMessage())); System.exit(HADOOP_ERROR); } }
From source file:com.stumbleupon.hbaseadmin.HBaseCompact.java
/** * Main entry point//from ww w. j av a 2s. co m * @param args command line arguments * @throws Exception */ public static void main(String[] args) throws Exception { CommandLineParser parser = new PosixParser(); CommandLine cmd = null; String hbaseSite = null; String jmxRemotePasswordFile = null; String jmxPort = null; Date startDate = null; Date endDate = null; int throttleFactor = 1; int numCycles = 1; int pauseInterval = DEFAULT_PAUSE_INTERVAL; int waitInterval = DEFAULT_WAIT_INTERVAL; int filesKeep = DEFAULT_FILES_KEEP; long regionCompactWaitTime = DEFAULT_REGION_COMPACT_WAIT_TIME; long maxStoreFileAge = 0; boolean excludeTables = false; String tableNamesString = ""; List<String> tableNames = new ArrayList<String>(); SimpleDateFormat sdf = new SimpleDateFormat("HH:mm"); // Parse command line options try { cmd = parser.parse(getOptions(), args); } catch (org.apache.commons.cli.ParseException e) { System.out.println(e.getMessage()); printOptions(); System.exit(-1); } for (Option option : cmd.getOptions()) { switch (option.getId()) { case 'c': hbaseSite = option.getValue(); break; case 'j': jmxRemotePasswordFile = option.getValue(); break; case 't': throttleFactor = Integer.parseInt(option.getValue()); break; case 'n': numCycles = Integer.parseInt(option.getValue()); break; case 'p': pauseInterval = Integer.parseInt(option.getValue()); break; case 'w': waitInterval = Integer.parseInt(option.getValue()); break; case 's': startDate = sdf.parse(option.getValue()); break; case 'e': endDate = sdf.parse(option.getValue()); break; case 'b': tableNamesString = option.getValue(); tableNames = Arrays.asList(option.getValue().split(",")); break; case 'f': filesKeep = Integer.parseInt(option.getValue()); break; case 'r': jmxPort = option.getValue(); break; case 'x': excludeTables = true; break; case 'm': regionCompactWaitTime = Long.parseLong(option.getValue()); break; case 'a': maxStoreFileAge = Long.parseLong(option.getValue()); break; default: throw new IllegalArgumentException("unexpected option " + option); } } LOG.info("Starting compactor"); LOG.info("--------------------------------------------------"); LOG.info("HBase site : {}", hbaseSite); LOG.info("RegionServer Jmx port : {}", jmxPort); LOG.info("Jmx password file : {}", jmxRemotePasswordFile); LOG.info("Compact interval : {}", pauseInterval); LOG.info("Check interval : {}", waitInterval); LOG.info("Throttle factor : {}", throttleFactor); LOG.info("Number of cycles : {}", numCycles); LOG.info("Off-peak start time : {}", Utils.dateString(startDate, "HH:mm")); LOG.info("Off-peak end time : {}", Utils.dateString(endDate, "HH:mm")); LOG.info("Minimum store files : {}", filesKeep); LOG.info("Table names : {}", tableNamesString); LOG.info("Exclude tables : {}", excludeTables); LOG.info("Region compact wait time: {}", regionCompactWaitTime); LOG.info("Max store file age : {}", maxStoreFileAge); LOG.info("--------------------------------------------------"); // Get command line options final Configuration conf = HBaseConfiguration.create(); conf.addResource(new Path(hbaseSite)); HBaseCompact compact = new HBaseCompact(); ClusterUtils clusterUtils = new ClusterUtils(compact, regionCompactWaitTime); compact.setClusterUtils(clusterUtils); compact.setAdmin(new HBaseAdmin(conf)); compact.setSleepBetweenCompacts(pauseInterval); compact.setSleepBetweenChecks(waitInterval); compact.setThrottleFactor(throttleFactor); compact.setNumCycles(numCycles); compact.setStartDate(startDate); compact.setEndDate(endDate); compact.setNumStoreFiles(filesKeep); compact.setTableNames(tableNames); compact.setExcludeTables(excludeTables); compact.setMaxStoreFileAge(maxStoreFileAge); clusterUtils.setJmxPort(jmxPort); clusterUtils.setJmxPasswordFile(jmxRemotePasswordFile); compact.runCompactions(); }
From source file:ml.shifu.shifu.util.ShifuCLI.java
/** * Main entry for the whole framework./*from w w w . j av a 2 s.c o m*/ * * @throws IOException */ public static void main(String[] args) { // invalid input and help options if (args.length < 1 || (isHelpOption(args[0]))) { printUsage(); System.exit(args.length < 1 ? -1 : 0); } // process -v and -version conditions manually if (isVersionOption(args[0])) { printVersionString(); System.exit(0); } CommandLineParser parser = new GnuParser(); Options opts = buildModelSetOptions(args); CommandLine cmd = null; try { cmd = parser.parse(opts, args); } catch (ParseException e) { log.error("Invalid command options. Please check help message."); printUsage(); System.exit(1); } try { if (args[0].equals(NEW) && args.length >= 2 && StringUtils.isNotEmpty(args[1])) { // modelset step String modelName = args[1]; int status = createNewModel(modelName, cmd.getOptionValue(MODELSET_CMD_TYPE), cmd.getOptionValue(MODELSET_CMD_M)); if (status == 0) { printModelSetCreatedSuccessfulLog(modelName); } // copyModel(manager, cmd.getOptionValues(MODELSET_CMD_CP)); } else { if (args[0].equals(MODELSET_CMD_CP) && args.length >= 3 && StringUtils.isNotEmpty(args[1]) && StringUtils.isNotEmpty(args[2])) { String newModelSetName = args[2]; // modelset step copyModel(new String[] { args[1], newModelSetName }); printModelSetCopiedSuccessfulLog(newModelSetName); } else if (args[0].equals(INIT_CMD)) { // init step if (cmd.getOptions() == null || cmd.getOptions().length == 0) { int status = initializeModel(); if (status == 0) { log.info( "ModelSet initilization is successful. Please continue next step by using 'shifu stats'."); } } else if (cmd.hasOption(INIT_CMD_MODEL)) { initializeModelParam(); } else { log.error("Invalid command, please check help message."); printUsage(); } } else if (args[0].equals(STATS_CMD)) { // stats step calModelStats(); log.info( "Do model set statistics successfully. Please continue next step by using 'shifu varselect'."); } else if (args[0].equals(NORMALIZE_CMD)) { // normalize step normalizeTrainData(); log.info( "Do model set normalization successfully. Please continue next step by using 'shifu train'."); } else if (args[0].equals(VARSELECT_CMD)) { // variable selected step selectModelVar(); log.info( "Do model set variables selection successfully. Please continue next step by using 'shifu normalize'."); } else if (args[0].equals(TRAIN_CMD)) { // train step trainModel(cmd.hasOption(TRAIN_CMD_DRY), cmd.hasOption(TRAIN_CMD_DEBUG)); log.info( "Do model set training successfully. Please continue next step by using 'shifu posttrain' or if no need posttrain you can go through with 'shifu eval'."); } else if (args[0].equals(POSTTRAIN_CMD)) { // post train step postTrainModel(); log.info( "Do model set post-training successfully. Please configurate your eval set in ModelConfig.json and continue next step by using 'shifu eval' or 'shifu eval -new <eval set>' to create a new eval set."); } else if (args[0].equals(SAVE)) { String newModelSetName = args.length >= 2 ? args[1] : null; saveCurrentModel(newModelSetName); } else if (args[0].equals(SWITCH)) { String newModelSetName = args[1]; switchCurrentModel(newModelSetName); } else if (args[0].equals(SHOW)) { ManageModelProcessor p = new ManageModelProcessor(ModelAction.SHOW, null); p.run(); } else if (args[0].equals(EVAL_CMD)) { // eval step if (args.length == 1) { //run everything runEvalSet(cmd.hasOption(TRAIN_CMD_DRY)); log.info("Run eval performance with all eval sets successfully."); } else if (cmd.getOptionValue(MODELSET_CMD_NEW) != null) { //create new eval createNewEvalSet(cmd.getOptionValue(MODELSET_CMD_NEW)); log.info( "Create eval set successfully. You can configurate EvalConfig.json or directly run 'shifu eval -run <evalSetName>' to get performance info."); } else if (cmd.hasOption(EVAL_CMD_RUN)) { runEvalSet(cmd.getOptionValue(EVAL_CMD_RUN), cmd.hasOption(TRAIN_CMD_DRY)); log.info("Finish run eval performance with eval set {}.", cmd.getOptionValue(EVAL_CMD_RUN)); } else if (cmd.hasOption(SCORE)) { //run score runEvalScore(cmd.getOptionValue(SCORE)); log.info("Finish run score with eval set {}.", cmd.getOptionValue(SCORE)); } else if (cmd.hasOption(CONFMAT)) { //run confusion matrix runEvalConfMat(cmd.getOptionValue(CONFMAT)); log.info("Finish run confusion matrix with eval set {}.", cmd.getOptionValue(CONFMAT)); } else if (cmd.hasOption(PERF)) { //run perfermance runEvalPerf(cmd.getOptionValue(PERF)); log.info("Finish run performance maxtrix with eval set {}.", cmd.getOptionValue(PERF)); } else if (cmd.hasOption(LIST)) { //list all evaluation sets listEvalSet(); } else if (cmd.hasOption(DELETE)) { // delete some evaluation set deleteEvalSet(cmd.getOptionValue(DELETE)); } else { log.error("Invalid command, please check help message."); printUsage(); } } else { log.error("Invalid command, please check help message."); printUsage(); } } } catch (ShifuException e) { // need define error code in each step. log.error(e.getError().toString(), e.getCause()); exceptionExit(e); } catch (Exception e) { exceptionExit(e); } }
From source file:gov.nasa.jpl.memex.pooledtimeseries.PoT.java
public static void main(String[] args) { System.loadLibrary(Core.NATIVE_LIBRARY_NAME); Option fileOpt = OptionBuilder.withArgName("file").hasArg().withLongOpt("file") .withDescription("Path to a single file").create('f'); Option dirOpt = OptionBuilder.withArgName("directory").hasArg().withLongOpt("dir") .withDescription("A directory with image files in it").create('d'); Option helpOpt = OptionBuilder.withLongOpt("help").withDescription("Print this message.").create('h'); Option pathFileOpt = OptionBuilder.withArgName("path file").hasArg().withLongOpt("pathfile") .withDescription(/*w w w. j av a 2 s. c o m*/ "A file containing full absolute paths to videos. Previous default was memex-index_temp.txt") .create('p'); Option outputFileOpt = OptionBuilder.withArgName("output file").withLongOpt("outputfile").hasArg() .withDescription("File containing similarity results. Defaults to ./similarity.txt").create('o'); Option jsonOutputFlag = OptionBuilder.withArgName("json output").withLongOpt("json") .withDescription("Set similarity output format to JSON. Defaults to .txt").create('j'); Option similarityFromFeatureVectorsOpt = OptionBuilder .withArgName("similarity from FeatureVectors directory") .withLongOpt("similarityFromFeatureVectorsDirectory").hasArg() .withDescription("calculate similarity matrix from given directory of feature vectors").create('s'); Options options = new Options(); options.addOption(dirOpt); options.addOption(pathFileOpt); options.addOption(fileOpt); options.addOption(helpOpt); options.addOption(outputFileOpt); options.addOption(jsonOutputFlag); options.addOption(similarityFromFeatureVectorsOpt); // create the parser CommandLineParser parser = new GnuParser(); try { // parse the command line arguments CommandLine line = parser.parse(options, args); String directoryPath = null; String pathFile = null; String singleFilePath = null; String similarityFromFeatureVectorsDirectory = null; ArrayList<Path> videoFiles = null; if (line.hasOption("dir")) { directoryPath = line.getOptionValue("dir"); } if (line.hasOption("pathfile")) { pathFile = line.getOptionValue("pathfile"); } if (line.hasOption("file")) { singleFilePath = line.getOptionValue("file"); } if (line.hasOption("outputfile")) { outputFile = line.getOptionValue("outputfile"); } if (line.hasOption("json")) { outputFormat = OUTPUT_FORMATS.JSON; } if (line.hasOption("similarityFromFeatureVectorsDirectory")) { similarityFromFeatureVectorsDirectory = line .getOptionValue("similarityFromFeatureVectorsDirectory"); } if (line.hasOption("help") || (line.getOptions() == null || (line.getOptions() != null && line.getOptions().length == 0)) || (directoryPath != null && pathFile != null && !directoryPath.equals("") && !pathFile.equals(""))) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("pooled_time_series", options); System.exit(1); } if (directoryPath != null) { File dir = new File(directoryPath); List<File> files = (List<File>) FileUtils.listFiles(dir, TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE); videoFiles = new ArrayList<Path>(files.size()); for (File file : files) { String filePath = file.toString(); // When given a directory to load videos from we need to ensure that we // don't try to load the of.txt and hog.txt intermediate result files // that results from previous processing runs. if (!filePath.contains(".txt")) { videoFiles.add(file.toPath()); } } LOG.info("Added " + videoFiles.size() + " video files from " + directoryPath); } if (pathFile != null) { Path list_file = Paths.get(pathFile); videoFiles = loadFiles(list_file); LOG.info("Loaded " + videoFiles.size() + " video files from " + pathFile); } if (singleFilePath != null) { Path singleFile = Paths.get(singleFilePath); LOG.info("Loaded file: " + singleFile); videoFiles = new ArrayList<Path>(1); videoFiles.add(singleFile); } if (similarityFromFeatureVectorsDirectory != null) { File dir = new File(similarityFromFeatureVectorsDirectory); List<File> files = (List<File>) FileUtils.listFiles(dir, TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE); videoFiles = new ArrayList<Path>(files.size()); for (File file : files) { String filePath = file.toString(); // We need to load only the *.of.txt and *.hog.txt values if (filePath.endsWith(".of.txt")) { videoFiles.add(file.toPath()); } if (filePath.endsWith(".hog.txt")) { videoFiles.add(file.toPath()); } } LOG.info("Added " + videoFiles.size() + " feature vectors from " + similarityFromFeatureVectorsDirectory); evaluateSimilarity(videoFiles, 1); } else { evaluateSimilarity(videoFiles, 1); } LOG.info("done."); } catch (ParseException exp) { // oops, something went wrong System.err.println("Parsing failed. Reason: " + exp.getMessage()); } }