List of usage examples for java.util Iterator hasNext
boolean hasNext();
From source file:com.hp.avmon.snmp.discover.SLPClient.java
/** * Test method.//from www. j a v a2 s . c om * * @param args * Ignored */ public static void main(String[] args) { SLPClient client = new SLPClient(); List<String> wbemservices = client.findWbemServices(); Iterator<String> serviceIterator = wbemservices.iterator(); while (serviceIterator.hasNext()) { String url = serviceIterator.next().toString(); System.out.println(url); logger.debug(url); List<String> attributes = client.findAttributes(url, SCOPE, new Vector<String>()); Iterator<String> attributeIterator = attributes.iterator(); while (attributeIterator.hasNext()) { System.out.println(attributeIterator.next()); logger.debug(attributeIterator.next()); } } }
From source file:com.mozilla.socorro.RawDumpSizeScan.java
public static void main(String[] args) throws ParseException { String startDateStr = args[0]; String endDateStr = args[1];// w w w. j av a 2 s . com // Set both start/end time and start/stop row Calendar startCal = Calendar.getInstance(); Calendar endCal = Calendar.getInstance(); SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); if (!StringUtils.isBlank(startDateStr)) { startCal.setTime(sdf.parse(startDateStr)); } if (!StringUtils.isBlank(endDateStr)) { endCal.setTime(sdf.parse(endDateStr)); } DescriptiveStatistics stats = new DescriptiveStatistics(); long numNullRawBytes = 0L; HTable table = null; Map<String, Integer> rowValueSizeMap = new HashMap<String, Integer>(); try { table = new HTable(TABLE_NAME_CRASH_REPORTS); Scan[] scans = generateScans(startCal, endCal); for (Scan s : scans) { ResultScanner rs = table.getScanner(s); Iterator<Result> iter = rs.iterator(); while (iter.hasNext()) { Result r = iter.next(); ImmutableBytesWritable rawBytes = r.getBytes(); //length = r.getValue(RAW_DATA_BYTES, DUMP_BYTES); if (rawBytes != null) { int length = rawBytes.getLength(); if (length > 20971520) { rowValueSizeMap.put(new String(r.getRow()), length); } stats.addValue(length); } else { numNullRawBytes++; } if (stats.getN() % 10000 == 0) { System.out.println("Processed " + stats.getN()); System.out.println(String.format("Min: %.02f Max: %.02f Mean: %.02f", stats.getMin(), stats.getMax(), stats.getMean())); System.out.println( String.format("1st Quartile: %.02f 2nd Quartile: %.02f 3rd Quartile: %.02f", stats.getPercentile(25.0d), stats.getPercentile(50.0d), stats.getPercentile(75.0d))); System.out.println("Number of large entries: " + rowValueSizeMap.size()); } } rs.close(); } System.out.println("Finished Processing!"); System.out.println(String.format("Min: %.02f Max: %.02f Mean: %.02f", stats.getMin(), stats.getMax(), stats.getMean())); System.out.println(String.format("1st Quartile: %.02f 2nd Quartile: %.02f 3rd Quartile: %.02f", stats.getPercentile(25.0d), stats.getPercentile(50.0d), stats.getPercentile(75.0d))); for (Map.Entry<String, Integer> entry : rowValueSizeMap.entrySet()) { System.out.println(String.format("RowId: %s => Length: %d", entry.getKey(), entry.getValue())); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if (table != null) { try { table.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
From source file:com.cedarsoft.serialization.SplittingPerformanceRunner.java
public static void main(String[] args) throws Exception { final String uri = "http://www.cedarsoft.com/some/slashes/1.0.0"; run("String.plit", new Callable<String>() { @Override/*www . j av a 2s. c om*/ public String call() throws Exception { String[] parts = uri.split("/"); return parts[parts.length - 1]; } }); run("Splitter", new Callable<String>() { @Override public String call() throws Exception { Splitter splitter = Splitter.on("/"); Iterable<String> parts = splitter.split(uri); Iterator<String> iterator = parts.iterator(); while (true) { String current = iterator.next(); if (!iterator.hasNext()) { return current; } } } }); run("static Splitter", new Callable<String>() { @Override public String call() throws Exception { Iterable<String> parts = SPLITTER.split(uri); Iterator<String> iterator = parts.iterator(); while (true) { String current = iterator.next(); if (!iterator.hasNext()) { return current; } } } }); run("indexOf", new Callable<String>() { @Override public String call() throws Exception { int index = uri.lastIndexOf("/"); return uri.substring(index + 1); } }); }
From source file:akori.Impact.java
static public void main(String[] args) throws IOException { String PATH = "E:\\Trabajos\\AKORI\\datosmatrizgino\\"; String PATHIMG = "E:\\NetBeansProjects\\AKORI\\Proccess_1\\ImagesPages\\"; for (int i = 1; i <= 32; ++i) { for (int k = 1; k <= 15; ++k) { System.out.println("Matrix " + i + "-" + k); BufferedImage img = null; try { img = ImageIO.read(new File(PATHIMG + i + ".png")); } catch (IOException ex) { ex.getStackTrace();/*from ww w .j av a 2s .co m*/ } int ymax = img.getHeight(); int xmax = img.getWidth(); double[][] imagen = new double[ymax][xmax]; BufferedReader in = null; try { in = new BufferedReader(new FileReader(PATH + i + "-" + k + ".txt")); } catch (FileNotFoundException ex) { ex.getStackTrace(); } String linea; ArrayList<String> lista = new ArrayList<String>(); HashMap<String, String> lista1 = new HashMap<String, String>(); try { for (int j = 0; (linea = in.readLine()) != null; ++j) { String[] datos = linea.split(","); int x = (int) Double.parseDouble(datos[1]); int y = (int) Double.parseDouble(datos[2]); if (x >= xmax || y >= ymax || x <= 0 || y <= 0) { continue; } lista.add(x + "," + y); } } catch (Exception ex) { ex.getStackTrace(); } try { in.close(); } catch (IOException ex) { ex.getStackTrace(); } Iterator iter = lista.iterator(); int[][] matrix = new int[lista.size()][2]; for (int j = 0; iter.hasNext(); ++j) { String xy = (String) iter.next(); String[] datos = xy.split(","); matrix[j][0] = Integer.parseInt(datos[0]); matrix[j][1] = Integer.parseInt(datos[1]); } for (int j = 0; j < matrix.length; ++j) { int std = 50; int x = matrix[j][0]; int y = matrix[j][1]; imagen[y][x] += 1; double aux; normalMatrix(imagen, y, x, std); } FileWriter fw = new FileWriter(PATH + "Matrix" + i + "-" + k + ".txt"); BufferedWriter bw = new BufferedWriter(fw); for (int j = 0; j < imagen.length; ++j) { for (int t = 0; t < imagen[j].length; ++t) { if (t + 1 == imagen[j].length) bw.write(imagen[j][t] + ""); else bw.write(imagen[j][t] + ","); } bw.write("\n"); } bw.close(); } } }
From source file:edu.umd.cloud9.example.bigram.AnalyzeBigramRelativeFrequency.java
@SuppressWarnings({ "static-access" }) public static void main(String[] args) { Options options = new Options(); options.addOption(OptionBuilder.withArgName("path").hasArg().withDescription("input path").create(INPUT)); CommandLine cmdline = null;/*from w w w . ja v a2 s . co m*/ CommandLineParser parser = new GnuParser(); try { cmdline = parser.parse(options, args); } catch (ParseException exp) { System.err.println("Error parsing command line: " + exp.getMessage()); System.exit(-1); } if (!cmdline.hasOption(INPUT)) { System.out.println("args: " + Arrays.toString(args)); HelpFormatter formatter = new HelpFormatter(); formatter.setWidth(120); formatter.printHelp(AnalyzeBigramRelativeFrequency.class.getName(), options); ToolRunner.printGenericCommandUsage(System.out); System.exit(-1); } String inputPath = cmdline.getOptionValue(INPUT); System.out.println("input path: " + inputPath); List<PairOfWritables<PairOfStrings, FloatWritable>> pairs = SequenceFileUtils .readDirectory(new Path(inputPath)); List<PairOfWritables<PairOfStrings, FloatWritable>> list1 = Lists.newArrayList(); List<PairOfWritables<PairOfStrings, FloatWritable>> list2 = Lists.newArrayList(); for (PairOfWritables<PairOfStrings, FloatWritable> p : pairs) { PairOfStrings bigram = p.getLeftElement(); if (bigram.getLeftElement().equals("light")) { list1.add(p); } if (bigram.getLeftElement().equals("contain")) { list2.add(p); } } Collections.sort(list1, new Comparator<PairOfWritables<PairOfStrings, FloatWritable>>() { public int compare(PairOfWritables<PairOfStrings, FloatWritable> e1, PairOfWritables<PairOfStrings, FloatWritable> e2) { if (e1.getRightElement().compareTo(e2.getRightElement()) == 0) { return e1.getLeftElement().compareTo(e2.getLeftElement()); } return e2.getRightElement().compareTo(e1.getRightElement()); } }); Iterator<PairOfWritables<PairOfStrings, FloatWritable>> iter1 = Iterators.limit(list1.iterator(), 10); while (iter1.hasNext()) { PairOfWritables<PairOfStrings, FloatWritable> p = iter1.next(); PairOfStrings bigram = p.getLeftElement(); System.out.println(bigram + "\t" + p.getRightElement()); } Collections.sort(list2, new Comparator<PairOfWritables<PairOfStrings, FloatWritable>>() { public int compare(PairOfWritables<PairOfStrings, FloatWritable> e1, PairOfWritables<PairOfStrings, FloatWritable> e2) { if (e1.getRightElement().compareTo(e2.getRightElement()) == 0) { return e1.getLeftElement().compareTo(e2.getLeftElement()); } return e2.getRightElement().compareTo(e1.getRightElement()); } }); Iterator<PairOfWritables<PairOfStrings, FloatWritable>> iter2 = Iterators.limit(list2.iterator(), 10); while (iter2.hasNext()) { PairOfWritables<PairOfStrings, FloatWritable> p = iter2.next(); PairOfStrings bigram = p.getLeftElement(); System.out.println(bigram + "\t" + p.getRightElement()); } }
From source file:joshelser.as2015.query.Query.java
public static void main(String[] args) throws Exception { JCommander commander = new JCommander(); final Opts options = new Opts(); commander.addObject(options);//from ww w.j ava 2 s.c o m commander.setProgramName("Query"); try { commander.parse(args); } catch (ParameterException ex) { commander.usage(); System.err.println(ex.getMessage()); System.exit(1); } ClientConfiguration conf = ClientConfiguration.loadDefault(); if (null != options.clientConfFile) { conf = new ClientConfiguration(new PropertiesConfiguration(options.clientConfFile)); } conf.withInstance(options.instanceName).withZkHosts(options.zookeepers); ZooKeeperInstance inst = new ZooKeeperInstance(conf); Connector conn = inst.getConnector(options.user, new PasswordToken(options.password)); BatchScanner bs = conn.createBatchScanner(options.table, Authorizations.EMPTY, 16); try { bs.setRanges(Collections.singleton(new Range())); final Text categoryText = new Text("category"); bs.fetchColumn(categoryText, new Text("name")); bs.fetchColumn(new Text("review"), new Text("score")); bs.fetchColumn(new Text("review"), new Text("userId")); bs.addScanIterator(new IteratorSetting(50, "wri", WholeRowIterator.class)); final Text colf = new Text(); Map<String, List<Integer>> scoresByUser = new HashMap<>(); for (Entry<Key, Value> entry : bs) { SortedMap<Key, Value> row = WholeRowIterator.decodeRow(entry.getKey(), entry.getValue()); Iterator<Entry<Key, Value>> iter = row.entrySet().iterator(); if (!iter.hasNext()) { // row was empty continue; } Entry<Key, Value> categoryEntry = iter.next(); categoryEntry.getKey().getColumnFamily(colf); if (!colf.equals(categoryText)) { throw new IllegalArgumentException("Unknown!"); } if (!categoryEntry.getValue().toString().equals("books")) { // not a book review continue; } if (!iter.hasNext()) { continue; } Entry<Key, Value> reviewScore = iter.next(); if (!iter.hasNext()) { continue; } Entry<Key, Value> reviewUserId = iter.next(); String userId = reviewUserId.getValue().toString(); if (userId.equals("unknown")) { // filter unknow user id continue; } List<Integer> scores = scoresByUser.get(userId); if (null == scores) { scores = new ArrayList<>(); scoresByUser.put(userId, scores); } scores.add(Float.valueOf(reviewScore.getValue().toString()).intValue()); } for (Entry<String, List<Integer>> entry : scoresByUser.entrySet()) { int sum = 0; for (Integer val : entry.getValue()) { sum += val; } System.out.println(entry.getKey() + " => " + new Float(sum) / entry.getValue().size()); } } finally { bs.close(); } }
From source file:com.mewmew.fairy.v1.book.Cut.java
public static void main(String[] args) throws FileNotFoundException { Iterator<Map<String, Object>> iter = new Cut(null) .createIterator(new FileInputStream("/Users/jax/.gconsole/caches/gonsole.xno.ningops.net.txt")); while (iter.hasNext()) { Map<String, Object> map = iter.next(); System.out.println(map);/* ww w . j a v a 2 s .c om*/ } }
From source file:asl.seedscan.DQAWeb.java
public static void main(String args[]) { db = new MetricDatabase("", "", ""); findConsoleHandler();/*from ww w . j a va 2s . co m*/ consoleHandler.setLevel(Level.ALL); Logger.getLogger("").setLevel(Level.CONFIG); // Default locations of config and schema files File configFile = new File("dqaweb-config.xml"); File schemaFile = new File("schemas/DQAWebConfig.xsd"); boolean parseConfig = true; boolean testMode = false; ArrayList<File> schemaFiles = new ArrayList<File>(); schemaFiles.add(schemaFile); // ==== Command Line Parsing ==== Options options = new Options(); Option opConfigFile = new Option("c", "config-file", true, "The config file to use for seedscan. XML format according to SeedScanConfig.xsd."); Option opSchemaFile = new Option("s", "schema-file", true, "The schame file which should be used to verify the config file format. "); Option opTest = new Option("t", "test", false, "Run in test console mode rather than as a servlet."); OptionGroup ogConfig = new OptionGroup(); ogConfig.addOption(opConfigFile); OptionGroup ogSchema = new OptionGroup(); ogConfig.addOption(opSchemaFile); OptionGroup ogTest = new OptionGroup(); ogTest.addOption(opTest); options.addOptionGroup(ogConfig); options.addOptionGroup(ogSchema); options.addOptionGroup(ogTest); PosixParser optParser = new PosixParser(); CommandLine cmdLine = null; try { cmdLine = optParser.parse(options, args, true); } catch (org.apache.commons.cli.ParseException e) { logger.severe("Error while parsing command-line arguments."); System.exit(1); } Option opt; Iterator iter = cmdLine.iterator(); while (iter.hasNext()) { opt = (Option) iter.next(); if (opt.getOpt().equals("c")) { configFile = new File(opt.getValue()); } else if (opt.getOpt().equals("s")) { schemaFile = new File(opt.getValue()); } else if (opt.getOpt().equals("t")) { testMode = true; } } String query = ""; System.out.println("Entering Test Mode"); System.out.println("Enter a query string to view results or type \"help\" for example query strings"); InputStreamReader input = new InputStreamReader(System.in); BufferedReader reader = new BufferedReader(input); String result = ""; while (testMode == true) { try { System.out.printf("Query: "); query = reader.readLine(); if (query.equals("exit")) { testMode = false; } else if (query.equals("help")) { System.out.println("Need to add some help for people"); //TODO } else { result = processCommand(query); } System.out.println(result); } catch (IOException err) { System.err.println("Error reading line, in DQAWeb.java"); } } System.err.printf("DONE.\n"); }
From source file:MyMap.java
public static void main(String[] argv) { // Construct and load the hash. This simulates loading a // database or reading from a file, or wherever the data is. Map map = new MyMap(); // The hash maps from company name to address. // In real life this might map to an Address object... map.put("Adobe", "Mountain View, CA"); map.put("Learning Tree", "Los Angeles, CA"); map.put("IBM", "White Plains, NY"); map.put("Netscape", "Mountain View, CA"); map.put("Microsoft", "Redmond, WA"); map.put("Sun", "Mountain View, CA"); map.put("O'Reilly", "Sebastopol, CA"); // Two versions of the "retrieval" phase. // Version 1: get one pair's value given its key // (presumably the key would really come from user input): String queryString = "O'Reilly"; System.out.println("You asked about " + queryString + "."); String resultString = (String) map.get(queryString); System.out.println("They are located in: " + resultString); System.out.println();//from ww w . jav a 2 s . c o m // Version 2: get ALL the keys and pairs // (maybe to print a report, or to save to disk) Iterator k = map.keySet().iterator(); while (k.hasNext()) { String key = (String) k.next(); System.out.println("Key " + key + "; Value " + (String) map.get(key)); } // Step 3 - try out the entrySet() method. Set es = map.entrySet(); System.out.println("entrySet() returns " + es.size() + " Map.Entry's"); }
From source file:id3Crawler.java
public static void main(String[] args) throws IOException { //Input for the directory to be searched. System.out.println("Please enter a directory: "); Scanner scanner = new Scanner(System.in); String input = scanner.nextLine(); //Start a timer to calculate runtime startTime = System.currentTimeMillis(); System.out.println("Starting scan..."); //Files for output PrintWriter pw1 = new PrintWriter(new FileWriter("C:/Users/gbob3_000/Desktop/id3CrawlerOutput/Song.txt")); PrintWriter pw2 = new PrintWriter(new FileWriter("C:/Users/gbob3_000/Desktop/id3CrawlerOutput/Artist.txt")); PrintWriter pw3 = new PrintWriter(new FileWriter("C:/Users/gbob3_000/Desktop/id3CrawlerOutput/Album.txt")); PrintWriter pw4 = new PrintWriter( new FileWriter("C:/Users/gbob3_000/Desktop/id3CrawlerOutput/PerformedBy.txt")); PrintWriter pw5 = new PrintWriter( new FileWriter("C:/Users/gbob3_000/Desktop/id3CrawlerOutput/TrackOf.txt")); PrintWriter pw6 = new PrintWriter( new FileWriter("C:/Users/gbob3_000/Desktop/id3CrawlerOutput/CreatedBy.txt")); //This is used for creating IDs for artists, songs, albums. int idCounter = 0; //This is used to prevent duplicate artists String previousArtist = " "; String currentArtist;/*from w ww . jav a 2s . c o m*/ int artistID = 0; //This is used to prevent duplicate albums String previousAlbum = " "; String currentAlbum; int albumID = 0; //This array holds valid extensions to iterate through String[] extensions = new String[] { "mp3" }; //iterate through all files in a directory Iterator<File> it = FileUtils.iterateFiles(new File(input), extensions, true); while (it.hasNext()) { //open the next file File file = it.next(); //instantiate an mp3file object with the opened file MP3 song = GetMP3(file); //pass the song through SongInfo and return the required information SongInfo info = new SongInfo(song); //This is used to prevent duplicate artists/albums currentArtist = info.getArtistInfo(); currentAlbum = info.getAlbumInfo(); //Append the song information to the end of a text file pw1.println(idCounter + "\t" + info.getTitleInfo()); //This prevents duplicates of artists if (!(currentArtist.equals(previousArtist))) { pw2.println(idCounter + "\t" + info.getArtistInfo()); previousArtist = currentArtist; artistID = idCounter; } //This prevents duplicates of albums if (!(currentAlbum.equals(previousAlbum))) { pw3.println(idCounter + "\t" + info.getAlbumInfo()); previousAlbum = currentAlbum; albumID = idCounter; //This formats the IDs for a "CreatedBy" relationship table pw6.println(artistID + "\t" + albumID); } //This formats the IDs for a "PerformedBy" relationship table pw4.println(idCounter + "\t" + artistID); //This formats the IDs for a "TrackOf" relationship table pw5.println(idCounter + "\t" + albumID); idCounter++; songCounter++; } scanner.close(); pw1.close(); pw2.close(); pw3.close(); pw4.close(); pw5.close(); pw6.close(); System.out.println("Scan took " + ((System.currentTimeMillis() - startTime) / 1000.0) + " seconds to scan " + songCounter + " items!"); }