List of usage examples for java.util List iterator
Iterator<E> iterator();
From source file:com.discursive.jccook.xml.bardsearch.TermFreq.java
public static void main(String[] pArgs) throws Exception { logger.info("Threshold is 200"); Integer threshold = new Integer(200); IndexReader reader = IndexReader.open("index"); TermEnum enumVar = reader.terms();/*w w w .j a v a2 s . c o m*/ List termList = new ArrayList(); while (enumVar.next()) { if (enumVar.docFreq() >= threshold.intValue() && enumVar.term().field().equals("speech")) { Freq freq = new Freq(enumVar.term().text(), enumVar.docFreq()); termList.add(freq); } } Collections.sort(termList); Collections.reverse(termList); System.out.println("Frequency | Term"); Iterator iterator = termList.iterator(); while (iterator.hasNext()) { Freq freq = (Freq) iterator.next(); System.out.print(freq.frequency); System.out.println(" | " + freq.term); } }
From source file:cn.dockerfoundry.ide.eclipse.dockerfile.validator.DockerfileDelegatingValidator.java
public static void main(String[] args) { InputStream dockerfileInputStream = DockerfileDelegatingValidator.class.getResourceAsStream("dockerfile"); DockerfileDelegatingValidator validator = new DockerfileDelegatingValidator(dockerfileInputStream); Map<DockerfileValidationLevel, List<DockerfileValidationResult>> result = validator.validate(); List<DockerfileValidationResult> infos = result.get(DockerfileValidationLevel.INFO); List<DockerfileValidationResult> errors = result.get(DockerfileValidationLevel.ERROR); List<DockerfileValidationResult> warnings = result.get(DockerfileValidationLevel.WARNING); System.out.println("infos:"); for (Iterator<DockerfileValidationResult> iterator = infos.iterator(); iterator.hasNext();) { DockerfileValidationResult validationResult = (DockerfileValidationResult) iterator.next(); System.out.println(validationResult); }//ww w .j a v a2s .c o m System.out.println("errors:"); for (Iterator<DockerfileValidationResult> iterator = errors.iterator(); iterator.hasNext();) { DockerfileValidationResult validationResult = (DockerfileValidationResult) iterator.next(); System.out.println(validationResult); } System.out.println("warnings:"); for (Iterator<DockerfileValidationResult> iterator = warnings.iterator(); iterator.hasNext();) { DockerfileValidationResult validationResult = (DockerfileValidationResult) iterator.next(); System.out.println(validationResult); } }
From source file:net.semanticmetadata.lire.solr.AddImages.java
public static void main(String[] args) throws IOException, InterruptedException { BitSampling.readHashFunctions();/*from w w w . j ava 2 s . c o m*/ LinkedList<Thread> threads = new LinkedList<Thread>(); for (int j = 10; j < 21; j++) { final int tz = j; Thread t = new Thread() { @Override public void run() { try { List<File> files = FileUtils .getAllImageFiles(new File("D:\\DataSets\\WIPO-US\\jpg_us_trim\\" + tz), true); int count = 0; BufferedWriter br = new BufferedWriter(new FileWriter("add-us-" + tz + ".xml", false)); br.write("<add>\n"); for (Iterator<File> iterator = files.iterator(); iterator.hasNext();) { File file = iterator.next(); br.write(createAddDoc(file).toString()); count++; // if (count % 1000 == 0) System.out.print('.'); } br.write("</add>\n"); br.close(); } catch (IOException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } } }; t.start(); threads.add(t); } for (Iterator<Thread> iterator = threads.iterator(); iterator.hasNext();) { Thread next = iterator.next(); next.join(); } }
From source file:ValidateLicenseHeaders.java
/** * ValidateLicenseHeaders jboss-src-root * //from ww w. j a va 2s. c om * @param args */ public static void main(String[] args) throws Exception { if (args.length == 0 || args[0].startsWith("-h")) { log.info("Usage: ValidateLicenseHeaders [-addheader] jboss-src-root"); System.exit(1); } int rootArg = 0; if (args.length == 2) { if (args[0].startsWith("-add")) addDefaultHeader = true; else { log.severe("Uknown argument: " + args[0]); log.info("Usage: ValidateLicenseHeaders [-addheader] jboss-src-root"); System.exit(1); } rootArg = 1; } File jbossSrcRoot = new File(args[rootArg]); if (jbossSrcRoot.exists() == false) { log.info("Src root does not exist, check " + jbossSrcRoot.getAbsolutePath()); System.exit(1); } URL u = Thread.currentThread().getContextClassLoader() .getResource("META-INF/services/javax.xml.parsers.DocumentBuilderFactory"); System.err.println(u); // Load the valid copyright statements for the licenses File licenseInfo = new File(jbossSrcRoot, "varia/src/etc/license-info.xml"); if (licenseInfo.exists() == false) { log.severe("Failed to find the varia/src/etc/license-info.xml under the src root"); System.exit(1); } DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder db = factory.newDocumentBuilder(); Document doc = db.parse(licenseInfo); NodeList licenses = doc.getElementsByTagName("license"); for (int i = 0; i < licenses.getLength(); i++) { Element license = (Element) licenses.item(i); String key = license.getAttribute("id"); ArrayList headers = new ArrayList(); licenseHeaders.put(key, headers); NodeList copyrights = license.getElementsByTagName("terms-header"); for (int j = 0; j < copyrights.getLength(); j++) { Element copyright = (Element) copyrights.item(j); copyright.normalize(); String id = copyright.getAttribute("id"); // The id will be blank if there is no id attribute if (id.length() == 0) continue; String text = getElementContent(copyright); if (text == null) continue; // Replace all duplicate whitespace and '*' with a single space text = text.replaceAll("[\\s*]+", " "); if (text.length() == 1) continue; text = text.toLowerCase().trim(); // Replace any copyright date0-date1,date2 with copyright ... text = text.replaceAll(COPYRIGHT_REGEX, "..."); LicenseHeader lh = new LicenseHeader(id, text); headers.add(lh); } } log.fine(licenseHeaders.toString()); File[] files = jbossSrcRoot.listFiles(dotJavaFilter); log.info("Root files count: " + files.length); processSourceFiles(files, 0); log.info("Processed " + totalCount); log.info("Updated jboss headers: " + jbossCount); // Files with no headers details log.info("Files with no headers: " + noheaders.size()); FileWriter fw = new FileWriter("NoHeaders.txt"); for (Iterator iter = noheaders.iterator(); iter.hasNext();) { File f = (File) iter.next(); fw.write(f.getAbsolutePath()); fw.write('\n'); } fw.close(); // Files with unknown headers details log.info("Files with invalid headers: " + invalidheaders.size()); fw = new FileWriter("InvalidHeaders.txt"); for (Iterator iter = invalidheaders.iterator(); iter.hasNext();) { File f = (File) iter.next(); fw.write(f.getAbsolutePath()); fw.write('\n'); } fw.close(); // License usage summary log.info("Creating HeadersSummary.txt"); fw = new FileWriter("HeadersSummary.txt"); for (Iterator iter = licenseHeaders.entrySet().iterator(); iter.hasNext();) { Map.Entry entry = (Map.Entry) iter.next(); String key = (String) entry.getKey(); fw.write("+++ License type=" + key); fw.write('\n'); List list = (List) entry.getValue(); Iterator jiter = list.iterator(); while (jiter.hasNext()) { LicenseHeader lh = (LicenseHeader) jiter.next(); fw.write('\t'); fw.write(lh.id); fw.write(", count="); fw.write("" + lh.count); fw.write('\n'); } } fw.close(); }
From source file:com.cloud.utils.crypt.EncryptionSecretKeyChanger.java
public static void main(String[] args) { List<String> argsList = Arrays.asList(args); Iterator<String> iter = argsList.iterator(); String oldMSKey = null;//from ww w . j av a 2 s . c o m String oldDBKey = null; String newMSKey = null; String newDBKey = null; //Parse command-line args while (iter.hasNext()) { String arg = iter.next(); // Old MS Key if (arg.equals("-m")) { oldMSKey = iter.next(); } // Old DB Key if (arg.equals("-d")) { oldDBKey = iter.next(); } // New MS Key if (arg.equals("-n")) { newMSKey = iter.next(); } // New DB Key if (arg.equals("-e")) { newDBKey = iter.next(); } } if (oldMSKey == null || oldDBKey == null) { System.out.println("Existing MS secret key or DB secret key is not provided"); usage(); return; } if (newMSKey == null && newDBKey == null) { System.out.println("New MS secret key and DB secret are both not provided"); usage(); return; } final File dbPropsFile = PropertiesUtil.findConfigFile("db.properties"); final Properties dbProps; EncryptionSecretKeyChanger keyChanger = new EncryptionSecretKeyChanger(); StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor(); keyChanger.initEncryptor(encryptor, oldMSKey); dbProps = new EncryptableProperties(encryptor); PropertiesConfiguration backupDBProps = null; System.out.println("Parsing db.properties file"); try { dbProps.load(new FileInputStream(dbPropsFile)); backupDBProps = new PropertiesConfiguration(dbPropsFile); } catch (FileNotFoundException e) { System.out.println("db.properties file not found while reading DB secret key" + e.getMessage()); } catch (IOException e) { System.out.println("Error while reading DB secret key from db.properties" + e.getMessage()); } catch (ConfigurationException e) { e.printStackTrace(); } String dbSecretKey = null; try { dbSecretKey = dbProps.getProperty("db.cloud.encrypt.secret"); } catch (EncryptionOperationNotPossibleException e) { System.out.println("Failed to decrypt existing DB secret key from db.properties. " + e.getMessage()); return; } if (!oldDBKey.equals(dbSecretKey)) { System.out.println("Incorrect MS Secret Key or DB Secret Key"); return; } System.out.println("Secret key provided matched the key in db.properties"); final String encryptionType = dbProps.getProperty("db.cloud.encryption.type"); if (newMSKey == null) { System.out.println("No change in MS Key. Skipping migrating db.properties"); } else { if (!keyChanger.migrateProperties(dbPropsFile, dbProps, newMSKey, newDBKey)) { System.out.println("Failed to update db.properties"); return; } else { //db.properties updated successfully if (encryptionType.equals("file")) { //update key file with new MS key try { FileWriter fwriter = new FileWriter(keyFile); BufferedWriter bwriter = new BufferedWriter(fwriter); bwriter.write(newMSKey); bwriter.close(); } catch (IOException e) { System.out.println("Failed to write new secret to file. Please update the file manually"); } } } } boolean success = false; if (newDBKey == null || newDBKey.equals(oldDBKey)) { System.out.println("No change in DB Secret Key. Skipping Data Migration"); } else { EncryptionSecretKeyChecker.initEncryptorForMigration(oldMSKey); try { success = keyChanger.migrateData(oldDBKey, newDBKey); } catch (Exception e) { System.out.println("Error during data migration"); e.printStackTrace(); success = false; } } if (success) { System.out.println("Successfully updated secret key(s)"); } else { System.out.println("Data Migration failed. Reverting db.properties"); //revert db.properties try { backupDBProps.save(); } catch (ConfigurationException e) { e.printStackTrace(); } if (encryptionType.equals("file")) { //revert secret key in file try { FileWriter fwriter = new FileWriter(keyFile); BufferedWriter bwriter = new BufferedWriter(fwriter); bwriter.write(oldMSKey); bwriter.close(); } catch (IOException e) { System.out.println("Failed to revert to old secret to file. Please update the file manually"); } } } }
From source file:com.cloud.test.utils.TestClient.java
public static void main(String[] args) { String host = "http://localhost"; String port = "8080"; String testUrl = "/client/test"; int numThreads = 1; try {//w ww .j a v a2 s . c o m // Parameters List<String> argsList = Arrays.asList(args); Iterator<String> iter = argsList.iterator(); while (iter.hasNext()) { String arg = iter.next(); // host if (arg.equals("-h")) { host = "http://" + iter.next(); } if (arg.equals("-p")) { port = iter.next(); } if (arg.equals("-t")) { numThreads = Integer.parseInt(iter.next()); } if (arg.equals("-s")) { sleepTime = Long.parseLong(iter.next()); } if (arg.equals("-c")) { cleanUp = Boolean.parseBoolean(iter.next()); if (!cleanUp) sleepTime = 0L; // no need to wait if we don't ever cleanup } if (arg.equals("-r")) { repeat = Boolean.parseBoolean(iter.next()); } if (arg.equals("-u")) { numOfUsers = Integer.parseInt(iter.next()); } if (arg.equals("-i")) { internet = Boolean.parseBoolean(iter.next()); } } final String server = host + ":" + port + testUrl; s_logger.info("Starting test against server: " + server + " with " + numThreads + " thread(s)"); if (cleanUp) s_logger.info("Clean up is enabled, each test will wait " + sleepTime + " ms before cleaning up"); if (numOfUsers > 0) { s_logger.info("Pre-generating users for test of size : " + numOfUsers); users = new String[numOfUsers]; Random ran = new Random(); for (int i = 0; i < numOfUsers; i++) { users[i] = Math.abs(ran.nextInt()) + "-user"; } } for (int i = 0; i < numThreads; i++) { new Thread(new Runnable() { public void run() { do { String username = null; try { long now = System.currentTimeMillis(); Random ran = new Random(); if (users != null) { username = users[Math.abs(ran.nextInt()) % numOfUsers]; } else { username = Math.abs(ran.nextInt()) + "-user"; } NDC.push(username); String url = server + "?email=" + username + "&password=" + username + "&command=deploy"; s_logger.info("Launching test for user: " + username + " with url: " + url); HttpClient client = new HttpClient(); HttpMethod method = new GetMethod(url); int responseCode = client.executeMethod(method); boolean success = false; String reason = null; if (responseCode == 200) { if (internet) { s_logger.info("Deploy successful...waiting 5 minute before SSH tests"); Thread.sleep(300000L); // Wait 60 seconds so the linux VM can boot up. s_logger.info("Begin Linux SSH test"); reason = sshTest(method.getResponseHeader("linuxIP").getValue()); if (reason == null) { s_logger.info("Linux SSH test successful"); s_logger.info("Begin Windows SSH test"); reason = sshWinTest(method.getResponseHeader("windowsIP").getValue()); } } if (reason == null) { if (internet) { s_logger.info("Windows SSH test successful"); } else { s_logger.info("deploy test successful....now cleaning up"); if (cleanUp) { s_logger.info( "Waiting " + sleepTime + " ms before cleaning up vms"); Thread.sleep(sleepTime); } else { success = true; } } if (users == null) { s_logger.info("Sending cleanup command"); url = server + "?email=" + username + "&password=" + username + "&command=cleanup"; } else { s_logger.info("Sending stop DomR / destroy VM command"); url = server + "?email=" + username + "&password=" + username + "&command=stopDomR"; } method = new GetMethod(url); responseCode = client.executeMethod(method); if (responseCode == 200) { success = true; } else { reason = method.getStatusText(); } } else { // Just stop but don't destroy the VMs/Routers s_logger.info("SSH test failed with reason '" + reason + "', stopping VMs"); url = server + "?email=" + username + "&password=" + username + "&command=stop"; responseCode = client.executeMethod(new GetMethod(url)); } } else { // Just stop but don't destroy the VMs/Routers reason = method.getStatusText(); s_logger.info("Deploy test failed with reason '" + reason + "', stopping VMs"); url = server + "?email=" + username + "&password=" + username + "&command=stop"; client.executeMethod(new GetMethod(url)); } if (success) { s_logger.info("***** Completed test for user : " + username + " in " + ((System.currentTimeMillis() - now) / 1000L) + " seconds"); } else { s_logger.info("##### FAILED test for user : " + username + " in " + ((System.currentTimeMillis() - now) / 1000L) + " seconds with reason : " + reason); } } catch (Exception e) { s_logger.warn("Error in thread", e); try { HttpClient client = new HttpClient(); String url = server + "?email=" + username + "&password=" + username + "&command=stop"; client.executeMethod(new GetMethod(url)); } catch (Exception e1) { } } finally { NDC.clear(); } } while (repeat); } }).start(); } } catch (Exception e) { s_logger.error(e); } }
From source file:MovingPlanets.java
public static void main(String args[]) { String names[] = { "Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune", "Pluto" }; List planets = new ArrayList(); for (int i = 0, n = names.length; i < n; i++) { planets.add(names[i]);//from w w w . j a v a2 s . c om } ListIterator lit = planets.listIterator(); String s; lit.next(); lit.next(); s = (String) lit.next(); lit.remove(); lit.next(); lit.next(); lit.next(); lit.add(s); lit.next(); // Gets back just added lit.previous(); lit.previous(); s = (String) lit.previous(); lit.remove(); lit.next(); lit.next(); lit.add(s); Iterator it = planets.iterator(); while (it.hasNext()) { System.out.println(it.next()); } }
From source file:hepple.postag.POSTagger.java
/** * Main method. Runs the tagger using the arguments to find the resources * to be used for initialisation and the input file. *//*from w w w .j av a2 s. c om*/ public static void main(String[] args) { if (args.length == 0) help(); try { LongOpt[] options = new LongOpt[] { new LongOpt("help", LongOpt.NO_ARGUMENT, null, 'h'), new LongOpt("lexicon", LongOpt.NO_ARGUMENT, null, 'l'), new LongOpt("rules", LongOpt.NO_ARGUMENT, null, 'r') }; Getopt getopt = new Getopt("HepTag", args, "hl:r:", options); String lexiconUrlString = null; String rulesUrlString = null; int opt; while ((opt = getopt.getopt()) != -1) { switch (opt) { // -h case 'h': { help(); System.exit(0); break; } // -l new lexicon case 'l': { lexiconUrlString = getopt.getOptarg(); break; } // -l new lexicon case 'r': { rulesUrlString = getopt.getOptarg(); break; } default: { System.err.println("Invalid option " + args[getopt.getOptind() - 1] + "!"); System.exit(1); } }//switch(opt) } //while( (opt = g.getopt()) != -1 ) String[] fileNames = new String[args.length - getopt.getOptind()]; for (int i = getopt.getOptind(); i < args.length; i++) { fileNames[i - getopt.getOptind()] = args[i]; } URL lexiconURL = (lexiconUrlString == null) ? POSTagger.class.getResource("/hepple/resources/sample_lexicon") : new File(lexiconUrlString).toURI().toURL(); URL rulesURL = (rulesUrlString == null) ? POSTagger.class.getResource("/hepple/resources/sample_ruleset.big") : new File(rulesUrlString).toURI().toURL(); POSTagger tagger = new POSTagger(lexiconURL, rulesURL); for (int i = 0; i < fileNames.length; i++) { String file = fileNames[i]; BufferedReader reader = null; try { reader = new BufferedReader(new FileReader(file)); String line = reader.readLine(); while (line != null) { StringTokenizer tokens = new StringTokenizer(line); List<String> sentence = new ArrayList<String>(); while (tokens.hasMoreTokens()) sentence.add(tokens.nextToken()); List<List<String>> sentences = new ArrayList<List<String>>(); sentences.add(sentence); List<List<String[]>> result = tagger.runTagger(sentences); Iterator<List<String[]>> iter = result.iterator(); while (iter.hasNext()) { List<String[]> sentenceFromTagger = iter.next(); Iterator<String[]> sentIter = sentenceFromTagger.iterator(); while (sentIter.hasNext()) { String[] tag = sentIter.next(); System.out.print(tag[0] + "/" + tag[1]); if (sentIter.hasNext()) System.out.print(" "); else System.out.println(); } //while(sentIter.hasNext()) } //while(iter.hasNext()) line = reader.readLine(); } //while(line != null) } finally { IOUtils.closeQuietly(reader); } // // // // List result = tagger.runTagger(readInput(file)); // Iterator iter = result.iterator(); // while(iter.hasNext()){ // List sentence = (List)iter.next(); // Iterator sentIter = sentence.iterator(); // while(sentIter.hasNext()){ // String[] tag = (String[])sentIter.next(); // System.out.print(tag[0] + "/" + tag[1]); // if(sentIter.hasNext()) System.out.print(" "); // else System.out.println(); // }//while(sentIter.hasNext()) // }//while(iter.hasNext()) } //for(int i = 0; i < fileNames.length; i++) } catch (Exception e) { e.printStackTrace(); } }
From source file:Main.java
public static void main(String[] args) { List<Integer> numbers = new ArrayList<Integer>(); for (Integer i : Arrays.asList(0, 1, 2, 3, 4, 5, 6, 7)) numbers.add(i);//from w w w .j av a 2 s . c o m printList(numbers); // 0,1,2,3,4,5,6,7 // replaces each element with twice its value for (int index = 0; index < numbers.size(); index++) { numbers.set(index, numbers.get(index) * 2); } printList(numbers); // does nothing because list is not being changed for (Integer number : numbers) { number++; } printList(numbers); // same as above -- just different syntax for (Iterator<Integer> iter = numbers.iterator(); iter.hasNext();) { Integer number = iter.next(); number++; } printList(numbers); for (ListIterator<Integer> iter = numbers.listIterator(); iter.hasNext();) { Integer number = iter.next(); iter.add(number + 1); } printList(numbers); for (Iterator<Integer> iter = numbers.iterator(); iter.hasNext();) { Integer number = iter.next(); if (number % 2 == 0) // if number is even iter.remove(); // remove it from the collection } printList(numbers); // 1,3,5,7,9,11,13,15 // ListIterator<?> has a "set" method to replace elements for (ListIterator<Integer> iter = numbers.listIterator(); iter.hasNext();) { Integer number = iter.next(); iter.set(number / 2); // divide each element by 2 } printList(numbers); // 0,1,2,3,4,5,6,7 // Use Java 8 Lambda List<Integer> list = numbers; list.stream().forEach(elem -> System.out.println("element " + elem)); }
From source file:com.pureinfo.srm.reports.table.data.sci.SCIBySchoolStatistic.java
public static void main(String[] args) throws PureException { IProductMgr mgr = (IProductMgr) ArkContentHelper.getContentMgrOf(Product.class); IStatement stat = mgr.createQuery(//from w w w.jav a2 s . c o m "select count({this.id}) _NUM, {this.englishScience} AS _SUB from {this} group by _SUB", 0); IObjects nums = stat.executeQuery(false); DolphinObject num = null; Map map = new HashedMap(); while ((num = nums.next()) != null) { String subest = num.getStrProperty("_SUB"); if (subest == null || subest.trim().length() == 0) continue; String[] subs = subest.split(";"); int nNum = num.getIntProperty("_NUM", 0); for (int i = 0; i < subs.length; i++) { String sSub = subs[i].trim(); Integer odValue = (Integer) map.get(sSub); int sum = odValue == null ? nNum : (nNum + odValue.intValue()); map.put(sSub, new Integer(sum)); } } List l = new ArrayList(map.size()); for (Iterator iter = map.entrySet().iterator(); iter.hasNext();) { Map.Entry en = (Map.Entry) iter.next(); l.add(new Object[] { en.getKey(), en.getValue() }); } Collections.sort(l, new Comparator() { public int compare(Object _sO1, Object _sO2) { Object[] arr1 = (Object[]) _sO1; Object[] arr2 = (Object[]) _sO2; Comparable s1 = (Comparable) arr1[1]; Comparable s2 = (Comparable) arr2[01]; return s1.compareTo(s2); } }); for (Iterator iter = l.iterator(); iter.hasNext();) { Object[] arr = (Object[]) iter.next(); System.out.println(arr[0] + " = " + arr[1]); } }