List of usage examples for java.util Iterator hasNext
boolean hasNext();
From source file:ListAlgorithms.java
public static void main(String[] args) { Provider[] providers = Security.getProviders(); Set<String> ciphers = new HashSet<String>(); Set<String> keyAgreements = new HashSet<String>(); Set<String> macs = new HashSet<String>(); Set<String> messageDigests = new HashSet<String>(); Set<String> signatures = new HashSet<String>(); for (int i = 0; i != providers.length; i++) { Iterator it = providers[i].keySet().iterator(); while (it.hasNext()) { String entry = (String) it.next(); if (entry.startsWith("Alg.Alias.")) { entry = entry.substring("Alg.Alias.".length()); }/*from w w w .java 2s . c om*/ if (entry.startsWith("Cipher.")) { ciphers.add(entry.substring("Cipher.".length())); } else if (entry.startsWith("KeyAgreement.")) { keyAgreements.add(entry.substring("KeyAgreement.".length())); } else if (entry.startsWith("Mac.")) { macs.add(entry.substring("Mac.".length())); } else if (entry.startsWith("MessageDigest.")) { messageDigests.add(entry.substring("MessageDigest.".length())); } else if (entry.startsWith("Signature.")) { signatures.add(entry.substring("Signature.".length())); } } } printSet("Ciphers", ciphers); printSet("KeyAgreeents", keyAgreements); printSet("Macs", macs); printSet("MessageDigests", messageDigests); printSet("Signatures", signatures); }
From source file:be.redlab.maven.yamlprops.create.YamlConvertCli.java
public static void main(String... args) throws IOException { CommandLineParser parser = new DefaultParser(); Options options = new Options(); HelpFormatter formatter = new HelpFormatter(); options.addOption(Option.builder("s").argName("source").desc("the source folder or file to convert") .longOpt("source").hasArg(true).build()); options.addOption(Option.builder("t").argName("target").desc("the target file to store in") .longOpt("target").hasArg(true).build()); options.addOption(Option.builder("h").desc("print help").build()); try {/*from w ww .j av a 2 s.co m*/ CommandLine cmd = parser.parse(options, args); if (cmd.hasOption('h')) { formatter.printHelp("converter", options); } File source = new File(cmd.getOptionValue("s", System.getProperty("user.dir"))); String name = source.getName(); if (source.isDirectory()) { PropertiesToYamlConverter yamlConverter = new PropertiesToYamlConverter(); String[] ext = { "properties" }; Iterator<File> fileIterator = FileUtils.iterateFiles(source, ext, true); while (fileIterator.hasNext()) { File next = fileIterator.next(); System.out.println(next); String s = StringUtils.removeStart(next.getParentFile().getPath(), source.getPath()); System.out.println(s); String f = StringUtils.split(s, IOUtils.DIR_SEPARATOR)[0]; System.out.println("key = " + f); Properties p = new Properties(); try { p.load(new FileReader(next)); yamlConverter.addProperties(f, p); } catch (IOException e) { e.printStackTrace(); } } FileWriter fileWriter = new FileWriter( new File(source.getParentFile(), StringUtils.substringBeforeLast(name, ".") + ".yaml")); yamlConverter.writeYaml(fileWriter); fileWriter.close(); } else { Properties p = new Properties(); p.load(new FileReader(source)); FileWriter fileWriter = new FileWriter( new File(source.getParentFile(), StringUtils.substringBeforeLast(name, ".") + ".yaml")); new PropertiesToYamlConverter().addProperties(name, p).writeYaml(fileWriter); fileWriter.close(); } } catch (ParseException e) { e.printStackTrace(); formatter.printHelp("converter", options); } }
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(/* ww w . j a v a2 s.c om*/ "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:cn.lhfei.spark.streaming.NginxlogSorterApp.java
public static void main(String[] args) { JavaSparkContext sc = null;/*from w ww .j a va2 s . c om*/ 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: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()); }/* w ww . ja v a2 s .com*/ }
From source file:edu.cmu.sv.modelinference.runner.Main.java
public static void main(String[] args) { Options cmdOpts = createCmdOptions(); CommandLineParser parser = new DefaultParser(); CommandLine cmd = null;//from www. j a v a 2 s .c o m try { cmd = parser.parse(cmdOpts, args, true); } catch (ParseException exp) { logger.error(exp.getMessage()); System.err.println(exp.getMessage()); Util.printHelpAndExit(Main.class, cmdOpts); } String inputType = cmd.getOptionValue(INPUT_TYPE_ARG); String tool = cmd.getOptionValue(TOOL_TYPE_ARG); String logFile = cmd.getOptionValue(LOG_FILE_ARG).replaceFirst("^~", System.getProperty("user.home")); LogHandler<?> logHandler = null; boolean found = false; for (LogHandler<?> lh : logHandlers) { if (lh.getHandlerName().equals(tool)) { logHandler = lh; found = true; break; } } if (!found) { StringBuilder sb = new StringBuilder(); Iterator<LogHandler<?>> logIter = logHandlers.iterator(); while (logIter.hasNext()) { sb.append(logIter.next().getHandlerName()); if (logIter.hasNext()) sb.append(", "); } logger.error("Did not find tool for arg " + tool); System.err.println("Supported tools: " + Util.getSupportedHandlersString(logHandlers)); Util.printHelpAndExit(Main.class, cmdOpts); } logger.info("Using loghandler for logtype: " + logHandler.getHandlerName()); logHandler.process(logFile, inputType, cmd.getArgs()); }
From source file:GetWebPageApp.java
public static void main(String args[]) throws Exception { String resource, host, file;// www .j a v a 2 s . co m 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: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."); }// w ww .jav a 2s . c o m }
From source file:net.sourceforge.happybank.facade.BankTest.java
/** * Test method./*from w ww. j a v a 2 s .c o m*/ * * @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:x595.Main.java
public static void main(String... args) { @SuppressWarnings("resource") ApplicationContext ctx = new AnnotationConfigApplicationContext(JpaConfig.class); CarRepository repo = ctx.getBean(CarRepository.class); log("Start testing CarRepository"); LicenceInfo info1 = new LicenceInfo("Jane Doe", "jane@corp.com", new Date(), "N17D3E"); LicenceInfo info2 = new LicenceInfo("Josh Maxwell", "josh@googol.com", new Date(), "G99331"); LicenceInfo info3 = new LicenceInfo("JD", "saxe@me.com", new Date(), "HL9010"); LicenceInfo info4 = new LicenceInfo("Triple corp", "triple@doodle.org", new Date(), "JDC13X"); LicenceInfo info5 = new LicenceInfo("JD", "pro4@k5.com", new Date(), "A75Dc1"); Car c1 = new Car("AMG", "A4", 2012, 110, info1); Car c2 = new Car("Genesis", "G20", 2008, 170, info2); Car c3 = new Car("Lena", "sigma", 2015, 150, info3); Car c4 = new Car("AMG", "A7", 2010, 130, info4); Car c5 = new Car("Tesla", "T1", 2011, 90, info5); log("Part 0. insert cars"); repo.save(c1);/*from ww w . j a va 2s . c o m*/ repo.save(c2); repo.save(c3); repo.save(c4); repo.save(c5); Iterator<Car> it = repo.findAll().iterator(); log("Part 0. result of inserted car: "); while (it.hasNext()) { log(it.next().toString()); } log("Part 1. findByOrderByMakerAsc"); it = repo.findByOrderByMakerAsc().iterator(); log("Result: "); while (it.hasNext()) { log(it.next().toString()); } log("Part 2. findByLicenseInfoOwnerName"); it = repo.findByLicenseInfoOwnerName("JD").iterator(); log("Result: "); while (it.hasNext()) { log(it.next().toString()); } log("Part 3. findByMaker"); it = repo.findByMaker("AMG").iterator(); log("Result: "); while (it.hasNext()) { log(it.next().toString()); } log("Part 4. findByMakeYearBetween"); it = repo.findByMakeYearBetween(2010, 2013).iterator(); log("Result: "); while (it.hasNext()) { log(it.next().toString()); } log("Part 5. findByLicenseInfoLicensePlateNumber"); Car c = repo.findByLicenseInfoLicensePlateNumber("HL9010"); log("Result: "); log(c.toString()); }