List of usage examples for java.util Iterator hasNext
boolean hasNext();
From source file:tsp.TSPTestSpring.java
public static void main(String[] args) throws IOException { ApplicationContext context = new ClassPathXmlApplicationContext("ApplicationContext.xml"); ITSPAlgorithm tspBruteForce = (ITSPAlgorithm) context.getBean("tspBruteForce"); ITSPAlgorithm tspNearestNeighbor = (ITSPAlgorithm) context.getBean("tspNearestNeighbor"); ITSPAlgorithm tspRandomSelection = (ITSPAlgorithm) context.getBean("tspRandomSelection"); ITSPAlgorithm tspGeneticAlgorithm = (ITSPAlgorithm) context.getBean("tspGeneticAlgorithm"); // test// w w w. j ava 2 s . c o m ITSPAlgorithm tspGeneticAlgorithm2 = (ITSPAlgorithm) context.getBean("tspGeneticAlgorithm"); if (tspGeneticAlgorithm == tspGeneticAlgorithm2) System.out.println("[TEST] The Same instance!!!"); List<TSPPath> bestPathList; Iterator it; tspBruteForce.getGraph().printGraph(); // Brute Force // if (g.getNumVertex()>100) return; System.out.printf("The Best Routes Found By Brute Force:\n"); bestPathList = tspBruteForce.getBestPathList(3); it = bestPathList.iterator(); while (it.hasNext()) { TSPPath path = ((TSPPath) it.next()); path.printPathStartingFrom(0); } System.out.println(""); // Select the best XXX routes from a randomly generated sample pool System.out.printf("The Best Routes Found (Approximation By Random Selection and Ranking):\n"); // System.out.printf("Sample Size: %d\n", tspRandomSelection.getSampleSize()); bestPathList = tspRandomSelection.getBestPathList(3); it = bestPathList.iterator(); while (it.hasNext()) { TSPPath path = ((TSPPath) it.next()); path.printPathStartingFrom(0); } System.out.println(""); // Select the best XXX routes by Nearest Neighbor System.out.printf("The Best Routes Found (Approximation By Nearest Neighbor):\n"); bestPathList = tspNearestNeighbor.getBestPathList(3); it = bestPathList.iterator(); while (it.hasNext()) { TSPPath path = ((TSPPath) it.next()); path.printPathStartingFrom(0); } System.out.println(""); // Select the best XXX routes by Genetic Algorithm System.out.printf("The Best Routes Found (Approximation By Genetic Algorithm):\n"); // System.out.printf("Population Size: %d\n", tspGeneticAlgorithm.getPopSize()); bestPathList = tspGeneticAlgorithm.getBestPathList(3); it = bestPathList.iterator(); while (it.hasNext()) { TSPPath path = ((TSPPath) it.next()); path.printPathStartingFrom(0); } System.out.println(""); }
From source file:enrichment.Disambiguate.java
/**prerequisites: * cd silk_2.5.3/*_links// www. j a v a 2s. com * cat *.nt|sort -t' ' -k3 > $filename * * @param args $filename * @throws IOException * @throws URISyntaxException */ public static void main(String[] args) { File file = new File(args[0]); if (file.isDirectory()) { args = file.list(new OnlyExtFilenameFilter("nt")); } BufferedReader in; for (int q = 0; q < args.length; q++) { String filename = null; if (file.isDirectory()) { filename = file.getPath() + File.separator + args[q]; } else { filename = args[q]; } try { FileWriter output = new FileWriter(filename + "_disambiguated.nt"); String prefix = "@prefix rdrel: <http://rdvocab.info/RDARelationshipsWEMI/> .\n" + "@prefix dbpedia: <http://de.dbpedia.org/resource/> .\n" + "@prefix frbr: <http://purl.org/vocab/frbr/core#> .\n" + "@prefix lobid: <http://lobid.org/resource/> .\n" + "@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .\n" + "@prefix foaf: <http://xmlns.com/foaf/0.1/> .\n" + "@prefix mo: <http://purl.org/ontology/mo/> .\n" + "@prefix wikipedia: <https://de.wikipedia.org/wiki/> ."; output.append(prefix + "\n\n"); in = new BufferedReader(new InputStreamReader(new FileInputStream(filename))); HashMap<String, HashMap<String, ArrayList<String>>> hm = new HashMap<String, HashMap<String, ArrayList<String>>>(); String s; HashMap<String, ArrayList<String>> hmLobid = new HashMap<String, ArrayList<String>>(); Stack<String> old_object = new Stack<String>(); while ((s = in.readLine()) != null) { String[] triples = s.split(" "); String object = triples[2].substring(1, triples[2].length() - 1); if (old_object.size() > 0 && !old_object.firstElement().equals(object)) { hmLobid = new HashMap<String, ArrayList<String>>(); old_object = new Stack<String>(); } old_object.push(object); String subject = triples[0].substring(1, triples[0].length() - 1); System.out.print("\nSubject=" + object); System.out.print("\ntriples[2]=" + triples[2]); hmLobid.put(subject, getAllCreators(new URI(subject))); hm.put(object, hmLobid); } // get all dbpedia resources for (String key_one : hm.keySet()) { System.out.print("\n==============\n==== " + key_one + "\n==============="); int resources_cnt = hm.get(key_one).keySet().size(); ArrayList<String>[] creators = new ArrayList[resources_cnt]; HashMap<String, Integer> creators_backed = new HashMap<String, Integer>(); int x = 0; // get all lobid_resources subsumed under the dbpedia resource for (String subject_uri : hm.get(key_one).keySet()) { creators[x] = new ArrayList<String>(); System.out.print("\n subject_uri=" + subject_uri); Iterator<String> ite = hm.get(key_one).get(subject_uri).iterator(); int y = 0; // get all creators of the lobid resource while (ite.hasNext()) { String creator = ite.next(); System.out.print("\n " + creator); if (creators_backed.containsKey(creator)) { y = creators_backed.get(creator); } else { y = creators_backed.size(); creators_backed.put(creator, y); } while (creators[x].size() <= y) { creators[x].add("-"); } creators[x].set(y, creator); y++; } x++; } if (creators_backed.size() == 1) { System.out .println("\n" + "Every resource pointing to " + key_one + " has the same creator!"); for (String key_two : hm.get(key_one).keySet()) { output.append("<" + key_two + "> rdrel:workManifested <" + key_one + "> .\n"); output.append("<" + key_two + "> mo:wikipedia <" + key_one.replaceAll("dbpedia\\.org/resource", "wikipedia\\.org/wiki") + "> .\n"); } } /*else { for (int a = 0; a < creators.length; a++) { System.out.print(creators[a].toString()+","); } }*/ } output.flush(); if (output != null) { output.close(); } } catch (Exception e) { System.out.print("Exception while working on " + filename + ": \n"); e.printStackTrace(System.out); } } }
From source file:ConsumerTool.java
public static void main(String[] args) { ArrayList<ConsumerTool> threads = new ArrayList(); ConsumerTool consumerTool = new ConsumerTool(); String[] unknown = CommandLineSupport.setOptions(consumerTool, args); if (unknown.length > 0) { System.out.println("Unknown options: " + Arrays.toString(unknown)); System.exit(-1);//from w ww . j av a 2 s . c o m } consumerTool.showParameters(); for (int threadCount = 1; threadCount <= parallelThreads; threadCount++) { consumerTool = new ConsumerTool(); CommandLineSupport.setOptions(consumerTool, args); consumerTool.start(); threads.add(consumerTool); } while (true) { Iterator<ConsumerTool> itr = threads.iterator(); int running = 0; while (itr.hasNext()) { ConsumerTool thread = itr.next(); if (thread.isAlive()) { running++; } } if (running <= 0) { System.out.println("All threads completed their work"); break; } try { Thread.sleep(1000); } catch (Exception e) { } } Iterator<ConsumerTool> itr = threads.iterator(); while (itr.hasNext()) { ConsumerTool thread = itr.next(); } }
From source file:edu.jhu.hlt.concrete.ingesters.gigaword.GigawordGzProcessor.java
public static void main(String... args) { Thread.setDefaultUncaughtExceptionHandler(new LoggedUncaughtExceptionHandler()); if (args.length != 2) { LOGGER.info("This program takes 2 arguments."); LOGGER.info("First: the path to a .gz file that is part of the English Gigaword v5 corpus."); LOGGER.info("Second: the path to the output file (a .tar.gz with communication files)."); LOGGER.info("Example usage:"); LOGGER.info("{} {} {}", GigawordGzProcessor.class.getName(), "/path/to/LDC/sgml/.gz", "/path/to/out.tar.gz"); System.exit(1);//from w ww. j a va2 s .c om } String inPathStr = args[0]; String outPathStr = args[1]; Path inPath = Paths.get(inPathStr); if (!Files.exists(inPath)) LOGGER.error("Input path {} does not exist. Try again with the right path.", inPath.toString()); Path outPath = Paths.get(outPathStr); Optional<Path> parent = Optional.ofNullable(outPath.getParent()); // lambda does not allow caught exceptions. if (parent.isPresent()) { if (!Files.exists(outPath.getParent())) { LOGGER.info("Attempting to create output directory: {}", outPath.toString()); try { Files.createDirectories(outPath); } catch (IOException e) { LOGGER.error("Caught exception creating output directory.", e); } } } GigawordDocumentConverter conv = new GigawordDocumentConverter(); Iterator<Communication> iter = conv.gzToStringIterator(inPath); try (OutputStream os = Files.newOutputStream(outPath); BufferedOutputStream bos = new BufferedOutputStream(os, 1024 * 8 * 16); GzipCompressorOutputStream gout = new GzipCompressorOutputStream(bos); TarArchiver archiver = new TarArchiver(gout);) { while (iter.hasNext()) { Communication c = iter.next(); LOGGER.info("Adding Communication {} [UUID: {}] to archive.", c.getId(), c.getUuid().getUuidString()); archiver.addEntry(new ArchivableCommunication(c)); } } catch (IOException e) { LOGGER.error("Caught IOException during output.", e); } }
From source file:com.thesmartweb.vivliocrawlermaven.VivlioCrawlerMavenMain.java
/** * @param args the command line arguments *///from w w w .j a v a2 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: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/* w ww . j a v a 2 s . c o m*/ 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: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);// w w w . jav a 2s . com 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.aliteralmind.codelet.examples.non_xbn.PrintJDBlocksStartStopLineNumsXmpl.java
/** <p>The main function.</p> *//*from w w w. j av a 2s . co m*/ 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: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// w w w . ja v a2s.c om 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:org.openiot.gsn.utils.VSMonitor.java
public static void main(String[] args) { PropertyConfigurator.configure(DEFAULT_GSN_LOG4J_PROPERTIES); String configFileName;//w w w. j ava 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); }