List of usage examples for java.util Iterator next
E next();
From source file:TwitterClustering.java
public static void main(String[] args) throws FileNotFoundException, IOException { // TODO code application logic here File outFile = new File(args[3]); Scanner s = new Scanner(new File(args[1])).useDelimiter(","); JSONParser parser = new JSONParser(); Set<Cluster> clusterSet = new HashSet<Cluster>(); HashMap<String, Tweet> tweets = new HashMap(); FileWriter fw = new FileWriter(outFile.getAbsoluteFile()); BufferedWriter bw = new BufferedWriter(fw); // init//from ww w.j a v a 2 s . c om try { Object obj = parser.parse(new FileReader(args[2])); JSONArray jsonArray = (JSONArray) obj; for (int i = 0; i < jsonArray.size(); i++) { Tweet twt = new Tweet(); JSONObject jObj = (JSONObject) jsonArray.get(i); String text = jObj.get("text").toString(); long sum = 0; for (int y = 0; y < text.toCharArray().length; y++) { sum += (int) text.toCharArray()[y]; } String[] token = text.split(" "); String tID = jObj.get("id").toString(); Set<String> mySet = new HashSet<String>(Arrays.asList(token)); twt.setAttributeValue(sum); twt.setText(mySet); twt.setTweetID(tID); tweets.put(tID, twt); } // preparing initial clusters int i = 0; while (s.hasNext()) { String id = s.next();// id Tweet t = tweets.get(id.trim()); clusterSet.add(new Cluster(i + 1, t, new LinkedList())); i++; } Iterator it = tweets.entrySet().iterator(); for (int l = 0; l < 2; l++) { // limit to 25 iterations while (it.hasNext()) { Map.Entry me = (Map.Entry) it.next(); // calculate distance to each centroid Tweet p = (Tweet) me.getValue(); HashMap<Cluster, Float> distMap = new HashMap(); for (Cluster clust : clusterSet) { distMap.put(clust, jaccardDistance(p.getText(), clust.getCentroid().getText())); } HashMap<Cluster, Float> sorted = (HashMap<Cluster, Float>) sortByValue(distMap); sorted.keySet().iterator().next().getMembers().add(p); } // calculate new centroid and update Clusterset for (Cluster clust : clusterSet) { TreeMap<String, Long> tDistMap = new TreeMap(); Tweet newCentroid = null; Long avgSumDist = new Long(0); for (int j = 0; j < clust.getMembers().size(); j++) { avgSumDist += clust.getMembers().get(j).getAttributeValue(); tDistMap.put(clust.getMembers().get(j).getTweetID(), clust.getMembers().get(j).getAttributeValue()); } if (clust.getMembers().size() != 0) { avgSumDist /= (clust.getMembers().size()); } ArrayList<Long> listValues = new ArrayList<Long>(tDistMap.values()); if (tDistMap.containsValue(findClosestNumber(listValues, avgSumDist))) { // found closest newCentroid = tweets .get(getKeyByValue(tDistMap, findClosestNumber(listValues, avgSumDist))); clust.setCentroid(newCentroid); } } } // create an iterator Iterator iterator = clusterSet.iterator(); // check values while (iterator.hasNext()) { Cluster c = (Cluster) iterator.next(); bw.write(c.getId() + "\t"); System.out.print(c.getId() + "\t"); for (Tweet t : c.getMembers()) { bw.write(t.getTweetID() + ", "); System.out.print(t.getTweetID() + ","); } bw.write("\n"); System.out.println(""); } System.out.println(""); System.out.println("SSE " + sumSquaredErrror(clusterSet)); } catch (Exception e) { e.printStackTrace(); } finally { bw.close(); fw.close(); } }
From source file:com.github.aliteralmind.codelet.examples.non_xbn.PrintJDBlocksStartStopLineNumsXmpl.java
/** <p>The main function.</p> *//*ww w.j av a2 s . com*/ public static final void main(String[] as_1RqdJavaSourcePath) { //Read command-line parameter String sJPath = null; try { sJPath = as_1RqdJavaSourcePath[0]; } catch (ArrayIndexOutOfBoundsException aibx) { throw new NullPointerException( "Missing one-and-only required parameter: Path to java source-code file."); } System.out.println("Java source: " + sJPath); //Establish line-iterator Iterator<String> lineItr = null; try { lineItr = FileUtils.lineIterator(new File(sJPath)); //Throws npx if null } catch (IOException iox) { throw new RTIOException("PrintJDBlocksStartStopLinesXmpl", iox); } Pattern pTrmdJDBlockStart = Pattern.compile("^[\\t ]*/\\*\\*"); String sDD = ".."; int lineNum = 1; boolean bInJDBlock = false; while (lineItr.hasNext()) { String sLn = lineItr.next(); if (!bInJDBlock) { if (pTrmdJDBlockStart.matcher(sLn).matches()) { bInJDBlock = true; System.out.print(lineNum + sDD); } } else if (sLn.indexOf("*/") != -1) { bInJDBlock = false; System.out.println(lineNum); } lineNum++; } if (bInJDBlock) { throw new IllegalStateException("Reach end of file. JavaDoc not closed."); } }
From source file:edu.cornell.med.icb.goby.reads.ColorSpaceConverter.java
public static void main(final String[] args) throws JSAPException, IOException { final JSAP jsap = new JSAP(); final FlaggedOption sequenceOption = new FlaggedOption("input"); sequenceOption.setRequired(true);/*ww w . j a v a 2 s . co m*/ sequenceOption.setLongFlag("input"); sequenceOption.setShortFlag('i'); sequenceOption.setStringParser(FileStringParser.getParser().setMustBeFile(true).setMustExist(true)); sequenceOption.setHelp("The input file (in Fasta format) to convert"); jsap.registerParameter(sequenceOption); final FlaggedOption outputOption = new FlaggedOption("output"); outputOption.setRequired(false); outputOption.setLongFlag("output"); outputOption.setShortFlag('o'); outputOption.setStringParser(FileStringParser.getParser().setMustBeFile(true)); outputOption.setHelp("The output file to write to (default = stdout)"); jsap.registerParameter(outputOption); final FlaggedOption titleOption = new FlaggedOption("title"); titleOption.setRequired(false); titleOption.setLongFlag("title"); titleOption.setShortFlag('t'); titleOption.setHelp("Title for this conversion"); jsap.registerParameter(titleOption); final Switch verboseOption = new Switch("verbose"); verboseOption.setLongFlag("verbose"); verboseOption.setShortFlag('v'); verboseOption.setHelp("Verbose output"); jsap.registerParameter(verboseOption); final Switch helpOption = new Switch("help"); helpOption.setLongFlag("help"); helpOption.setShortFlag('h'); helpOption.setHelp("Print this message"); jsap.registerParameter(helpOption); jsap.setUsage("Usage: " + ColorSpaceConverter.class.getName() + " " + jsap.getUsage()); final JSAPResult result = jsap.parse(args); if (result.getBoolean("help")) { System.out.println(jsap.getHelp()); System.exit(0); } if (!result.success()) { final Iterator<String> errors = result.getErrorMessageIterator(); while (errors.hasNext()) { System.err.println(errors.next()); } System.err.println(jsap.getUsage()); System.exit(1); } final boolean verbose = result.getBoolean("verbose"); final File sequenceFile = result.getFile("input"); if (verbose) { System.out.println("Reading sequence from: " + sequenceFile); } // extract the title to use for the output header final String title; if (result.contains("title")) { title = result.getString("title"); } else { title = sequenceFile.getName(); } Reader inputReader = null; PrintWriter outputWriter = null; try { if ("gz".equals(FilenameUtils.getExtension(sequenceFile.getName()))) { inputReader = new InputStreamReader(new GZIPInputStream(FileUtils.openInputStream(sequenceFile))); } else { inputReader = new FileReader(sequenceFile); } final FastaParser fastaParser = new FastaParser(inputReader); final File outputFile = result.getFile("output"); final OutputStream outputStream; if (outputFile != null) { outputStream = FileUtils.openOutputStream(outputFile); if (verbose) { System.out.println("Writing sequence : " + outputFile); } } else { outputStream = System.out; } outputWriter = new PrintWriter(outputStream); // write the header portion of the output outputWriter.print("# "); outputWriter.print(new Date()); outputWriter.print(' '); outputWriter.print(ColorSpaceConverter.class.getName()); for (final String arg : args) { outputWriter.print(' '); outputWriter.print(arg); } outputWriter.println(); outputWriter.print("# Cwd: "); outputWriter.println(new File(".").getCanonicalPath()); outputWriter.print("# Title: "); outputWriter.println(title); // now parse the input sequence long sequenceCount = 0; final MutableString descriptionLine = new MutableString(); final MutableString sequence = new MutableString(); final MutableString colorSpaceSequence = new MutableString(); while (fastaParser.hasNext()) { fastaParser.next(descriptionLine, sequence); outputWriter.print('>'); outputWriter.println(descriptionLine); convert(sequence, colorSpaceSequence); CompactToFastaMode.writeSequence(outputWriter, colorSpaceSequence); sequenceCount++; if (verbose && sequenceCount % 10000 == 0) { System.out.println("Converted " + sequenceCount + " entries"); } } if (verbose) { System.out.println("Conversion complete!"); } } finally { IOUtils.closeQuietly(inputReader); IOUtils.closeQuietly(outputWriter); } }
From source file:com.github.liyp.test.TestMain.java
@SuppressWarnings("unchecked") public static void main(String[] args) { // add a shutdown hook to stop the server Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { @Override//from w w w . ja v a 2 s . c o m public void run() { System.out.println("########### shoutdown begin...."); try { Thread.sleep(10000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("########### shoutdown end...."); } })); System.out.println(args.length); Iterator<String> iterator1 = IteratorUtils .arrayIterator(new String[] { "one", "two", "three", "11", "22", "AB" }); Iterator<String> iterator2 = IteratorUtils.arrayIterator(new String[] { "a", "b", "c", "33", "ab", "aB" }); Iterator<String> chainedIter = IteratorUtils.chainedIterator(iterator1, iterator2); System.out.println("=================="); Iterator<String> iter = IteratorUtils.filteredIterator(chainedIter, new Predicate() { @Override public boolean evaluate(Object arg0) { System.out.println("xx:" + arg0.toString()); String str = (String) arg0; return str.matches("([a-z]|[A-Z]){2}"); } }); while (iter.hasNext()) { System.out.println(iter.next()); } System.out.println("==================="); System.out.println("asas".matches("[a-z]{4}")); System.out.println("Y".equals(null)); System.out.println(String.format("%02d", 1000L)); System.out.println(ArrayUtils.toString(splitAndTrim(" 11, 21,12 ,", ","))); System.out.println(new ArrayList<String>().toString()); JSONObject json = new JSONObject("{\"keynull\":null}"); json.put("bool", false); json.put("keya", "as"); json.put("key2", 2212222222222222222L); System.out.println(json); System.out.println(json.get("keynull").equals(null)); String a = String.format("{\"id\":%d,\"method\":\"testCrossSync\"," + "\"circle\":%d},\"isEnd\":true", 1, 1); System.out.println(a.getBytes().length); System.out.println(new String[] { "a", "b" }); System.out.println(new JSONArray("[\"aa\",\"\"]")); String data = String.format("%9d %s", 1, RandomStringUtils.randomAlphanumeric(10)); System.out.println(data.getBytes().length); System.out.println(ArrayUtils.toString("1|2| 3| 333||| 3".split("\\|"))); JSONObject j1 = new JSONObject("{\"a\":\"11111\"}"); JSONObject j2 = new JSONObject(j1.toString()); j2.put("b", "22222"); System.out.println(j1 + " | " + j2); System.out.println("======================"); String regex = "\\d+(\\-\\d+){2} \\d+(:\\d+){2}"; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher("2015-12-28 15:46:14 _NC250_MD:motion de\n"); String eventDate = matcher.find() ? matcher.group() : ""; System.out.println(eventDate); }
From source file:akori.AKORI.java
public static void main(String[] args) throws IOException, InterruptedException { System.out.println("esto es AKORI"); URL = "http://www.mbauchile.cl"; PATH = "E:\\NetBeansProjects\\AKORI\\"; NAME = "mbauchile.png"; // Extrar DOM tree Document doc = Jsoup.connect(URL).timeout(0).get(); // The Firefox driver supports javascript WebDriver driver = new FirefoxDriver(); driver.manage().window().maximize(); System.out.println(driver.manage().window().getSize().toString()); System.out.println(driver.manage().window().getPosition().toString()); int xmax = driver.manage().window().getSize().width; int ymax = driver.manage().window().getSize().height; // Go to the URL page driver.get(URL);/*from w w w . j a v a2 s. c o m*/ File screen = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE); FileUtils.copyFile(screen, new File(PATH + NAME)); BufferedImage img = ImageIO.read(new File(PATH + NAME)); //Graphics2D graph = img.createGraphics(); BufferedImage img1 = new BufferedImage(xmax, ymax, BufferedImage.TYPE_INT_ARGB); Graphics2D graph1 = img.createGraphics(); double[][] matrix = new double[ymax][xmax]; BufferedReader in = new BufferedReader(new FileReader("et.txt")); String linea; double max = 0; graph1.drawImage(img, 0, 0, null); HashMap<String, Integer> lista = new HashMap<String, Integer>(); int count = 0; for (int i = 0; (linea = in.readLine()) != null && i < 10000; ++i) { String[] datos = linea.split(","); int x = (int) Double.parseDouble(datos[0]); int y = (int) Double.parseDouble(datos[2]); long time = Double.valueOf(datos[4]).longValue(); if (x >= xmax || y >= ymax) continue; if (time < 691215) continue; if (time > 705648) break; if (lista.containsKey(x + "," + y)) lista.put(x + "," + y, lista.get(x + "," + y) + 1); else lista.put(x + "," + y, 1); ++count; } System.out.println(count); in.close(); Iterator iter = lista.entrySet().iterator(); Map.Entry e; for (String key : lista.keySet()) { Integer i = lista.get(key); if (max < i) max = i; } System.out.println(max); max = 0; while (iter.hasNext()) { e = (Map.Entry) iter.next(); String xy = (String) e.getKey(); String[] datos = xy.split(","); int x = Integer.parseInt(datos[0]); int y = Integer.parseInt(datos[1]); matrix[y][x] += (int) e.getValue(); double aux; if ((aux = normalMatrix(matrix, y, x, ((int) e.getValue()) * 4)) > max) { max = aux; } //normalMatrix(matrix,x,y,20); if (matrix[y][x] > max) max = matrix[y][x]; } int A, R, G, B, n; for (int i = 0; i < xmax; ++i) { for (int j = 0; j < ymax; ++j) { if (matrix[j][i] != 0) { n = (int) Math.round(matrix[j][i] * 100 / max); R = Math.round((255 * n) / 100); G = Math.round((255 * (100 - n)) / 100); B = 0; A = Math.round((255 * n) / 100); ; if (R > 255) R = 255; if (R < 0) R = 0; if (G > 255) G = 255; if (G < 0) G = 0; if (R < 50) A = 0; graph1.setColor(new Color(R, G, B, A)); graph1.fillOval(i, j, 1, 1); } } } //graph1.dispose(); ImageIO.write(img, "png", new File("example.png")); System.out.println(max); graph1.setColor(Color.RED); // Extraer elementos Elements e1 = doc.body().getAllElements(); int i = 1; ArrayList<String> tags = new ArrayList<String>(); for (Element temp : e1) { if (tags.indexOf(temp.tagName()) == -1) { tags.add(temp.tagName()); List<WebElement> query = driver.findElements(By.tagName(temp.tagName())); for (WebElement temp1 : query) { Point po = temp1.getLocation(); Dimension d = temp1.getSize(); if (d.width <= 0 || d.height <= 0 || po.x < 0 || po.y < 0) continue; System.out.println(i + " " + temp.nodeName()); System.out.println(" x: " + po.x + " y: " + po.y); System.out.println(" width: " + d.width + " height: " + d.height); graph1.draw(new Rectangle(po.x, po.y, d.width, d.height)); ++i; } } } graph1.dispose(); ImageIO.write(img, "png", new File(PATH + NAME)); driver.quit(); }
From source file:com.thesmartweb.vivliocrawlermaven.VivlioCrawlerMavenMain.java
/** * @param args the command line arguments *//*from w w w.j a v a 2 s .co m*/ public static void main(String[] args) { // TODO code application logic here try { OaiPmhServer server = new OaiPmhServer("http://vivliothmmy.ee.auth.gr/cgi/oai2"); RecordsList listRecords = server.listRecords("oai_dc");//we capture all the records in oai dc format List<VivlioCrawlerMavenMain> listtotal = new ArrayList<VivlioCrawlerMavenMain>(); //we capture all the names of the professors and former professor of ECE of AUTH from a txt file //change the directory to yours List<String> profs = Files.readAllLines(Paths.get( "/home/themis/NetBeansProjects/VivlioCrawlerMaven/src/main/java/com/thesmartweb/vivliocrawlermaven/profs.txt")); boolean more = true;//it is a flag used if we encounter more entries than the initial capture JSONArray array = new JSONArray();//it is going to be our final total json array JSONObject jsonObject = new JSONObject();//it is going to be our final total json object while (more) { for (Record rec : listRecords.asList()) { VivlioCrawlerMavenMain vc = new VivlioCrawlerMavenMain(); Element metadata = rec.getMetadata(); if (metadata != null) { //System.out.println(rec.getMetadataAsString()); List<Element> elements = metadata.elements(); //System.out.println(metadata.getStringValue()); for (Element element : elements) { String name = element.getName(); //we get the title, remove \r, \n and beginning and trailing whitespace if (name.equalsIgnoreCase("title")) { vc.title = element.getStringValue(); vc.title = vc.title.trim(); vc.title = vc.title.replaceAll("(\\r|\\n)", ""); if (!(vc.title.endsWith("."))) { vc.title = vc.title + ".";//we also add dot in the end for the titles to be uniformed } } if (name.equalsIgnoreCase("creator")) { vc.creators.add(element.getStringValue());//we capture the students' names } if (name.equalsIgnoreCase("subject")) { vc.subjects.add(element.getStringValue());//we capture the subjects } if (name.equalsIgnoreCase("description")) { vc.description = element.getStringValue();//we capture the abstract } if (name.equalsIgnoreCase("date")) { vc.datestring = element.getStringValue(); } if (name.equalsIgnoreCase("identifier")) { if (element.getStringValue().contains("http://")) { vc.thesisFiles.add(element.getStringValue());//we capture the url of the thesis whole file if (vc.thesisURL == null) { vc.thesisURL = element.getStringValue().substring(0, 32); } } //if the identifier contains the title then it must be the citation //out of the citation we need to extract the supevisor's name if (element.getStringValue().contains(vc.title.substring(0, 10))) { vc.citation = element.getStringValue(); vc.supervisor = element.getStringValue(); Iterator profsIterator = profs.iterator(); vc.supervisor = vc.supervisor.replace(vc.title, "");//we remove the title out of the citation //if we have two students we remove the first occurence of "" which stands for "and" if (vc.creators.size() == 2) { vc.supervisor = vc.supervisor.replaceFirst("", ""); } //we remove the students' names Iterator creatorsIterator = vc.creators.iterator(); while (creatorsIterator.hasNext()) { vc.supervisor = vc.supervisor.replace(creatorsIterator.next().toString(), ""); } boolean profFlag = false;//flag used that declares that we found the professor that was supervisor while (profsIterator.hasNext() && !profFlag) { String prof = profsIterator.next().toString(); //we split the professor's name to surname and name //because some entries have first the surname and others first the name String[] profSplitted = prof.split("\\s+"); String supervisorCleared = vc.supervisor; supervisorCleared = supervisorCleared.replaceAll("\\s+", "");//we clear the white space supervisorCleared = supervisorCleared.replaceAll("(\\r|\\n)", "");//we remove the \r\n //now we check if the citation includes any name of the professors from the txt if (supervisorCleared.contains(profSplitted[0]) && supervisorCleared.contains(profSplitted[1])) { vc.supervisor = prof; profFlag = true; } } //if we don't find the name of the supervisor, we have to perform string manipulation to extract it if (!profFlag) { vc.supervisor = vc.supervisor.trim(); //we remove the word "" which stands for "Thessaloniki" and "" which stands for Greece if (vc.supervisor.contains("")) { vc.supervisor = vc.supervisor.replaceFirst("", ""); } if (vc.supervisor.contains("")) { vc.supervisor = vc.supervisor.replaceFirst("", ""); } if (vc.supervisor.contains("")) { vc.supervisor = vc.supervisor.replaceFirst("", ""); } if (vc.supervisor.contains("")) { vc.supervisor = vc.supervisor.replaceFirst("", ""); } //we remove the year and then we should be left only with the supervisor's name vc.supervisor = vc.supervisor.replace("(", ""); vc.supervisor = vc.supervisor.trim(); vc.supervisor = vc.supervisor.replace(")", ""); vc.supervisor = vc.supervisor.trim(); vc.supervisor = vc.supervisor.replace(",", ""); vc.supervisor = vc.supervisor.trim(); vc.supervisor = vc.supervisor.replace(".", ""); vc.supervisor = vc.supervisor.trim(); vc.supervisor = vc.supervisor.replace(vc.datestring.substring(0, 4), ""); vc.supervisor = vc.supervisor.trim(); } //we put everything in a json object JSONObject obj = new JSONObject(); obj.put("title", vc.title); obj.put("description", vc.description); JSONArray creatorsArray = new JSONArray(); creatorsArray.add(vc.creators); obj.put("creators", creatorsArray); JSONArray subjectsArray = new JSONArray(); List<String> subjectsList = new ArrayList<String>(vc.subjects); subjectsArray.add(subjectsList); obj.put("subjects", subjectsArray); obj.put("datestring", vc.datestring); JSONArray thesisFilesArray = new JSONArray(); thesisFilesArray.add(vc.thesisFiles); obj.put("thesisFiles", thesisFilesArray); obj.put("thesisURL", vc.thesisURL); obj.put("supervisor", vc.supervisor); obj.put("citation", vc.citation); //if you are using JSON.simple do this array.add(obj); } } } listtotal.add(vc);//a list containing all the objects //it is not used for now, but created for potential extension of the work } } //the following if clause searches for new records if (listRecords.getResumptionToken() != null) { listRecords = server.listRecords(listRecords.getResumptionToken()); } else { more = false; } } //we print which records did not have a supervisor for (VivlioCrawlerMavenMain vctest : listtotal) { if (vctest.supervisor == null) { System.out.println(vctest.title); System.out.println(vctest.citation); } } //we create a pretty json with GSON and we write it into a file jsonObject.put("VivliothmmyOldArray", array); JsonParser parser = new JsonParser(); JsonObject json = parser.parse(jsonObject.toJSONString()).getAsJsonObject(); Gson gson = new GsonBuilder().setPrettyPrinting().create(); String prettyJson = gson.toJson(json); try { FileWriter file = new FileWriter( "/home/themis/NetBeansProjects/VivlioCrawlerMaven/src/main/java/com/thesmartweb/vivliocrawlermaven/VivliothmmyOldRecords.json"); file.write(prettyJson); file.flush(); file.close(); } catch (IOException e) { System.out.println("Exception: " + e); } //System.out.print(prettyJson); //int j=0; } catch (OAIException | IOException e) { System.out.println("Exception: " + e); } }
From source file:org.openiot.gsn.utils.VSMonitor.java
public static void main(String[] args) { PropertyConfigurator.configure(DEFAULT_GSN_LOG4J_PROPERTIES); String configFileName;/*from w ww.j av a2s.c o m*/ if (args.length >= 2) { configFileName = args[0]; System.out.println("Using config file: " + configFileName); for (int i = 1; i < args.length; i++) { System.out.println("Adding e-mail: " + args[i]); listOfMails.add(args[i]); } } else { System.out.println("Usage java -jar VSMonitor.jar <config_file> <list_of_mails>"); System.out.println("e.g. java -jar VSMonitor.jar conf/monitoring.cfg user@gmail.com admin@gmail.com"); return; } initFromFile(configFileName); // for each monitored GSN server Iterator iter = listOfGSNSessions.iterator(); while (iter.hasNext()) { try { readStatus((GSNSessionAddress) iter.next()); } catch (Exception e) { logger.error("Exception: " + e.getMessage()); logger.error("StackTrace:\n" + getStackTrace(e)); } } checkUpdateTimes(); // Generate Report report.append("\n[ERROR]\n" + errorsBuffer).append("\n[WARNING]\n" + warningsBuffer) .append("\n[INFO]\n" + infosBuffer); if ((nSensorsLate > 0) || (nHostsDown > 0)) { summary.append("WARNING: "); if (nHostsDown > 0) summary.append(nHostsDown + " host(s) down. "); if (nSensorsLate > 0) summary.append(nSensorsLate + " sensor(s) not updated. "); // Send e-mail only if there are errors try { sendMail(); } catch (EmailException e) { logger.error("Cannot send e-mail. " + e.getMessage()); logger.error("StackTrace:\n" + getStackTrace(e)); } } // Showing report System.out.println(summary); System.out.println(report); }
From source file:gsn.utils.VSMonitor.java
public static void main(String[] args) { String configFileName;/* w w w . j a va2 s. c om*/ if (args.length >= 2) { configFileName = args[0]; System.out.println("Using config file: " + configFileName); for (int i = 1; i < args.length; i++) { System.out.println("Adding e-mail: " + args[i]); listOfMails.add(args[i]); } } else { System.out.println("Usage java -jar VSMonitor.jar <config_file> <list_of_mails>"); System.out.println("e.g. java -jar VSMonitor.jar conf/monitoring.cfg user@gmail.com admin@gmail.com"); return; } initFromFile(configFileName); // for each monitored GSN server Iterator iter = listOfGSNSessions.iterator(); while (iter.hasNext()) { try { readStatus((GSNSessionAddress) iter.next()); } catch (Exception e) { logger.error("Exception: " + e.getMessage()); logger.error("StackTrace:\n" + getStackTrace(e)); } } checkUpdateTimes(); // Generate Report report.append("\n[ERROR]\n" + errorsBuffer).append("\n[WARNING]\n" + warningsBuffer) .append("\n[INFO]\n" + infosBuffer); if ((nSensorsLate > 0) || (nHostsDown > 0)) { summary.append("WARNING: "); if (nHostsDown > 0) summary.append(nHostsDown + " host(s) down. "); if (nSensorsLate > 0) summary.append(nSensorsLate + " sensor(s) not updated. "); // Send e-mail only if there are errors try { sendMail(); } catch (EmailException e) { logger.error("Cannot send e-mail. " + e.getMessage()); logger.error("StackTrace:\n" + getStackTrace(e)); } } // Showing report System.out.println(summary); System.out.println(report); }
From source file:com.bluemarsh.jswat.console.Main.java
/** * Kicks off the application.//from w ww. ja v a2 s. c om * * @param args the command line arguments. */ public static void main(String[] args) { // // An attempt was made early on to use the Console class in java.io, // but that is not designed to handle asynchronous output from // multiple threads, so we just use the usual System.out for output // and System.in for input. Note that automatic flushing is used to // ensure output is shown in a timely fashion. // // // Where console mode seems to work: // - bash // - emacs // // Where console mode does not seem to work: // - NetBeans: output from event listeners is never shown and the // cursor sometimes lags behind the output // // Turn on flushing so printing the prompt will flush // all buffered output generated from other threads. PrintWriter output = new PrintWriter(System.out, true); // Make sure we have the JPDA classes. try { Bootstrap.virtualMachineManager(); } catch (NoClassDefFoundError ncdfe) { output.println(NbBundle.getMessage(Main.class, "MSG_Main_NoJPDA")); System.exit(1); } // Ensure we can create the user directory by requesting the // platform service. Simply asking for it has the desired effect. PlatformProvider.getPlatformService(); // Define the logging configuration. LogManager manager = LogManager.getLogManager(); InputStream is = Main.class.getResourceAsStream("logging.properties"); try { manager.readConfiguration(is); } catch (IOException ioe) { ioe.printStackTrace(); System.exit(1); } // Print out some useful debugging information. logSystemDetails(); // Add a shutdown hook to make sure we exit cleanly. Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { @Override public void run() { // Save the command aliases. CommandParser parser = CommandProvider.getCommandParser(); parser.saveSettings(); // Save the runtimes to persistent storage. RuntimeManager rm = RuntimeProvider.getRuntimeManager(); rm.saveRuntimes(); // Save the sessions to persistent storage and have them // close down in preparation to exit. SessionManager sm = SessionProvider.getSessionManager(); sm.saveSessions(true); } })); // Initialize the command parser and load the aliases. CommandParser parser = CommandProvider.getCommandParser(); parser.loadSettings(); parser.setOutput(output); // Create an OutputAdapter to display debuggee output. OutputAdapter adapter = new OutputAdapter(output); SessionManager sessionMgr = SessionProvider.getSessionManager(); sessionMgr.addSessionManagerListener(adapter); // Create a SessionWatcher to monitor the session status. SessionWatcher swatcher = new SessionWatcher(); sessionMgr.addSessionManagerListener(swatcher); // Create a BreakpointWatcher to monitor the breakpoints. BreakpointWatcher bwatcher = new BreakpointWatcher(); sessionMgr.addSessionManagerListener(bwatcher); // Add the watchers and adapters to the open sessions. Iterator<Session> iter = sessionMgr.iterateSessions(); while (iter.hasNext()) { Session s = iter.next(); s.addSessionListener(adapter); s.addSessionListener(swatcher); } // Find and run the RC file. try { runStartupFile(parser, output); } catch (IOException ioe) { logger.log(Level.SEVERE, null, ioe); } // Process command line arguments. try { processArguments(args); } catch (ParseException pe) { // Report the problem and keep going. System.err.println("Option parsing failed: " + pe.getMessage()); logger.log(Level.SEVERE, null, pe); } // Display a helpful greeting. output.println(NbBundle.getMessage(Main.class, "MSG_Main_Welcome")); if (jdbEmulationMode) { output.println(NbBundle.getMessage(Main.class, "MSG_Main_Jdb_Emulation")); } // Enter the main loop of processing user input. BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); while (true) { // Keep the prompt format identical to jdb for compatibility // with emacs and other possible wrappers. output.print("> "); output.flush(); try { String command = input.readLine(); // A null value indicates end of stream. if (command != null) { performCommand(output, parser, command); } // Sleep briefly to give the event processing threads, // and the automatic output flushing, a chance to catch // up before printing the input prompt again. Thread.sleep(250); } catch (InterruptedException ie) { logger.log(Level.WARNING, null, ie); } catch (IOException ioe) { logger.log(Level.SEVERE, null, ioe); output.println(NbBundle.getMessage(Main.class, "ERR_Main_IOError", ioe)); } catch (Exception x) { // Don't ever let an internal bug (e.g. in the command parser) // hork the console, as it really irritates people. logger.log(Level.SEVERE, null, x); output.println(NbBundle.getMessage(Main.class, "ERR_Main_Exception", x)); } } }
From source file:org.openiot.gsn.utils.GSNMonitor.java
public static void main(String[] args) { PropertyConfigurator.configure(DEFAULT_GSN_LOG4J_PROPERTIES); String configFileName;//from ww w . j a va 2 s .c o m if (args.length >= 2) { configFileName = args[0]; System.out.println("Using config file: " + configFileName); for (int i = 1; i < args.length; i++) { System.out.println("Adding e-mail: " + args[i]); listOfMails.add(args[i]); } } else { System.out.println("Usage java -jar VSMonitor.jar <config_file> <list_of_mails>"); System.out.println("e.g. java -jar VSMonitor.jar conf/monitoring.cfg user@gmail.com admin@gmail.com"); return; } initFromFile(configFileName); // for each monitored GSN server Iterator iter = listOfGSNSessions.iterator(); while (iter.hasNext()) { try { readStatus((GSNSessionAddress) iter.next()); } catch (Exception e) { logger.error("Exception: " + e.getMessage()); logger.error("StackTrace:\n" + getStackTrace(e)); } } checkUpdateTimes(); // Generate Report report.append("\n[ERROR]\n" + errorsBuffer).append("\n[WARNING]\n" + warningsBuffer) .append("\n[INFO]\n" + infosBuffer); if ((nSensorsLate > 0) || (nHostsDown > 0)) { summary.append("WARNING: "); if (nHostsDown > 0) summary.append(nHostsDown + " host(s) down. "); if (nSensorsLate > 0) summary.append(nSensorsLate + " sensor(s) not updated. "); // Send e-mail only if there are errors try { sendMail(); } catch (EmailException e) { logger.error("Cannot send e-mail. " + e.getMessage()); logger.error("StackTrace:\n" + getStackTrace(e)); } } // Showing report System.out.println(summary); System.out.println(report); System.exit(status); }