List of usage examples for java.util Collection iterator
Iterator<E> iterator();
From source file:find.Main.java
public static void main(String[] args) throws Exception { Options options = getOptions();/* w w w . ja va2 s.co m*/ try { CommandLineParser parser = new GnuParser(); CommandLine line = parser.parse(options, args); File dir = new File(line.getOptionValue("dir", ".")); String name = line.getOptionValue("name", "jar"); Collection files = FindFile.find(dir, name); System.out.println("listing files in " + dir + " containing " + name); for (Iterator it = files.iterator(); it.hasNext();) { System.out.println("\t" + it.next() + "\n"); } } catch (ParseException exp) { // oops, something went wrong System.err.println("Parsing failed. Reason: " + exp.getMessage()); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("find", options); } }
From source file:MainClass.java
public static void main(String[] args) throws Exception { Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); KeyPair pair = generateRSAKeyPair(); ByteArrayOutputStream bOut = new ByteArrayOutputStream(); bOut.write(generateV1Certificate(pair).getEncoded()); bOut.close();/*from w w w . j av a 2s .c om*/ InputStream in = new ByteArrayInputStream(bOut.toByteArray()); CertificateFactory fact = CertificateFactory.getInstance("X.509", "BC"); X509Certificate x509Cert; Collection collection = new ArrayList(); while ((x509Cert = (X509Certificate) fact.generateCertificate(in)) != null) { collection.add(x509Cert); } Iterator it = collection.iterator(); while (it.hasNext()) { System.out.println("version: " + ((X509Certificate) it.next()).getVersion()); } }
From source file:Professor.java
public static void main(String[] a) throws Exception { JPAUtil util = new JPAUtil(); EntityManagerFactory emf = Persistence.createEntityManagerFactory("ProfessorService"); EntityManager em = emf.createEntityManager(); ProfessorService service = new ProfessorService(em); em.getTransaction().begin();/*from w ww .ja va2 s. c o m*/ Professor emp = service.createProfessor(1, "name", 100); emp = service.createProfessor(2, "name 2", 100); Collection emps = em.createQuery("SELECT e FROM Professor e").getResultList(); for (Iterator i = emps.iterator(); i.hasNext();) { Professor e = (Professor) i.next(); System.out.println("Professor " + e.getId() + ", " + e.getName()); } util.checkData("select * from Professor"); em.getTransaction().commit(); em.close(); emf.close(); }
From source file:com.athena.dolly.websocket.client.test.WebSocketClient.java
public static void main(String[] args) throws Exception { URI uri;// w w w . j ava 2s.c o m if (args.length > 0) { uri = new URI(args[0]); } else { uri = new URI("ws://localhost:7700/websocket"); } WebSocketClient client = new WebSocketClient(uri); client.initialize(); File directory = new File("C:/Private"); Collection<File> files = FileUtils.listFiles(directory, TrueFileFilter.TRUE, TrueFileFilter.TRUE); for (Iterator<File> iterator = files.iterator(); iterator.hasNext();) { File file = (File) iterator.next(); client.sendFile(file); } //client.sendFile(new File("C:/Temp/netty-master.zip")); client.shutdown(); }
From source file:com.github.xbn.examples.io.non_xbn.SizeOrderAllFilesInDirXmpl.java
public static final void main(String[] ignored) { File fDir = (new File("R:\\jeffy\\programming\\sandbox\\xbnjava\\xbn\\")); Collection<File> cllf = FileUtils.listFiles(fDir, (new String[] { "java" }), true); //Add all file paths to a Map, keyed by size. //It's actually a map of lists-of-files, to //allow multiple files that happen to have the //same length. TreeMap<Long, List<File>> tmFilesBySize = new TreeMap<Long, List<File>>(); Iterator<File> itrf = cllf.iterator(); while (itrf.hasNext()) { File f = itrf.next();/*from www. ja v a 2 s . co m*/ Long LLen = f.length(); if (!tmFilesBySize.containsKey(LLen)) { ArrayList<File> alf = new ArrayList<File>(); alf.add(f); tmFilesBySize.put(LLen, alf); } else { tmFilesBySize.get(LLen).add(f); } } //Iterate backwards by key through the map. For each //List<File>, iterate through the files, printing out //its size and path. ArrayList<Long> alSize = new ArrayList<Long>(tmFilesBySize.keySet()); for (int i = alSize.size() - 1; i >= 0; i--) { itrf = tmFilesBySize.get(alSize.get(i)).iterator(); while (itrf.hasNext()) { File f = itrf.next(); System.out.println(f.length() + ": " + f.getPath()); } } }
From source file:grnet.validation.XMLValidation.java
public static void main(String[] args) throws IOException { // TODO Auto-generated method ssstub Enviroment enviroment = new Enviroment(args[0]); if (enviroment.envCreation) { String schemaUrl = enviroment.getArguments().getSchemaURL(); Core core = new Core(schemaUrl); XMLSource source = new XMLSource(args[0]); File sourceFile = source.getSource(); if (sourceFile.exists()) { Collection<File> xmls = source.getXMLs(); System.out.println("Validating repository:" + sourceFile.getName()); System.out.println("Number of files to validate:" + xmls.size()); Iterator<File> iterator = xmls.iterator(); System.out.println("Validating against schema:" + schemaUrl + "..."); ValidationReport report = null; if (enviroment.getArguments().createReport().equalsIgnoreCase("true")) { report = new ValidationReport(enviroment.getArguments().getDestFolderLocation(), enviroment.getDataProviderValid().getName()); }//from w ww. ja va 2 s. c o m ConnectionFactory factory = new ConnectionFactory(); factory.setHost(enviroment.getArguments().getQueueHost()); factory.setUsername(enviroment.getArguments().getQueueUserName()); factory.setPassword(enviroment.getArguments().getQueuePassword()); while (iterator.hasNext()) { StringBuffer logString = new StringBuffer(); logString.append(sourceFile.getName()); logString.append(" " + schemaUrl); File xmlFile = iterator.next(); String name = xmlFile.getName(); name = name.substring(0, name.indexOf(".xml")); logString.append(" " + name); boolean xmlIsValid = core.validateXMLSchema(xmlFile); if (xmlIsValid) { logString.append(" " + "Valid"); slf4jLogger.info(logString.toString()); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.queueDeclare(QUEUE_NAME, false, false, false, null); channel.basicPublish("", QUEUE_NAME, null, logString.toString().getBytes()); channel.close(); connection.close(); try { if (report != null) { report.raiseValidFilesNum(); } FileUtils.copyFileToDirectory(xmlFile, enviroment.getDataProviderValid()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { logString.append(" " + "Invalid"); slf4jLogger.info(logString.toString()); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.queueDeclare(QUEUE_NAME, false, false, false, null); channel.basicPublish("", QUEUE_NAME, null, logString.toString().getBytes()); channel.close(); connection.close(); try { if (report != null) { if (enviroment.getArguments().extendedReport().equalsIgnoreCase("true")) report.appendXMLFileNameNStatus(xmlFile.getPath(), Constants.invalidData, core.getReason()); report.raiseInvalidFilesNum(); } FileUtils.copyFileToDirectory(xmlFile, enviroment.getDataProviderInValid()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } if (report != null) { report.writeErrorBank(core.getErrorBank()); report.appendGeneralInfo(); } System.out.println("Validation is done."); } } }
From source file:grnet.filter.XMLFiltering.java
public static void main(String[] args) throws IOException { // TODO Auto-generated method ssstub Enviroment enviroment = new Enviroment(args[0]); if (enviroment.envCreation) { Core core = new Core(); XMLSource source = new XMLSource(args[0]); File sourceFile = source.getSource(); if (sourceFile.exists()) { Collection<File> xmls = source.getXMLs(); System.out.println("Filtering repository:" + enviroment.dataProviderFilteredIn.getName()); System.out.println("Number of files to filter:" + xmls.size()); Iterator<File> iterator = xmls.iterator(); FilteringReport report = null; if (enviroment.getArguments().getProps().getProperty(Constants.createReport) .equalsIgnoreCase("true")) { report = new FilteringReport(enviroment.getArguments().getDestFolderLocation(), enviroment.getDataProviderFilteredIn().getName()); }/*from w w w. jav a 2 s. c o m*/ ConnectionFactory factory = new ConnectionFactory(); factory.setHost(enviroment.getArguments().getQueueHost()); factory.setUsername(enviroment.getArguments().getQueueUserName()); factory.setPassword(enviroment.getArguments().getQueuePassword()); while (iterator.hasNext()) { StringBuffer logString = new StringBuffer(); logString.append(enviroment.dataProviderFilteredIn.getName()); File xmlFile = iterator.next(); String name = xmlFile.getName(); name = name.substring(0, name.indexOf(".xml")); logString.append(" " + name); boolean xmlIsFilteredIn = core.filterXML(xmlFile, enviroment.getArguments().getQueries()); if (xmlIsFilteredIn) { logString.append(" " + "FilteredIn"); slf4jLogger.info(logString.toString()); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.queueDeclare(QUEUE_NAME, false, false, false, null); channel.basicPublish("", QUEUE_NAME, null, logString.toString().getBytes()); channel.close(); connection.close(); try { if (report != null) { report.appendXMLFileNameNStatus(xmlFile.getPath(), Constants.filteredInData); report.raiseFilteredInFilesNum(); } FileUtils.copyFileToDirectory(xmlFile, enviroment.getDataProviderFilteredIn()); } catch (IOException e) { // TODO Auto-generated catch block // e.printStackTrace(); e.printStackTrace(); System.out.println("Filtering failed."); } } else { logString.append(" " + "FilteredOut"); slf4jLogger.info(logString.toString()); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.queueDeclare(QUEUE_NAME, false, false, false, null); channel.basicPublish("", QUEUE_NAME, null, logString.toString().getBytes()); channel.close(); connection.close(); try { if (report != null) { report.appendXMLFileNameNStatus(xmlFile.getPath(), Constants.filteredOutData); report.raiseFilteredOutFilesNum(); } FileUtils.copyFileToDirectory(xmlFile, enviroment.getDataProviderFilteredOuT()); } catch (IOException e) { // TODO Auto-generated catch block // e.printStackTrace(); e.printStackTrace(); System.out.println("Filtering failed."); } } } if (report != null) { report.appendXPathExpression(enviroment.getArguments().getQueries()); report.appendGeneralInfo(); } System.out.println("Filtering is done."); } } }
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 va2s. c om*/ 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); }
From source file:br.com.autonomiccs.cloudTraces.main.GoogleTracesToCloudTracesParser.java
public static void main(String[] args) { validateArguments(args);//from www . java 2 s. c o m List<GoogleTrace> googleTraces = readAllGoogleTracesFromDataset(args[0]); logger.info(String.format("#Google traces loaded [%d]", googleTraces.size())); Collection<GoogleJob> googleJobs = buildTasksHierachyAndCreateJobList(googleTraces); buildJobsTaksByTimeMap(googleJobs); fillOutStartAndEndTimeOfJobs(googleJobs); calculateThePeakJobResourceUsage(googleJobs); GoogleJob biggestCpuUsageJob = googleJobs.iterator().next(); GoogleJob biggestMemoryUsageJob = biggestCpuUsageJob; GoogleJob lowestCpuUsageJob = googleJobs.iterator().next(); GoogleJob lowestMemoryUsageJob = lowestCpuUsageJob; for (GoogleJob googleJob : googleJobs) { if (biggestCpuUsageJob.getMaximumCpuUsageAtTime() < googleJob.getMaximumCpuUsageAtTime()) { biggestCpuUsageJob = googleJob; } if (biggestMemoryUsageJob.getMaximumMemoryUsageAtTime() < googleJob.getMaximumMemoryUsageAtTime()) { biggestMemoryUsageJob = googleJob; } if (lowestCpuUsageJob.getMaximumCpuUsageAtTime() > googleJob.getMaximumCpuUsageAtTime()) { lowestCpuUsageJob = googleJob; } if (lowestMemoryUsageJob.getMaximumMemoryUsageAtTime() > googleJob.getMaximumMemoryUsageAtTime()) { lowestMemoryUsageJob = googleJob; } } logger.info("Max job cpu usage: " + biggestCpuUsageJob); logger.info("Max job memory usage: " + biggestMemoryUsageJob); logger.info("Min job cpu usage: " + lowestCpuUsageJob); logger.info("Min job memory usage: " + lowestMemoryUsageJob); List<VirtualMachine> virtualMachines = createVmsToExecuteJobs(googleJobs); writeVmTracesToFile(virtualMachines); }
From source file:mase.jbot.JBotViewer.java
/** * @param args the command line arguments *//*from w w w . jav a 2s.co m*/ public static void main(String args[]) throws Exception { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(JBotViewer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(JBotViewer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(JBotViewer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(JBotViewer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> //</editor-fold> File jbotConfig; final File solution = new File(args[0]); if (args.length == 2) { jbotConfig = new File(args[1]); } else { // Search the individual's folder for the jbot config file File dir = solution.getParentFile(); Collection<File> listFiles = FileUtils.listFiles(dir, new String[] { "conf" }, false); if (listFiles.size() != 1) { System.out.println("Zero or more than one config files found!:\n" + listFiles.toString()); } jbotConfig = listFiles.iterator().next(); } final File jbot = jbotConfig; /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { try { new JBotViewer(jbot, solution).setVisible(true); } catch (Exception ex) { Logger.getLogger(JBotViewer.class.getName()).log(Level.SEVERE, null, ex); } } }); }