List of usage examples for org.apache.commons.cli PosixParser PosixParser
PosixParser
From source file:biomine.nodeimportancecompression.ImportanceCompressionReport.java
public static void main(String[] args) throws IOException, java.text.ParseException { opts.addOption("algorithm", true, "Used algorithm for compression. Possible values are 'brute-force', " + "'brute-force-edges','brute-force-merges','randomized','randomized-merges'," + "'randomized-edges'," + "'fast-brute-force'," + "'fast-brute-force-merges','fast-brute-force-merge-edges'. Default is 'brute-force'."); opts.addOption("query", true, "Query nodes ids, separated by comma."); opts.addOption("queryfile", true, "Read query nodes from file."); opts.addOption("ratio", true, "Goal ratio"); opts.addOption("importancefile", true, "Read importances straight from file"); opts.addOption("keepedges", false, "Don't remove edges during merges"); opts.addOption("connectivity", false, "Compute and output connectivities in edge oriented case"); opts.addOption("paths", false, "Do path oriented compression"); opts.addOption("edges", false, "Do edge oriented compression"); // opts.addOption( "a", double sigma = 1.0; CommandLineParser parser = new PosixParser(); CommandLine cmd = null;//from ww w . j a v a 2s . c o m try { cmd = parser.parse(opts, args); } catch (ParseException e) { e.printStackTrace(); System.exit(0); } String queryStr = cmd.getOptionValue("query"); String[] queryNodeIDs = {}; double[] queryNodeIMP = {}; if (queryStr != null) { queryNodeIDs = queryStr.split(","); queryNodeIMP = new double[queryNodeIDs.length]; for (int i = 0; i < queryNodeIDs.length; i++) { String s = queryNodeIDs[i]; String[] es = s.split("="); queryNodeIMP[i] = 1; if (es.length == 2) { queryNodeIDs[i] = es[0]; queryNodeIMP[i] = Double.parseDouble(es[1]); } else if (es.length > 2) { System.out.println("Too many '=' in querynode specification: " + s); } } } String queryFile = cmd.getOptionValue("queryfile"); Map<String, Double> queryNodes = Collections.EMPTY_MAP; if (queryFile != null) { File in = new File(queryFile); BufferedReader read = new BufferedReader(new FileReader(in)); queryNodes = readMap(read); read.close(); } String impfile = cmd.getOptionValue("importancefile"); Map<String, Double> importances = null; if (impfile != null) { File in = new File(impfile); BufferedReader read = new BufferedReader(new FileReader(in)); importances = readMap(read); read.close(); } String algoStr = cmd.getOptionValue("algorithm"); CompressionAlgorithm algo = null; if (algoStr == null || algoStr.equals("brute-force")) { algo = new BruteForceCompression(); } else if (algoStr.equals("brute-force-edges")) { algo = new BruteForceCompressionOnlyEdges(); } else if (algoStr.equals("brute-force-merges")) { algo = new BruteForceCompressionOnlyMerges(); } else if (algoStr.equals("fast-brute-force-merges")) { //algo = new FastBruteForceCompressionOnlyMerges(); algo = new FastBruteForceCompression(true, false); } else if (algoStr.equals("fast-brute-force-edges")) { algo = new FastBruteForceCompression(false, true); //algo = new FastBruteForceCompressionOnlyEdges(); } else if (algoStr.equals("fast-brute-force")) { algo = new FastBruteForceCompression(true, true); } else if (algoStr.equals("randomized-edges")) { algo = new RandomizedCompressionOnlyEdges(); //modified } else if (algoStr.equals("randomized")) { algo = new RandomizedCompression(); } else if (algoStr.equals("randomized-merges")) { algo = new RandomizedCompressionOnlyMerges(); } else { System.out.println("Unsupported algorithm: " + algoStr); printHelp(); } String ratioStr = cmd.getOptionValue("ratio"); double ratio = 0; if (ratioStr != null) { ratio = Double.parseDouble(ratioStr); } else { System.out.println("Goal ratio not specified"); printHelp(); } String infile = null; if (cmd.getArgs().length != 0) { infile = cmd.getArgs()[0]; } else { printHelp(); } BMGraph bmg = BMGraphUtils.readBMGraph(new File(infile)); HashMap<BMNode, Double> queryBMNodes = new HashMap<BMNode, Double>(); for (String id : queryNodes.keySet()) { queryBMNodes.put(bmg.getNode(id), queryNodes.get(id)); } long startMillis = System.currentTimeMillis(); ImportanceGraphWrapper wrap = QueryImportance.queryImportanceGraph(bmg, queryBMNodes); if (importances != null) { for (String id : importances.keySet()) { wrap.setImportance(bmg.getNode(id), importances.get(id)); } } ImportanceMerger merger = null; if (cmd.hasOption("edges")) { merger = new ImportanceMergerEdges(wrap.getImportanceGraph()); } else if (cmd.hasOption("paths")) { merger = new ImportanceMergerPaths(wrap.getImportanceGraph()); } else { System.out.println("Specify either 'paths' or 'edges'."); System.exit(1); } if (cmd.hasOption("keepedges")) { merger.setKeepEdges(true); } algo.compress(merger, ratio); long endMillis = System.currentTimeMillis(); // write importance { BufferedWriter wr = new BufferedWriter(new FileWriter("importance.txt", false)); for (BMNode nod : bmg.getNodes()) { wr.write(nod + " " + wrap.getImportance(nod) + "\n"); } wr.close(); } // write sum of all pairs of node importance added by Fang /* { BufferedWriter wr = new BufferedWriter(new FileWriter("sum_of_all_pairs_importance.txt", true)); ImportanceGraph orig = wrap.getImportanceGraph(); double sum = 0; for (int i = 0; i <= orig.getMaxNodeId(); i++) { for (int j = i+1; j <= orig.getMaxNodeId(); j++) { sum = sum+ wrap.getImportance(i)* wrap.getImportance(j); } } wr.write(""+sum); wr.write("\n"); wr.close(); } */ // write uncompressed edges { BufferedWriter wr = new BufferedWriter(new FileWriter("edges.txt", false)); ImportanceGraph orig = wrap.getImportanceGraph(); ImportanceGraph ucom = merger.getUncompressedGraph(); for (int i = 0; i <= orig.getMaxNodeId(); i++) { String iname = wrap.intToNode(i).toString(); HashSet<Integer> ne = new HashSet<Integer>(); ne.addAll(orig.getNeighbors(i)); ne.addAll(ucom.getNeighbors(i)); for (int j : ne) { if (i < j) continue; String jname = wrap.intToNode(j).toString(); double a = orig.getEdgeWeight(i, j); double b = ucom.getEdgeWeight(i, j); wr.write(iname + " " + jname + " " + a + " " + b + " " + Math.abs(a - b)); wr.write("\n"); } } wr.close(); } // write distance { // BufferedWriter wr = new BufferedWriter(new // FileWriter("distance.txt",false)); BufferedWriter wr = new BufferedWriter(new FileWriter("distance.txt", true)); //modified by Fang ImportanceGraph orig = wrap.getImportanceGraph(); ImportanceGraph ucom = merger.getUncompressedGraph(); double error = 0; for (int i = 0; i <= orig.getMaxNodeId(); i++) { HashSet<Integer> ne = new HashSet<Integer>(); ne.addAll(orig.getNeighbors(i)); ne.addAll(ucom.getNeighbors(i)); for (int j : ne) { if (i <= j) continue; double a = orig.getEdgeWeight(i, j); double b = ucom.getEdgeWeight(i, j); error += (a - b) * (a - b) * wrap.getImportance(i) * wrap.getImportance(j); // modify by Fang: multiply imp(u)imp(v) } } error = Math.sqrt(error); //////////error = Math.sqrt(error / 2); // modified by Fang: the error of each // edge is counted twice wr.write("" + error); wr.write("\n"); wr.close(); } // write sizes { ImportanceGraph orig = wrap.getImportanceGraph(); ImportanceGraph comp = merger.getCurrentGraph(); // BufferedWriter wr = new BufferedWriter(new // FileWriter("sizes.txt",false)); BufferedWriter wr = new BufferedWriter(new FileWriter("sizes.txt", true)); //modified by Fang wr.write(orig.getNodeCount() + " " + orig.getEdgeCount() + " " + comp.getNodeCount() + " " + comp.getEdgeCount()); wr.write("\n"); wr.close(); } //write time { System.out.println("writing time"); BufferedWriter wr = new BufferedWriter(new FileWriter("time.txt", true)); //modified by Fang double secs = (endMillis - startMillis) * 0.001; wr.write("" + secs + "\n"); wr.close(); } //write change of connectivity for edge-oriented case // added by Fang { if (cmd.hasOption("connectivity")) { BufferedWriter wr = new BufferedWriter(new FileWriter("connectivity.txt", true)); ImportanceGraph orig = wrap.getImportanceGraph(); ImportanceGraph ucom = merger.getUncompressedGraph(); double diff = 0; for (int i = 0; i <= orig.getMaxNodeId(); i++) { ProbDijkstra pdori = new ProbDijkstra(orig, i); ProbDijkstra pducom = new ProbDijkstra(ucom, i); for (int j = i + 1; j <= orig.getMaxNodeId(); j++) { double oriconn = pdori.getProbTo(j); double ucomconn = pducom.getProbTo(j); diff = diff + (oriconn - ucomconn) * (oriconn - ucomconn) * wrap.getImportance(i) * wrap.getImportance(j); } } diff = Math.sqrt(diff); wr.write("" + diff); wr.write("\n"); wr.close(); } } //write output graph { BMGraph output = bmg;//new BMGraph(bmg); int no = 0; BMNode[] nodes = new BMNode[merger.getGroups().size()]; for (ArrayList<Integer> gr : merger.getGroups()) { BMNode bmgroup = new BMNode("Group", "" + (no + 1)); bmgroup.setAttributes(new HashMap<String, String>()); bmgroup.put("autoedges", "0"); nodes[no] = bmgroup; no++; if (gr.size() == 0) continue; for (int x : gr) { BMNode nod = output.getNode(wrap.intToNode(x).toString()); BMEdge belongs = new BMEdge(nod, bmgroup, "belongs_to"); output.ensureHasEdge(belongs); } output.ensureHasNode(bmgroup); } for (int i = 0; i < nodes.length; i++) { for (int x : merger.getCurrentGraph().getNeighbors(i)) { if (x == i) { nodes[x].put("selfedge", "" + merger.getCurrentGraph().getEdgeWeight(i, x)); //ge.put("goodness", ""+merger.getCurrentGraph().getEdgeWeight(i, x)); continue; } BMEdge ge = new BMEdge(nodes[x], nodes[i], "groupedge"); ge.setAttributes(new HashMap<String, String>()); ge.put("goodness", "" + merger.getCurrentGraph().getEdgeWeight(i, x)); output.ensureHasEdge(ge); } } System.out.println(output.getGroupNodes()); BMGraphUtils.writeBMGraph(output, "output.bmg"); } }
From source file:com.linkedin.helix.tools.ZKDumper.java
public static void main(String[] args) throws Exception { if (args == null || args.length == 0) { HelpFormatter helpFormatter = new HelpFormatter(); helpFormatter.printHelp("java " + ZKDumper.class.getName(), options); System.exit(1);//from ww w.j ava2 s . com } CommandLineParser parser = new PosixParser(); CommandLine cmd = parser.parse(options, args); cmd.hasOption("zkSvr"); boolean download = cmd.hasOption("download"); boolean upload = cmd.hasOption("upload"); boolean del = cmd.hasOption("delete"); String zkAddress = cmd.getOptionValue("zkSvr"); String zkPath = cmd.getOptionValue("zkpath"); String fsPath = cmd.getOptionValue("fspath"); ZKDumper zkDump = new ZKDumper(zkAddress); if (download) { if (cmd.hasOption("addSuffix")) { zkDump.suffix = cmd.getOptionValue("addSuffix"); } zkDump.download(zkPath, fsPath + zkPath); } if (upload) { if (cmd.hasOption("removeSuffix")) { zkDump.removeSuffix = true; } zkDump.upload(zkPath, fsPath); } if (del) { zkDump.delete(zkPath); } }
From source file:com.linkedin.databus.eventgenerator.DataGenerator.java
public static void main(String[] args) throws IOException, UnknownTypeException { // load and verify the options CommandLineParser parser = new PosixParser(); Options opts = loadOptions();//from w ww. j a v a 2 s . com CommandLine cmd = null; try { cmd = parser.parse(opts, args); } catch (org.apache.commons.cli.ParseException parseEx) { LOG.error("Invalid option"); printHelp(opts); return; } if (cmd.hasOption('l')) { String log4jPropFile = cmd.getOptionValue('l'); PropertyConfigurator.configure(log4jPropFile); LOG.info("Using custom logging settings from file " + log4jPropFile); } else { PatternLayout defaultLayout = new PatternLayout("%d{ISO8601} +%r [%t] (%p) {%c{1}} %m%n"); ConsoleAppender defaultAppender = new ConsoleAppender(defaultLayout); Logger.getRootLogger().removeAllAppenders(); Logger.getRootLogger().addAppender(defaultAppender); LOG.info("Using default logging settings"); } // check for necessary options String fileLoc = cmd.getOptionValue("schemaLocation"); if (fileLoc == null) { LOG.error("schemaLocation not specified"); printHelp(opts); } //get string length and check if min is greater than 0 // Generate the record File schemaFile = new File(fileLoc); DataGenerator dataGenerator = new DataGenerator(schemaFile); GenericRecord record = dataGenerator.generateRandomRecord(); if (cmd.hasOption(PRINT_AVRO_JSON_OPTNAME)) { String outname = cmd.getOptionValue(PRINT_AVRO_JSON_OPTNAME); OutputStream outs = System.out; if (!outname.equals("-")) { outs = new FileOutputStream(outname); } printAvroJson(record, outs); if (!outname.equals("-")) { outs.close(); } } else { DataGenerator.prettyPrint(record); } }
From source file:com.entertailion.java.caster.Main.java
/** * @param args/* ww w .j av a 2 s . c o 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:br.edu.ufcg.lsd.seghidro.extratoropendap.ui.CLI.java
/** * Exemplo://from ww w.j a v a 2s.co m * * <pre> * java -jar extrator-opendap.jar -d "dods://150.165.126.97:8080/thredds/dodsC/test/MIMR_SRB1_1_pr-change_2011-2030.nc" -p ../../resources/arquivos_de_entrada/postoBoqueirao.txt -i "2020-05-16" -f "2020-08-16" -o output.txt * </pre> * * @param args * @throws java.text.ParseException * @throws ExtratorOpendapException * @throws IOException */ public static void main(String[] args) throws IOException, ExtratorOpendapException, java.text.ParseException { // System.out.println(args[0]+" "+ args[1] +" "+ args[2]+" "+ args[3] // +" "+ args[4]); // System.out.println("===========================hsdklhfsllll+======"); // if (args[3].equals("forMarbs")) { // ExtratorNoFormatoPMH extrator = new // ExtratorNoFormatoPMH(args[4],args[5],args[6]); if (args[0].equals("forMarbs")) { ExtratorNoFormatoPMH extrator = new ExtratorNoFormatoPMH(args[1], args[2], args[3]); } else { Options options = new Options(); options.addOption(PONTOS, "pontos", true, "Caminho para o arquivo de pontos."); options.addOption(DATASET, "dataset", true, "Caminho para o dataset de origem."); options.addOption(OUTPUT, "output", true, "Nome do arquivo de sada."); options.addOption(INICIO, "inicio", true, "Data inicial da extrao."); options.addOption(FIM, "fim", true, "Data final da extrao."); options.addOption(HELP, false, "Comando de ajuda."); options.addOption(USAGE, false, "Instrues de uso."); CommandLineParser parser = new PosixParser(); HelpFormatter formatter = new HelpFormatter(); CommandLine cmd = null; try { cmd = parser.parse(options, args); } catch (ParseException e) { MainUtil.showMessageAndExit(e); } if (cmd.hasOption(PONTOS) && cmd.hasOption(DATASET) && cmd.hasOption(OUTPUT)) { String arquivoNetCDF = cmd.getOptionValue(DATASET); String arquivoDePontos = cmd.getOptionValue(PONTOS); String outputFileName = cmd.getOptionValue(OUTPUT); DataSet dataset; try { dataset = new DataSet(arquivoNetCDF); ExtratorDeVariaveisIF extrator; if (cmd.hasOption(INICIO) && cmd.hasOption(FIM)) { Date dataInicial = null; Date dataFinal = null; try { dataInicial = formatadorDeDatas.parse(cmd.getOptionValue(INICIO)); } catch (java.text.ParseException e) { MainUtil.showMessageAndExit("A data inicial '" + cmd.getOptionValue(INICIO) + "' no est em um formato reconhecido. Informe no formato " + formatoParaData + ". Por Exemplo: " + formatadorDeDatas.format(new Date()) + "."); } try { dataFinal = formatadorDeDatas.parse(cmd.getOptionValue(FIM)); } catch (java.text.ParseException e) { MainUtil.showMessageAndExit("A data final '" + cmd.getOptionValue(FIM) + "' no est em um formato reconhecido. Informe no formato " + formatoParaData + ". Por Exemplo: " + formatadorDeDatas.format(new Date()) + "."); } extrator = new ExtratorDeVariaveisInterpolado(dataset, new File(arquivoDePontos), dataInicial, dataFinal, new File(outputFileName)); } else { extrator = new ExtratorDeVariaveisInterpolado(dataset, new File(arquivoDePontos), new File(outputFileName)); } String extracoes = extrator.extraiValoresDeInteresse(); System.out.println(extracoes); extrator.salvaArquivoComExtracoes(); } catch (ExtratorOpendapException e) { MainUtil.showMessageAndExit(e); } } else { if (cmd.hasOption(HELP)) { formatter.printHelp(EXECUTION_LINE, options); } else if (cmd.hasOption(USAGE)) { formatter.printHelp(EXECUTION_LINE, options, true); } else { formatter.printHelp(EXECUTION_LINE, options, true); } } } }
From source file:com.netscape.cms.servlet.test.ConfigurationTest.java
public static void main(String args[]) throws Exception { String host = null;//from w ww. java2 s. co m String port = null; String cstype = null; String token_pwd = null; String db_dir = "./"; String protocol = "https"; String pin = null; String extCertFile = null; int testnum = 1; // parse command line arguments Options options = new Options(); options.addOption("t", true, "Subsystem type"); options.addOption("h", true, "Hostname of the CS subsystem"); options.addOption("p", true, "Port of the CS subsystem"); options.addOption("w", true, "Token password"); options.addOption("d", true, "Directory for tokendb"); options.addOption("s", true, "preop pin"); options.addOption("e", true, "File for externally signed signing cert"); options.addOption("x", true, "Test number"); try { CommandLineParser parser = new PosixParser(); CommandLine cmd = parser.parse(options, args); if (cmd.hasOption("t")) { cstype = cmd.getOptionValue("t"); } else { System.err.println("Error: no subsystem type provided."); usage(options); } if (cmd.hasOption("h")) { host = cmd.getOptionValue("h"); } else { System.err.println("Error: no hostname provided."); usage(options); } if (cmd.hasOption("p")) { port = cmd.getOptionValue("p"); } else { System.err.println("Error: no port provided"); usage(options); } if (cmd.hasOption("w")) { token_pwd = cmd.getOptionValue("w"); } else { System.err.println("Error: no token password provided"); usage(options); } if (cmd.hasOption("d")) { db_dir = cmd.getOptionValue("d"); } if (cmd.hasOption("s")) { pin = cmd.getOptionValue("s"); } if (cmd.hasOption("e")) { extCertFile = cmd.getOptionValue("e"); } if (cmd.hasOption("x")) { testnum = Integer.parseInt(cmd.getOptionValue("x")); } } catch (ParseException e) { System.err.println("Error in parsing command line options: " + e.getMessage()); usage(options); } // Initialize token try { CryptoManager.initialize(db_dir); } catch (AlreadyInitializedException e) { // it is ok if it is already initialized } catch (Exception e) { System.out.println("INITIALIZATION ERROR: " + e.toString()); System.exit(1); } // log into token CryptoManager manager = null; CryptoToken token = null; try { manager = CryptoManager.getInstance(); token = manager.getInternalKeyStorageToken(); Password password = new Password(token_pwd.toCharArray()); try { token.login(password); } catch (Exception e) { System.out.println("login Exception: " + e.toString()); if (!token.isLoggedIn()) { token.initPassword(password, password); } } } catch (Exception e) { System.out.println("Exception in logging into token:" + e.toString()); } SystemConfigClient client = null; try { ClientConfig config = new ClientConfig(); config.setServerURL(protocol + "://" + host + ":" + port); client = new SystemConfigClient(new PKIClient(config, null), cstype); } catch (URISyntaxException e1) { e1.printStackTrace(); System.exit(1); } ConfigurationRequest data = null; switch (testnum) { case 1: data = constructCAData(host, port, pin, db_dir, token_pwd, token); break; case 2: data = constructCloneCAData(host, port, pin, db_dir, token_pwd, token); break; case 3: data = constructKRAData(host, port, pin, db_dir, token_pwd, token); break; case 4: data = constructOCSPData(host, port, pin, db_dir, token_pwd, token); break; case 5: data = constructTKSData(host, port, pin, db_dir, token_pwd, token); break; case 6: data = constructSubCAData(host, port, pin, db_dir, token_pwd, token); break; case 7: data = constructExternalCADataPart1(host, port, pin, db_dir, token_pwd, token); break; case 8: data = constructExternalCADataPart2(host, port, pin, db_dir, token_pwd, token, extCertFile); break; default: System.out.println("Invalid test"); System.exit(1); } ConfigurationResponse response = client.configure(data); System.out.println("adminCert: " + response.getAdminCert().getCert()); List<SystemCertData> certs = response.getSystemCerts(); Iterator<SystemCertData> iterator = certs.iterator(); while (iterator.hasNext()) { SystemCertData cdata = iterator.next(); System.out.println("tag: " + cdata.getTag()); System.out.println("cert: " + cdata.getCert()); System.out.println("request: " + cdata.getRequest()); } }
From source file:ch.ethz.dcg.jukefox.cli.CliJukefoxApplication.java
public static void main(String[] args) { CommandLineParser parser = new PosixParser(); LogLevel logLevel = LogLevel.ERROR;/* w w w.j av a 2s . c o m*/ try { CommandLine line = parser.parse(getCliOptions(), args); if (line.hasOption(VERBOSE_OPTION)) { logLevel = LogLevel.VERBOSE; } } catch (ParseException e1) { Log.e(TAG, "Unexpected exception: " + e1.getMessage()); } printWelcome(); Log.setLogLevel(logLevel); // Send logs async new Thread(new Runnable() { @Override public void run() { playerModel.getLogManager().sendLogs(); } }).start(); CliJukefoxApplication application = new CliJukefoxApplication(); try { scanner = new Scanner(System.in); application.start(); ImportState importState = libraryImportManager.getImportState(); importState.addListener(application); //System.out.println(importState.getProgress().getStatusMessage()); while (running) { String next = scanner.nextLine(); if (next.isEmpty()) { continue; } try { application.getCommandLineInterface().execute(next); } catch (ExecutionException e) { System.out.println("Invalid input, please use following commands: "); application.getCommandLineInterface().execute("help"); } } } catch (ExecutionException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:eu.fbk.utils.twm.FormPageSearcher.java
public static void main(final String args[]) throws Exception { String logConfig = System.getProperty("log-config"); if (logConfig == null) { logConfig = "configuration/log-config.txt"; }//from w w w. j ava2 s. co m PropertyConfigurator.configure(logConfig); final Options options = new Options(); try { OptionBuilder.withArgName("index"); OptionBuilder.hasArg(); OptionBuilder.withDescription("open an index with the specified name"); OptionBuilder.isRequired(); OptionBuilder.withLongOpt("index"); final Option indexNameOpt = OptionBuilder.create("i"); OptionBuilder.withArgName("interactive-mode"); OptionBuilder.withDescription("enter in the interactive mode"); OptionBuilder.withLongOpt("interactive-mode"); final Option interactiveModeOpt = OptionBuilder.create("t"); OptionBuilder.withArgName("search"); OptionBuilder.hasArg(); OptionBuilder.withDescription("search for the specified key"); OptionBuilder.withLongOpt("search"); final Option searchOpt = OptionBuilder.create("s"); OptionBuilder.withArgName("key-freq"); OptionBuilder.hasArg(); OptionBuilder.withDescription("read the keys' frequencies from the specified file"); OptionBuilder.withLongOpt("key-freq"); final Option freqFileOpt = OptionBuilder.create("f"); OptionBuilder.withArgName("minimum-freq"); // Option keyFieldNameOpt = // OptionBuilder.withArgName("key-field-name").hasArg().withDescription("use the specified name for the field key").withLongOpt("key-field-name").create("k"); // Option valueFieldNameOpt = // OptionBuilder.withArgName("value-field-name").hasArg().withDescription("use the specified name for the field value").withLongOpt("value-field-name").create("v"); final Option minimumKeyFreqOpt = OptionBuilder.hasArg() .withDescription("minimum key frequency of cached values (default is " + DEFAULT_MIN_FREQ + ")") .withLongOpt("minimum-freq").create("m"); OptionBuilder.withArgName("int"); final Option notificationPointOpt = OptionBuilder.hasArg() .withDescription( "receive notification every n pages (default is " + DEFAULT_NOTIFICATION_POINT + ")") .withLongOpt("notification-point").create("b"); options.addOption("h", "help", false, "print this message"); options.addOption("v", "version", false, "output version information and exit"); options.addOption(indexNameOpt); options.addOption(interactiveModeOpt); options.addOption(searchOpt); options.addOption(freqFileOpt); // options.addOption(keyFieldNameOpt); // options.addOption(valueFieldNameOpt); options.addOption(minimumKeyFreqOpt); options.addOption(notificationPointOpt); final CommandLineParser parser = new PosixParser(); final CommandLine line = parser.parse(options, args); if (line.hasOption("help") || line.hasOption("version")) { throw new ParseException(""); } int minFreq = DEFAULT_MIN_FREQ; if (line.hasOption("minimum-freq")) { minFreq = Integer.parseInt(line.getOptionValue("minimum-freq")); } int notificationPoint = DEFAULT_NOTIFICATION_POINT; if (line.hasOption("notification-point")) { notificationPoint = Integer.parseInt(line.getOptionValue("notification-point")); } final FormPageSearcher pageFormSearcher = new FormPageSearcher(line.getOptionValue("index")); pageFormSearcher.setNotificationPoint(notificationPoint); /* * logger.debug(line.getOptionValue("key-field-name") + "\t" + * line.getOptionValue("value-field-name")); if (line.hasOption("key-field-name")) { * pageFormSearcher.setKeyFieldName(line.getOptionValue("key-field-name")); } if * (line.hasOption("value-field-name")) { * pageFormSearcher.setValueFieldName(line.getOptionValue("value-field-name")); } */ if (line.hasOption("key-freq")) { pageFormSearcher.loadCache(line.getOptionValue("key-freq"), minFreq); } if (line.hasOption("search")) { logger.debug("searching " + line.getOptionValue("search") + "..."); final FreqSetSearcher.Entry[] result = pageFormSearcher.search(line.getOptionValue("search")); logger.info(Arrays.toString(result)); } if (line.hasOption("interactive-mode")) { pageFormSearcher.interactive(); } } catch (final ParseException e) { // oops, something went wrong if (e.getMessage().length() > 0) { System.out.println("Parsing failed: " + e.getMessage() + "\n"); } final HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(400, "java -cp dist/thewikimachine.jar org.fbk.cit.hlt.thewikimachine.index.FormPageSearcher", "\n", options, "\n", true); } }
From source file:edu.msu.cme.rdp.readseq.utils.RmDupSeqs.java
public static void main(String[] args) throws Exception { String inFile;//from ww w . j a v a2s.c o m String outFile; int length = 0; boolean debug = false; boolean removeDuplicates = false; try { CommandLine line = new PosixParser().parse(options, args); if (line.hasOption("duplicates")) { removeDuplicates = true; } if (line.hasOption("min_seq_length")) { length = Integer.parseInt(line.getOptionValue("min_seq_length")); } if (line.hasOption("infile")) { inFile = line.getOptionValue("infile"); } else { throw new Exception("infile is required"); } if (line.hasOption("outfile")) { outFile = line.getOptionValue("outfile"); } else { throw new Exception("outfile is required"); } if (line.hasOption("debug")) { debug = true; } } catch (Exception e) { new HelpFormatter().printHelp(120, "RmRedundantSeqs [options]", "", options, ""); System.err.println("ERROR: " + e.getMessage()); return; } if (!removeDuplicates) { filterByLength(inFile, outFile, length); } else { filterDuplicates(inFile, outFile, length, debug); } }
From source file:com.simple.sftpfetch.App.java
public static void main(String[] args) throws Exception { Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); Options options = getOptions();//from w w w . j a v a 2s. c om List<String> requiredProperties = asList("c"); CommandLineParser parser = new PosixParser(); try { CommandLine commandLine = parser.parse(options, args); if (commandLine.hasOption("h")) { printUsage(options); System.exit(0); } for (String opt : requiredProperties) { if (!commandLine.hasOption(opt)) { System.err.println("The option: " + opt + " is required."); printUsage(options); System.exit(1); } } Pattern pattern; if (commandLine.hasOption("p")) { pattern = Pattern.compile(commandLine.getOptionValue("p")); } else { pattern = MATCH_EVERYTHING; } String filename = commandLine.getOptionValue("c"); Properties properties = new Properties(); try { InputStream stream = new FileInputStream(new File(filename)); properties.load(stream); } catch (IOException ioe) { System.err.println("Unable to read properties from: " + filename); System.exit(2); } String routingKey = ""; if (commandLine.hasOption("r")) { routingKey = commandLine.getOptionValue("r"); } else if (properties.containsKey("rabbit.routingkey")) { routingKey = properties.getProperty("rabbit.routingkey"); } int daysToFetch; if (commandLine.hasOption("d")) { daysToFetch = Integer.valueOf(commandLine.getOptionValue("d")); } else { daysToFetch = Integer.valueOf(properties.getProperty(FETCH_DAYS)); } FileDecrypter decrypter = null; if (properties.containsKey("decryption.key.path")) { decrypter = new PGPFileDecrypter(new File(properties.getProperty("decryption.key.path"))); } else { decrypter = new NoopDecrypter(); } SftpClient sftpClient = new SftpClient(new JSch(), new SftpConnectionInfo(properties)); try { App app = new App(sftpClient, s3FromProperties(properties), new RabbitClient(new ConnectionFactory(), new RabbitConnectionInfo(properties)), decrypter, System.out); app.run(routingKey, daysToFetch, pattern, commandLine.hasOption("n"), commandLine.hasOption("o")); } finally { sftpClient.close(); } System.exit(0); } catch (UnrecognizedOptionException uoe) { System.err.println(uoe.getMessage()); printUsage(options); System.exit(10); } }