List of usage examples for java.util Iterator next
E next();
From source file:DateUtilsV1.java
public static void main(String args[]) { GregorianCalendar calendar = new GregorianCalendar(1974, 5, 25, 6, 30, 30); Date date = calendar.getTime(); System.err.println("Original Date: " + date); System.err.println("Rounded Date: " + DateUtils.round(date, Calendar.HOUR)); System.err.println("Truncated Date: " + DateUtils.truncate(date, Calendar.MONTH)); Iterator itr = DateUtils.iterator(date, DateUtils.RANGE_WEEK_MONDAY); while(itr.hasNext()) { System.err.println(((Calendar)itr.next()).getTime()); }/*from w w w. ja v a2 s . c om*/ }
From source file:NewStyle.java
public static void main(String args[]) { // Now, list holds references of type String. ArrayList<String> list = new ArrayList<String>(); list.add("one"); list.add("two"); list.add("three"); list.add("four"); // Notice that Iterator is also generic. Iterator<String> itr = list.iterator(); // The following statement will now cause a compile-time eror. // Iterator<Integer> itr = list.iterator(); // Error! while (itr.hasNext()) { String str = itr.next(); // no cast needed // Now, the following line is a compile-time, // rather than runtime, error. // Integer i = itr.next(); // this won't compile System.out.println(str + " is " + str.length() + " chars long."); }/*from w w w .ja v a 2s .c om*/ }
From source file:com.stratio.decision.executables.DataFlowFromCsvMain.java
public static void main(String[] args) throws IOException, NumberFormatException, InterruptedException { if (args.length < 4) { log.info(//from ww w .j a va2s . c o m "Usage: \n param 1 - path to file \n param 2 - stream name to send the data \n param 3 - time in ms to wait to send each data \n param 4 - broker list"); } else { Producer<String, String> producer = new Producer<String, String>(createProducerConfig(args[3])); Gson gson = new Gson(); Reader in = new FileReader(args[0]); CSVParser parser = CSVFormat.DEFAULT.parse(in); List<String> columnNames = new ArrayList<>(); for (CSVRecord csvRecord : parser.getRecords()) { if (columnNames.size() == 0) { Iterator<String> iterator = csvRecord.iterator(); while (iterator.hasNext()) { columnNames.add(iterator.next()); } } else { StratioStreamingMessage message = new StratioStreamingMessage(); message.setOperation(STREAM_OPERATIONS.MANIPULATION.INSERT.toLowerCase()); message.setStreamName(args[1]); message.setTimestamp(System.currentTimeMillis()); message.setSession_id(String.valueOf(System.currentTimeMillis())); message.setRequest_id(String.valueOf(System.currentTimeMillis())); message.setRequest("dummy request"); List<ColumnNameTypeValue> sensorData = new ArrayList<>(); for (int i = 0; i < columnNames.size(); i++) { // Workaround Object value = null; try { value = Double.valueOf(csvRecord.get(i)); } catch (NumberFormatException e) { value = csvRecord.get(i); } sensorData.add(new ColumnNameTypeValue(columnNames.get(i), null, value)); } message.setColumns(sensorData); String json = gson.toJson(message); log.info("Sending data: {}", json); producer.send(new KeyedMessage<String, String>(InternalTopic.TOPIC_DATA.getTopicName(), STREAM_OPERATIONS.MANIPULATION.INSERT, json)); log.info("Sleeping {} ms...", args[2]); Thread.sleep(Long.valueOf(args[2])); } } log.info("Program completed."); } }
From source file:net.sourceforge.happybank.facade.BankTest.java
/** * Test method./* w w w . j a va2 s. c om*/ * * @param args command line arguments */ public static void main(final String[] args) { try { // get context and facade ApplicationContext ctx = new FileSystemXmlApplicationContext("build/applicationContext.xml"); BankingFacade bank = (BankingFacade) ctx.getBean("bankManager"); // get all customers List<Customer> customers = bank.getCustomers(); Iterator<Customer> custIter = customers.iterator(); Customer cust = null; while (custIter.hasNext()) { cust = custIter.next(); String cid = cust.getId(); Customer customer = bank.getCustomer(cid); System.out.println(customer.toString()); // get customers accounts List<Account> accounts = bank.getAccounts(cid); Iterator<Account> accIter = accounts.iterator(); Account acc = null; while (accIter.hasNext()) { acc = accIter.next(); String aid = acc.getId(); Account account = bank.getAccount(aid); System.out.println("\t> " + account.toString()); // get account transactions List<TransRecord> transactions = bank.getTransactions(aid); Iterator<TransRecord> transIter = transactions.iterator(); TransRecord tr = null; while (transIter.hasNext()) { tr = transIter.next(); System.out.println("\t\t>" + tr.toString()); } } } // test creation, deletion and withdrawal bank.addCustomer("999", "Mr", "First", "Last"); bank.addAccount("999-99", "999", "Checking"); bank.deposit("999-99", new BigDecimal(1000.0)); bank.withdraw("999-99", new BigDecimal(500.0)); bank.deleteAccount("999-99"); bank.deleteCustomer("999"); } catch (BankException ex) { ex.printStackTrace(); } }
From source file:com.puffywhiteshare.PWSApp.java
/** * @param args// w ww .j av a 2s . c o m * @throws IOException */ public static void main(String[] args) throws IOException { CloudBucket cloud = new CloudBucket(); logger.info("Test my output bitches"); Yaml y = new Yaml(); File f = new File("Playing.yml"); FileInputStream fis = new FileInputStream(f); Map m = (Map) y.load(fis); Long startFiles = System.currentTimeMillis(); Iterator<File> fileIterator = FileUtils.iterateFiles(new File("/Users/chad/Pictures/."), null, true); do { File file = fileIterator.next(); cloud.add(file); } while (fileIterator.hasNext()); Long endFiles = System.currentTimeMillis(); System.out.println("Files processing took " + ((endFiles - startFiles))); Long startSer = System.currentTimeMillis(); String filename = "cloud.ser"; FileOutputStream fos = null; ObjectOutputStream out = null; try { fos = new FileOutputStream(filename); out = new ObjectOutputStream(fos); out.writeObject(cloud); out.close(); } catch (IOException ex) { ex.printStackTrace(); } Long endSer = System.currentTimeMillis(); System.out.println("Files processing took " + ((endSer - startSer))); logger.info(" Size = " + FileUtils.byteCountToDisplaySize(cloud.getSize())); logger.info("Count = " + cloud.getCount()); /* Set<String> buckets = m.keySet(); System.out.println(m.toString()); for(String bucket : buckets) { logger.info("Bucket = " + bucket); logger.info("Folders = " + m.get(bucket)); List<Object> folders = (List<Object>) m.get(bucket); for(Object folder : folders) { if(folder instanceof String) { logger.info("Folder Root = " + folder); } else if(folder instanceof Map) { logger.info("Folder Map = " + folder); } } BlockingQueue<File> fileFeed = new ArrayBlockingQueue<File>(10); Map folderMap = (Map) m.get(bucket); Set<String> folders = folderMap.entrySet(); for(String folder : folders) { logger.info("Folder = " + folder); } } */ }
From source file:graphene.dao.titan.BatchGraphTest.java
public static void main(String[] args) { Configuration conf = new BaseConfiguration(); conf.setProperty("storage.backend", "cassandrathrift"); conf.setProperty("storage.hostname", "127.0.0.1"); //conf.setProperty("storage.port", 9160); TitanGraph g = TitanFactory.open(conf); BatchGraph<TitanGraph> bgraph = new BatchGraph(g, VertexIDType.STRING, 1000); // for (String[] quad : quads) { // Vertex[] vertices = new Vertex[2]; // for (int i=0;i<2;i++) { // vertices[i] = bgraph.getVertex(quad[i]); // if (vertices[i]==null) vertices[i]=bgraph.addVertex(quad[i]); // }/* ww w .ja v a 2 s . co m*/ // Edge edge = bgraph.addEdge(null,vertices[0],vertices[1],quad[2]); // edge.setProperty("annotation",quad[3]); // } for (int k = 0; k < MAXNODES; k++) { Vertex[] vertices = new Vertex[2]; for (int i = 0; i < 2; i++) { String id = "Vertex-" + rand.nextInt(MAXNODES); vertices[i] = bgraph.getVertex(id); if (vertices[i] == null) { vertices[i] = bgraph.addVertex(id); vertices[i].setProperty("label", id); } } String edgeId = "Edge-" + vertices[0].getId() + "--" + vertices[1].getId(); Edge e = bgraph.getEdge(edgeId); if (e == null) { e = bgraph.addEdge(null, vertices[0], vertices[1], edgeId); DateTime dt = new DateTime(); e.setProperty("edgeData", dt.getMillis()); } } bgraph.commit(); Iterator<Vertex> iter = bgraph.getVertices().iterator(); logger.debug("Start iterating over vertices"); while (iter.hasNext()) { Vertex v = iter.next(); Iterator<Edge> eIter = v.getEdges(Direction.BOTH).iterator(); while (eIter.hasNext()) { Edge currentEdge = eIter.next(); String data = currentEdge.getProperty("edgeData"); logger.debug("Observing edge " + currentEdge.getLabel()); logger.debug("has edge with data: " + data + " from " + currentEdge.getVertex(Direction.IN).getProperty("label") + " to " + currentEdge.getVertex(Direction.OUT).getProperty("label")); } } logger.debug("Done iterating over vertices"); }
From source file:MainClass.java
public static void main(String[] argv) { Map map = new MyMap(); map.put("Adobe", "Mountain View, CA"); map.put("Learning Tree", "Los Angeles, CA"); map.put("IBM", "White Plains, NY"); String queryString = "Google"; 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 w w w . jav a 2 s.c om*/ Iterator k = map.keySet().iterator(); while (k.hasNext()) { String key = (String) k.next(); System.out.println("Key " + key + "; Value " + (String) map.get(key)); } Set es = map.entrySet(); System.out.println("entrySet() returns " + es.size() + " Map.Entry's"); }
From source file:cn.lhfei.spark.streaming.NginxlogSorterApp.java
public static void main(String[] args) { JavaSparkContext sc = null;// w w w . ja v a 2 s.c o m try { SparkConf conf = new SparkConf().setMaster("local").setAppName("NginxlogSorterApp"); sc = new JavaSparkContext(conf); JavaRDD<String> lines = sc.textFile(ORIGIN_PATH); JavaRDD<NginxLog> items = lines.map(new Function<String, NginxLog>() { private static final long serialVersionUID = -1530783780334450383L; @Override public NginxLog call(String v1) throws Exception { NginxLog item = new NginxLog(); String[] arrays = v1.split("[\\t]"); if (arrays.length == 3) { item.setIp(arrays[0]); item.setLiveTime(Long.parseLong(arrays[1])); item.setAgent(arrays[2]); } return item; } }); log.info("=================================Length: [{}]", items.count()); JavaPairRDD<String, Iterable<NginxLog>> keyMaps = items.groupBy(new Function<NginxLog, String>() { @Override public String call(NginxLog v1) throws Exception { return v1.getIp(); } }); log.info("=================================Group by Key Length: [{}]", keyMaps.count()); keyMaps.foreach(new VoidFunction<Tuple2<String, Iterable<NginxLog>>>() { @Override public void call(Tuple2<String, Iterable<NginxLog>> t) throws Exception { log.info("++++++++++++++++++++++++++++++++ key: {}", t._1); Iterator<NginxLog> ts = t._2().iterator(); while (ts.hasNext()) { log.info("=====================================[{}]", ts.next().toString()); } } }); FileUtils.deleteDirectory(new File(DESTI_PATH)); keyMaps.saveAsTextFile(DESTI_PATH); } catch (Exception e) { e.printStackTrace(); } finally { sc.close(); } }
From source file:GetWebPageApp.java
public static void main(String args[]) throws Exception { String resource, host, file;// w w w. j a v a 2s . com int slashPos; resource = "www.java2s.com/index.htm"; // skip HTTP:// slashPos = resource.indexOf('/'); // find host/file separator if (slashPos < 0) { resource = resource + "/"; slashPos = resource.indexOf('/'); } file = resource.substring(slashPos); // isolate host and file parts host = resource.substring(0, slashPos); System.out.println("Host to contact: '" + host + "'"); System.out.println("File to fetch : '" + file + "'"); SocketChannel channel = null; try { Charset charset = Charset.forName("ISO-8859-1"); CharsetDecoder decoder = charset.newDecoder(); CharsetEncoder encoder = charset.newEncoder(); ByteBuffer buffer = ByteBuffer.allocateDirect(1024); CharBuffer charBuffer = CharBuffer.allocate(1024); InetSocketAddress socketAddress = new InetSocketAddress(host, 80); channel = SocketChannel.open(); channel.configureBlocking(false); channel.connect(socketAddress); selector = Selector.open(); channel.register(selector, SelectionKey.OP_CONNECT | SelectionKey.OP_READ); while (selector.select(500) > 0) { Set readyKeys = selector.selectedKeys(); try { Iterator readyItor = readyKeys.iterator(); while (readyItor.hasNext()) { SelectionKey key = (SelectionKey) readyItor.next(); readyItor.remove(); SocketChannel keyChannel = (SocketChannel) key.channel(); if (key.isConnectable()) { if (keyChannel.isConnectionPending()) { keyChannel.finishConnect(); } String request = "GET " + file + " \r\n\r\n"; keyChannel.write(encoder.encode(CharBuffer.wrap(request))); } else if (key.isReadable()) { keyChannel.read(buffer); buffer.flip(); decoder.decode(buffer, charBuffer, false); charBuffer.flip(); System.out.print(charBuffer); buffer.clear(); charBuffer.clear(); } else { System.err.println("Unknown key"); } } } catch (ConcurrentModificationException e) { } } } catch (UnknownHostException e) { System.err.println(e); } catch (IOException e) { System.err.println(e); } finally { if (channel != null) { try { channel.close(); } catch (IOException ignored) { } } } System.out.println("\nDone."); }
From source file:de.tudarmstadt.ukp.experiments.argumentation.convincingness.sampling.Step7aLearningDataProducer.java
@SuppressWarnings("unchecked") public static void main(String[] args) throws IOException { String inputDir = args[0];/*from w w w . ja va2 s .co m*/ File outputDir = new File(args[1]); if (!outputDir.exists()) { outputDir.mkdirs(); } Collection<File> files = IOHelper.listXmlFiles(new File(inputDir)); // for generating ConvArgStrict use this String prefix = "no-eq_DescendingScoreArgumentPairListSorter"; // for oversampling using graph transitivity properties use this // String prefix = "generated_no-eq_AscendingScoreArgumentPairListSorter"; Iterator<File> iterator = files.iterator(); while (iterator.hasNext()) { File file = iterator.next(); if (!file.getName().startsWith(prefix)) { iterator.remove(); } } int totalGoldPairsCounter = 0; Map<String, Integer> goldDataDistribution = new HashMap<>(); DescriptiveStatistics statsPerTopic = new DescriptiveStatistics(); int totalPairsWithReasonSameAsGold = 0; DescriptiveStatistics ds = new DescriptiveStatistics(); for (File file : files) { List<AnnotatedArgumentPair> argumentPairs = (List<AnnotatedArgumentPair>) XStreamTools.getXStream() .fromXML(file); int pairsPerTopicCounter = 0; String name = file.getName().replaceAll(prefix, "").replaceAll("\\.xml", ""); PrintWriter pw = new PrintWriter(new File(outputDir, name + ".csv"), "utf-8"); pw.println("#id\tlabel\ta1\ta2"); for (AnnotatedArgumentPair argumentPair : argumentPairs) { String goldLabel = argumentPair.getGoldLabel(); if (!goldDataDistribution.containsKey(goldLabel)) { goldDataDistribution.put(goldLabel, 0); } goldDataDistribution.put(goldLabel, goldDataDistribution.get(goldLabel) + 1); pw.printf(Locale.ENGLISH, "%s\t%s\t%s\t%s%n", argumentPair.getId(), goldLabel, multipleParagraphsToSingleLine(argumentPair.getArg1().getText()), multipleParagraphsToSingleLine(argumentPair.getArg2().getText())); pairsPerTopicCounter++; int sameInOnePair = 0; // get gold reason statistics for (AnnotatedArgumentPair.MTurkAssignment assignment : argumentPair.mTurkAssignments) { String label = assignment.getValue(); if (goldLabel.equals(label)) { sameInOnePair++; } } ds.addValue(sameInOnePair); totalPairsWithReasonSameAsGold += sameInOnePair; } totalGoldPairsCounter += pairsPerTopicCounter; statsPerTopic.addValue(pairsPerTopicCounter); pw.close(); } System.out.println("Total reasons matching gold " + totalPairsWithReasonSameAsGold); System.out.println(ds); System.out.println("Total gold pairs: " + totalGoldPairsCounter); System.out.println(statsPerTopic); int totalPairs = 0; for (Integer pairs : goldDataDistribution.values()) { totalPairs += pairs; } System.out.println("Total pairs: " + totalPairs); System.out.println(goldDataDistribution); }