You can subscribe to this list here.
2003 |
Jan
|
Feb
|
Mar
|
Apr
|
May
|
Jun
|
Jul
|
Aug
|
Sep
(11) |
Oct
(60) |
Nov
(68) |
Dec
(10) |
---|---|---|---|---|---|---|---|---|---|---|---|---|
2004 |
Jan
(10) |
Feb
(15) |
Mar
(30) |
Apr
(20) |
May
(32) |
Jun
(30) |
Jul
(61) |
Aug
(13) |
Sep
(14) |
Oct
(13) |
Nov
(28) |
Dec
(10) |
2005 |
Jan
(7) |
Feb
(5) |
Mar
|
Apr
(2) |
May
|
Jun
|
Jul
|
Aug
|
Sep
(4) |
Oct
|
Nov
|
Dec
|
2006 |
Jan
|
Feb
|
Mar
|
Apr
|
May
|
Jun
|
Jul
|
Aug
|
Sep
|
Oct
|
Nov
|
Dec
(15) |
2007 |
Jan
|
Feb
|
Mar
|
Apr
|
May
|
Jun
|
Jul
(20) |
Aug
(35) |
Sep
(3) |
Oct
(2) |
Nov
|
Dec
|
2008 |
Jan
|
Feb
|
Mar
|
Apr
|
May
|
Jun
|
Jul
|
Aug
(14) |
Sep
(2) |
Oct
|
Nov
|
Dec
|
2010 |
Jan
|
Feb
|
Mar
|
Apr
|
May
|
Jun
|
Jul
|
Aug
|
Sep
|
Oct
|
Nov
|
Dec
(3) |
2011 |
Jan
|
Feb
|
Mar
|
Apr
(5) |
May
|
Jun
|
Jul
|
Aug
|
Sep
|
Oct
|
Nov
|
Dec
|
From: Sasa M. <sa...@us...> - 2004-03-22 09:30:28
|
Update of /cvsroot/jrobin/src In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv27847 Modified Files: Demo.java Log Message: final tweaks Index: Demo.java =================================================================== RCS file: /cvsroot/jrobin/src/Demo.java,v retrieving revision 1.11 retrieving revision 1.12 diff -C2 -d -r1.11 -r1.12 *** Demo.java 26 Feb 2004 12:14:06 -0000 1.11 --- Demo.java 22 Mar 2004 09:20:12 -0000 1.12 *************** *** 81,86 **** log.println(rrdDef.dump()); RrdDb rrdDb = new RrdDb(rrdDef); rrdDb.close(); ! println("== RRD file created and closed."); // update database --- 81,87 ---- log.println(rrdDef.dump()); RrdDb rrdDb = new RrdDb(rrdDef); + println("== RRD file created."); rrdDb.close(); ! println("== RRD file closed."); // update database *************** *** 104,108 **** }; } ! System.out.println(""); println("== Finished. RRD file updated " + n + " times"); println("== Last update time was: " + rrdDb.getLastUpdateTime()); --- 105,109 ---- }; } ! println(""); println("== Finished. RRD file updated " + n + " times"); println("== Last update time was: " + rrdDb.getLastUpdateTime()); *************** *** 131,135 **** --- 132,138 ---- println("== Closing both RRD files"); rrdDb.close(); + println("== First file closed"); rrdRestoredDb.close(); + println("== Second file closed"); // create graph *************** *** 158,167 **** RrdGraph graph = new RrdGraph(gDef); println("== Graph created"); - println("== Saving graph as PNG file " + pngPath); graph.saveAsPNG(pngPath, 400, 250); ! println("== Saving graph as JPEG file " + jpegPath); graph.saveAsJPEG(jpegPath, 400, 250, 0.5F); ! println("== Saving graph as GIF file " + gifPath); graph.saveAsGIF(gifPath, 400, 250); // demo ends --- 161,170 ---- RrdGraph graph = new RrdGraph(gDef); println("== Graph created"); graph.saveAsPNG(pngPath, 400, 250); ! println("== Graph saved as a PNG file " + pngPath); graph.saveAsJPEG(jpegPath, 400, 250, 0.5F); ! println("== Graph saved as a JPEG file " + jpegPath); graph.saveAsGIF(gifPath, 400, 250); + println("== Graph saved as a GIF file " + gifPath); // demo ends *************** *** 172,176 **** static void println(String msg) { ! System.out.println(msg); } --- 175,183 ---- static void println(String msg) { ! System.out.println(msg + " " + Util.getLapTime()); ! } ! ! static void print(String msg) { ! System.out.print(msg); } |
From: <sa...@us...> - 2004-03-15 10:49:56
|
Update of /cvsroot/jrobin/src/org/jrobin/core In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv3745/org/jrobin/core Modified Files: FetchRequest.java XmlTemplate.java Log Message: bug fixes Index: FetchRequest.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/core/FetchRequest.java,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** FetchRequest.java 10 Nov 2003 08:52:27 -0000 1.3 --- FetchRequest.java 15 Mar 2004 10:40:50 -0000 1.4 *************** *** 134,140 **** throw new RrdException("Invalid end time in fetch request: " + fetchEnd); } ! if(fetchStart >= fetchEnd) { throw new RrdException("Invalid start/end time in fetch request: " + fetchStart + ! "/" + fetchEnd); } if(resolution <= 0) { --- 134,140 ---- throw new RrdException("Invalid end time in fetch request: " + fetchEnd); } ! if(fetchStart > fetchEnd) { throw new RrdException("Invalid start/end time in fetch request: " + fetchStart + ! " > " + fetchEnd); } if(resolution <= 0) { Index: XmlTemplate.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/core/XmlTemplate.java,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** XmlTemplate.java 8 Mar 2004 13:14:39 -0000 1.5 --- XmlTemplate.java 15 Mar 2004 10:40:50 -0000 1.6 *************** *** 189,199 **** private String resolveMappings(String templateValue) { Matcher matcher = PATTERN.matcher(templateValue); StringBuffer result = new StringBuffer(); while(matcher.find()) { String var = matcher.group(1); if(valueMap.containsKey(var)) { // mapping found ! matcher.appendReplacement(result, valueMap.get(var).toString()); } else { --- 189,205 ---- private String resolveMappings(String templateValue) { + if(templateValue == null) { + return null; + } Matcher matcher = PATTERN.matcher(templateValue); StringBuffer result = new StringBuffer(); + int lastMatchEnd = 0; while(matcher.find()) { String var = matcher.group(1); if(valueMap.containsKey(var)) { // mapping found ! result.append(templateValue.substring(lastMatchEnd, matcher.start())); ! result.append(valueMap.get(var).toString()); ! lastMatchEnd = matcher.end(); } else { *************** *** 204,208 **** } } ! matcher.appendTail(result); return result.toString(); } --- 210,214 ---- } } ! result.append(templateValue.substring(lastMatchEnd)); return result.toString(); } |
From: <sa...@us...> - 2004-03-11 14:21:10
|
Update of /cvsroot/jrobin/src/org/jrobin/mrtg/server In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv27547/org/jrobin/mrtg/server Modified Files: Plotter.java Server.java Timer.java Log Message: RrdDbPool final tweaks Index: Plotter.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/mrtg/server/Plotter.java,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** Plotter.java 8 Mar 2004 13:14:39 -0000 1.2 --- Plotter.java 11 Mar 2004 13:54:26 -0000 1.3 *************** *** 91,96 **** } } ! RrdGraph graph = new RrdGraph(true); // use pool ! graph.setGraphDef(rrdGraphDef); return graph; } --- 91,95 ---- } } ! RrdGraph graph = new RrdGraph(rrdGraphDef, true); // use pool return graph; } Index: Server.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/mrtg/server/Server.java,v retrieving revision 1.8 retrieving revision 1.9 diff -C2 -d -r1.8 -r1.9 *** Server.java 8 Mar 2004 13:14:39 -0000 1.8 --- Server.java 11 Mar 2004 13:54:26 -0000 1.9 *************** *** 26,29 **** --- 26,30 ---- import org.jrobin.core.RrdDb; + import org.jrobin.core.RrdDbPool; import org.jrobin.mrtg.MrtgException; import org.jrobin.mrtg.MrtgConstants; *************** *** 68,72 **** private Server() { RrdDb.setLockMode(RrdDb.NO_LOCKS); ! //RrdDbPool.getInstance().setCapacity(500); } --- 69,73 ---- private Server() { RrdDb.setLockMode(RrdDb.NO_LOCKS); ! RrdDbPool.getInstance().setCapacity(POOL_CAPACITY); } Index: Timer.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/mrtg/server/Timer.java,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** Timer.java 9 Dec 2003 12:22:04 -0000 1.1 --- Timer.java 11 Mar 2004 13:54:26 -0000 1.2 *************** *** 51,54 **** --- 51,59 ---- link.isDue() && !link.isSampling()) { new SnmpReader(router, link).start(); + try { + sleep(SCHEDULER_DELAY); + } catch (InterruptedException e) { + e.printStackTrace(); + } } } |
From: <sa...@us...> - 2004-03-11 14:21:10
|
Update of /cvsroot/jrobin/src/org/jrobin/graph In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv27547/org/jrobin/graph Modified Files: RrdGraph.java Log Message: RrdDbPool final tweaks Index: RrdGraph.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/graph/RrdGraph.java,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** RrdGraph.java 1 Mar 2004 12:02:46 -0000 1.4 --- RrdGraph.java 11 Mar 2004 13:54:25 -0000 1.5 *************** *** 26,30 **** import javax.swing.JPanel; - import java.util.ArrayList; import java.util.Iterator; import java.io.File; --- 26,29 ---- *************** *** 56,68 **** // -- Members // ================================================================ ! private static int DEFAULT_POOLSIZE = 15; ! private Grapher grapher; private BufferedImage img; ! private ArrayList rrdDbPool; ! private RrdDbPool pool; - private int maxPoolSize = DEFAULT_POOLSIZE; private boolean useImageSize = false; --- 55,64 ---- // -- Members // ================================================================ ! private Grapher grapher; private BufferedImage img; ! private RrdDbPool pool; private boolean useImageSize = false; *************** *** 91,98 **** * Constructs a new JRobin graph object from the supplied definition. * @param graphDef Graph definition. - * @throws IOException Thrown in case of I/O error. - * @throws RrdException Thrown in case of JRobin specific error. */ ! public RrdGraph( RrdGraphDef graphDef ) throws IOException, RrdException { this( graphDef, false ); --- 87,92 ---- * Constructs a new JRobin graph object from the supplied definition. * @param graphDef Graph definition. */ ! public RrdGraph( RrdGraphDef graphDef ) { this( graphDef, false ); *************** *** 103,110 **** * @param graphDef Graph definition. * @param usePool True if this should object should use RrdDbPool - * @throws IOException Thrown in case of I/O error. - * @throws RrdException Thrown in case of JRobin specific error. */ ! public RrdGraph( RrdGraphDef graphDef, boolean usePool ) throws IOException, RrdException { if ( usePool ) --- 97,102 ---- * @param graphDef Graph definition. * @param usePool True if this should object should use RrdDbPool */ ! public RrdGraph( RrdGraphDef graphDef, boolean usePool ) { if ( usePool ) *************** *** 162,166 **** public void saveAsPNG( String path, int width, int height ) throws RrdException, IOException { ! ImageIO.write( (RenderedImage) getBufferedImage(width, height, BufferedImage.TYPE_INT_RGB), "png", new File(path) ); } --- 154,159 ---- public void saveAsPNG( String path, int width, int height ) throws RrdException, IOException { ! ImageIO.write(getBufferedImage(width, height, BufferedImage.TYPE_INT_RGB), ! "png", new File(path) ); } *************** *** 224,229 **** // Based on http://javaalmanac.com/egs/javax.imageio/JpegWrite.html?l=rel // Retrieve jpg image to be compressed ! BufferedImage gImage = getBufferedImage(width, height, BufferedImage.TYPE_INT_RGB); ! RenderedImage rndImage = (RenderedImage) gImage; // Find a jpeg writer --- 217,221 ---- // Based on http://javaalmanac.com/egs/javax.imageio/JpegWrite.html?l=rel // Retrieve jpg image to be compressed ! RenderedImage rndImage = getBufferedImage(width, height, BufferedImage.TYPE_INT_RGB); // Find a jpeg writer *************** *** 273,277 **** ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ! ImageIO.write( (RenderedImage) getBufferedImage(width, height, BufferedImage.TYPE_INT_RGB), "png", outputStream ); return outputStream.toByteArray(); --- 265,270 ---- ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ! ImageIO.write(getBufferedImage(width, height, BufferedImage.TYPE_INT_RGB), ! "png", outputStream ); return outputStream.toByteArray(); *************** *** 302,307 **** // Retrieve jpg image to be compressed ! BufferedImage gImage = getBufferedImage(width, height, BufferedImage.TYPE_INT_RGB); ! RenderedImage rndImage = (RenderedImage) gImage; // Find a jpeg writer --- 295,299 ---- // Retrieve jpg image to be compressed ! RenderedImage rndImage = getBufferedImage(width, height, BufferedImage.TYPE_INT_RGB); // Find a jpeg writer |
From: <sa...@us...> - 2004-03-11 14:21:09
|
Update of /cvsroot/jrobin/src/org/jrobin/mrtg In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv27547/org/jrobin/mrtg Modified Files: MrtgConstants.java Log Message: RrdDbPool final tweaks Index: MrtgConstants.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/mrtg/MrtgConstants.java,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** MrtgConstants.java 8 Mar 2004 13:14:39 -0000 1.4 --- MrtgConstants.java 11 Mar 2004 13:54:26 -0000 1.5 *************** *** 33,43 **** int SERVER_PORT = 35353; ! // run Scheduler each 3 seconds ! int SCHEDULER_RESOLUTION = 3; // graph dimensions int GRAPH_WIDTH = 502, GRAPH_HEIGHT = 234; ! // initial temeplate for RrdDef String RRD_TEMPLATE_STR = "<rrd_def> \n" + --- 33,49 ---- int SERVER_PORT = 35353; ! // run Scheduler each 5 seconds ! int SCHEDULER_RESOLUTION = 5; ! ! // pause between poller threads in milliseconds ! int SCHEDULER_DELAY = 20; ! ! // number of open RRD files held in the pool ! int POOL_CAPACITY = 50; // graph dimensions int GRAPH_WIDTH = 502, GRAPH_HEIGHT = 234; ! // initial template for RrdDef String RRD_TEMPLATE_STR = "<rrd_def> \n" + |
From: <sa...@us...> - 2004-03-11 14:21:08
|
Update of /cvsroot/jrobin/src/org/jrobin/core In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv27547/org/jrobin/core Modified Files: RrdDb.java RrdDbPool.java Log Message: RrdDbPool final tweaks Index: RrdDb.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/core/RrdDb.java,v retrieving revision 1.12 retrieving revision 1.13 diff -C2 -d -r1.12 -r1.13 *** RrdDb.java 2 Mar 2004 09:47:49 -0000 1.12 --- RrdDb.java 11 Mar 2004 13:54:25 -0000 1.13 *************** *** 69,72 **** --- 69,73 ---- static final int XML_INITIAL_BUFFER_CAPACITY = 100000; // bytes + private String canonicalPath; private RrdFile file; private Header header; *************** *** 224,227 **** --- 225,229 ---- } file.setMode(RrdFile.MODE_NORMAL); + canonicalPath = file.getCanonicalFilePath(); } *************** *** 762,764 **** } } ! } --- 764,774 ---- } } ! ! /** ! * Returns canonical path to the underlying RRD file. ! * @return Canonical path to RRD file; ! */ ! public String getCanonicalPath() { ! return canonicalPath; ! } ! } Index: RrdDbPool.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/core/RrdDbPool.java,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** RrdDbPool.java 2 Mar 2004 09:47:49 -0000 1.5 --- RrdDbPool.java 11 Mar 2004 13:54:25 -0000 1.6 *************** *** 101,121 **** private static final boolean DEBUG = false; - private static final Comparator ENTRY_COMPARATOR = new Comparator() { - public int compare(Object o1, Object o2) { - RrdEntry r1 = (RrdEntry) o1, r2 = (RrdEntry) o2; - if (!r1.isReleased() && !r2.isReleased()) { - return 0; - } else if (r1.isReleased() && !r2.isReleased()) { - return -1; - } else if (!r1.isReleased() && r2.isReleased()) { - return +1; - } else { - // both released - long diff = r1.getReleaseDate().getTime() - - r2.getReleaseDate().getTime(); - return diff < 0L ? -1 : (diff == 0L ? 0 : +1); - } - } - }; /** * Constant to represent the maximum number of internally open RRD files --- 101,104 ---- *************** *** 123,129 **** */ public static final int INITIAL_CAPACITY = 50; ! private volatile int capacity = INITIAL_CAPACITY; ! private HashMap rrdMap = new HashMap(); /** --- 106,113 ---- */ public static final int INITIAL_CAPACITY = 50; ! private int capacity = INITIAL_CAPACITY; ! private Map rrdMap = new HashMap(); ! private List rrdGcList = new LinkedList(); /** *************** *** 163,167 **** // already open RrdEntry rrdEntry = (RrdEntry) rrdMap.get(keypath); ! rrdEntry.reportUsage(); debug("EXISTING: " + rrdEntry.dump()); return rrdEntry.getRrdDb(); --- 147,151 ---- // already open RrdEntry rrdEntry = (RrdEntry) rrdMap.get(keypath); ! reportUsage(rrdEntry); debug("EXISTING: " + rrdEntry.dump()); return rrdEntry.getRrdDb(); *************** *** 169,173 **** // not found, open it RrdDb rrdDb = new RrdDb(path); ! put(keypath, rrdDb); return rrdDb; } --- 153,157 ---- // not found, open it RrdDb rrdDb = new RrdDb(path); ! addRrdEntry(keypath, rrdDb); return rrdDb; } *************** *** 187,193 **** throws IOException, RrdException { String keypath = getCanonicalPath(path); ! validateInactive(keypath); RrdDb rrdDb = new RrdDb(path, xmlPath); ! put(keypath, rrdDb); return rrdDb; } --- 171,177 ---- throws IOException, RrdException { String keypath = getCanonicalPath(path); ! prooveInactive(keypath); RrdDb rrdDb = new RrdDb(path, xmlPath); ! addRrdEntry(keypath, rrdDb); return rrdDb; } *************** *** 204,215 **** String path = rrdDef.getPath(); String keypath = getCanonicalPath(path); ! validateInactive(keypath); RrdDb rrdDb = new RrdDb(rrdDef); ! put(keypath, rrdDb); return rrdDb; } ! private synchronized void put(String keypath, RrdDb rrdDb) throws IOException { RrdEntry newEntry = new RrdEntry(rrdDb); debug("NEW: " + newEntry.dump()); rrdMap.put(keypath, newEntry); --- 188,214 ---- String path = rrdDef.getPath(); String keypath = getCanonicalPath(path); ! prooveInactive(keypath); RrdDb rrdDb = new RrdDb(rrdDef); ! addRrdEntry(keypath, rrdDb); return rrdDb; } ! private void reportUsage(RrdEntry rrdEntry) { ! if(rrdEntry.reportUsage() == 1) { ! // must not be garbage collected ! rrdGcList.remove(rrdEntry); ! } ! } ! ! private void reportRelease(RrdEntry rrdEntry) { ! if(rrdEntry.reportRelease() == 0) { ! // ready to be garbage collected ! rrdGcList.add(rrdEntry); ! } ! } ! ! private void addRrdEntry(String keypath, RrdDb rrdDb) throws IOException { RrdEntry newEntry = new RrdEntry(rrdDb); + reportUsage(newEntry); debug("NEW: " + newEntry.dump()); rrdMap.put(keypath, newEntry); *************** *** 218,226 **** } ! private void validateInactive(String keypath) throws RrdException, IOException { if(rrdMap.containsKey(keypath)) { // already open, check if active (not released) RrdEntry rrdEntry = (RrdEntry) rrdMap.get(keypath); ! if(!rrdEntry.isReleased()) { // not released, not allowed here throw new RrdException("VALIDATOR: Cannot create new RrdDb file. " + --- 217,225 ---- } ! private void prooveInactive(String keypath) throws RrdException, IOException { if(rrdMap.containsKey(keypath)) { // already open, check if active (not released) RrdEntry rrdEntry = (RrdEntry) rrdMap.get(keypath); ! if(rrdEntry.isInUse()) { // not released, not allowed here throw new RrdException("VALIDATOR: Cannot create new RrdDb file. " + *************** *** 230,239 **** // open but released... safe to close it debug("WILL BE RECREATED: " + rrdEntry.dump()); ! rrdEntry.close(); ! rrdMap.values().remove(rrdEntry); } } } /** * Method used to report that the reference to a RRD file is no longer needed. File that --- 229,244 ---- // open but released... safe to close it debug("WILL BE RECREATED: " + rrdEntry.dump()); ! removeRrdEntry(rrdEntry); } } } + private void removeRrdEntry(RrdEntry rrdEntry) throws IOException { + rrdEntry.closeRrdDb(); + rrdMap.values().remove(rrdEntry); + rrdGcList.remove(rrdEntry); + debug("REMOVED: " + rrdEntry.dump()); + } + /** * Method used to report that the reference to a RRD file is no longer needed. File that *************** *** 258,262 **** if(rrdMap.containsKey(keypath)) { RrdEntry rrdEntry = (RrdEntry) rrdMap.get(keypath); ! rrdEntry.release(); debug("RELEASED: " + rrdEntry.dump()); } --- 263,267 ---- if(rrdMap.containsKey(keypath)) { RrdEntry rrdEntry = (RrdEntry) rrdMap.get(keypath); ! reportRelease(rrdEntry); debug("RELEASED: " + rrdEntry.dump()); } *************** *** 278,307 **** debug("GC: started"); synchronized (this) { ! for (;;) { ! while (rrdMap.size() > capacity) { ! debug("GC: should run: (" + rrdMap.size() + " > " + capacity + ")"); ! RrdEntry oldestEntry = (RrdEntry) ! Collections.min(rrdMap.values(), ENTRY_COMPARATOR); ! if (oldestEntry.isReleased()) { ! try { ! debug("GC: closing " + oldestEntry.dump()); ! oldestEntry.close(); ! } catch (IOException e) { ! debug("GC error: " + e); ! e.printStackTrace(); ! } ! rrdMap.values().remove(oldestEntry); ! } else { ! // all references are used ! debug("GC: NOP: all references are active (" + rrdMap.size() + ")"); ! break; } } try { ! // nothing to do ! debug("GC: sleeping (" + rrdMap.size() + ")"); wait(); debug("GC: running"); ! } catch (InterruptedException e) { } } } --- 283,303 ---- debug("GC: started"); synchronized (this) { ! for (; ;) { ! while (rrdMap.size() > capacity && rrdGcList.size() > 0) { ! try { ! RrdEntry oldestRrdEntry = (RrdEntry) rrdGcList.get(0); ! debug("GC: closing " + oldestRrdEntry.dump()); ! removeRrdEntry(oldestRrdEntry); ! } catch (IOException e) { ! e.printStackTrace(); } } + try { ! debug("GC: sleeping (" + rrdMap.size() + "/" + rrdGcList.size() + ")"); wait(); debug("GC: running"); ! } catch (InterruptedException e) { ! } } } *************** *** 314,318 **** /** * Clears the internal state of the pool entirely. All open RRD files are closed. - * Use with extreme caution. * @throws IOException Thrown in case of I/O related error. */ --- 310,313 ---- *************** *** 321,335 **** while(it.hasNext()) { RrdEntry rrdEntry = (RrdEntry) it.next(); ! rrdEntry.close(); } rrdMap.clear(); debug("Nothing left in the pool"); } ! static String getCanonicalPath(String path) throws IOException { return new File(path).getCanonicalPath(); } ! static void debug(String msg) { if(DEBUG) { System.out.println("POOL: " + msg); --- 316,331 ---- while(it.hasNext()) { RrdEntry rrdEntry = (RrdEntry) it.next(); ! rrdEntry.closeRrdDb(); } rrdMap.clear(); + rrdGcList.clear(); debug("Nothing left in the pool"); } ! private static String getCanonicalPath(String path) throws IOException { return new File(path).getCanonicalPath(); } ! private static void debug(String msg) { if(DEBUG) { System.out.println("POOL: " + msg); *************** *** 360,364 **** * @return Desired nuber of open files held in the pool. */ ! public int getCapacity() { return capacity; } --- 356,360 ---- * @return Desired nuber of open files held in the pool. */ ! public synchronized int getCapacity() { return capacity; } *************** *** 370,374 **** * @param capacity Desired number of open files to hold in the pool */ ! public void setCapacity(int capacity) { this.capacity = capacity; } --- 366,370 ---- * @param capacity Desired number of open files to hold in the pool */ ! public synchronized void setCapacity(int capacity) { this.capacity = capacity; } *************** *** 376,385 **** private class RrdEntry { private RrdDb rrdDb; - private Date releaseDate; private int usageCount; public RrdEntry(RrdDb rrdDb) { this.rrdDb = rrdDb; - reportUsage(); } --- 372,379 ---- *************** *** 388,423 **** } ! void reportUsage() { ! releaseDate = null; ! usageCount++; ! } ! ! void release() { ! if(usageCount > 0) { ! usageCount--; ! if(usageCount == 0) { ! releaseDate = new Date(); ! } ! } ! } ! ! boolean isReleased() { ! return usageCount == 0; } ! int getUsageCount() { ! return usageCount; } ! Date getReleaseDate() { ! return releaseDate; } ! void close() throws IOException { rrdDb.close(); } String dump() throws IOException { ! String keypath = getCanonicalPath(rrdDb.getRrdFile().getFilePath()); return keypath + " [" + usageCount + "]"; } --- 382,405 ---- } ! int reportUsage() { ! assert usageCount >= 0: "Unexpected reportUsage count: " + usageCount; ! return ++usageCount; } ! int reportRelease() { ! assert usageCount > 0: "Unexpected reportRelease count: " + usageCount; ! return --usageCount; } ! boolean isInUse() { ! return usageCount > 0; } ! void closeRrdDb() throws IOException { rrdDb.close(); } String dump() throws IOException { ! String keypath = getCanonicalPath(rrdDb.getCanonicalPath()); return keypath + " [" + usageCount + "]"; } |
From: <sa...@us...> - 2004-03-08 13:38:59
|
Update of /cvsroot/jrobin/src/org/jrobin/mrtg/server In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv10511/org/jrobin/mrtg/server Modified Files: Config.java Plotter.java RrdWriter.java Server.java Log Message: XML templates improved Index: Config.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/mrtg/server/Config.java,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** Config.java 10 Nov 2003 08:52:29 -0000 1.2 --- Config.java 8 Mar 2004 13:14:39 -0000 1.3 *************** *** 25,33 **** package org.jrobin.mrtg.server; import java.io.File; ! class Config { private static final String DELIM = System.getProperty("file.separator"); - private static final String HOME_DIR = System.getProperty("user.home") + DELIM + "mrtg" + DELIM; --- 25,35 ---- package org.jrobin.mrtg.server; + import org.jrobin.mrtg.MrtgConstants; + import java.io.File; ! class Config implements MrtgConstants { ! // various paths private static final String DELIM = System.getProperty("file.separator"); private static final String HOME_DIR = System.getProperty("user.home") + DELIM + "mrtg" + DELIM; *************** *** 35,38 **** --- 37,42 ---- private static final String RRD_DIR = HOME_DIR + "rrd" + DELIM; private static final String HARDWARE_FILE = CONF_DIR + "mrtg.dat"; + private static final String RRD_DEF_TEMPLATE_FILE = CONF_DIR + "rrd_template.xml"; + private static final String RRD_GRAPH_DEF_TEMPLATE_FILE = CONF_DIR + "graph_template.xml"; static { *************** *** 57,59 **** --- 61,71 ---- return HARDWARE_FILE; } + + public static String getRrdTemplateFile() { + return RRD_DEF_TEMPLATE_FILE; + } + + public static String getGraphTemplateFile() { + return RRD_GRAPH_DEF_TEMPLATE_FILE; + } } Index: Plotter.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/mrtg/server/Plotter.java,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** Plotter.java 9 Dec 2003 12:22:04 -0000 1.1 --- Plotter.java 8 Mar 2004 13:14:39 -0000 1.2 *************** *** 27,36 **** import org.jrobin.core.RrdException; import org.jrobin.graph.RrdGraph; import org.jrobin.graph.RrdGraphDef; import org.jrobin.mrtg.MrtgConstants; import org.jrobin.mrtg.MrtgException; - import java.awt.*; import java.io.IOException; import java.util.Date; --- 27,37 ---- import org.jrobin.core.RrdException; import org.jrobin.graph.RrdGraph; + import org.jrobin.graph.RrdGraphDefTemplate; import org.jrobin.graph.RrdGraphDef; import org.jrobin.mrtg.MrtgConstants; import org.jrobin.mrtg.MrtgException; import java.io.IOException; + import java.io.File; import java.util.Date; *************** *** 38,43 **** --- 39,59 ---- private String ifDescr, host, alias; + private static RrdGraphDefTemplate rrdGraphDefTemplate = null; + + static { + try { + rrdGraphDefTemplate = + new RrdGraphDefTemplate(new File(Config.getGraphTemplateFile())); + } catch (IOException e) { + e.printStackTrace(); + } catch (RrdException e) { + e.printStackTrace(); + } + } Plotter(String host, String ifDescr) throws MrtgException { + if(rrdGraphDefTemplate == null) { + throw new MrtgException("Could not load graph XML template"); + } this.host = host; this.ifDescr = ifDescr; *************** *** 57,90 **** } ! RrdGraph getRrdGraph(long start, long stop) throws MrtgException { ! String filename = RrdWriter.getRrdFilename(host, ifDescr); ! RrdGraph graph = new RrdGraph(true); ! RrdGraphDef graphDef = new RrdGraphDef(); ! try { ! graphDef.setImageBorder(Color.WHITE, 0); // Don't show border ! graphDef.setTimePeriod(start, stop); ! graphDef.setTitle(ifDescr + "@" + host); ! graphDef.setVerticalLabel("transfer speed [bits/sec]"); ! graphDef.datasource("in", filename, "in", "AVERAGE"); ! graphDef.datasource("out", filename, "out", "AVERAGE"); ! graphDef.datasource("in8", "in,8,*"); ! graphDef.datasource("out8", "out,8,*"); ! graphDef.area("out8", Color.GREEN, "output traffic\n"); ! graphDef.line("in8", Color.BLUE, "input traffic"); ! graphDef.comment("\n"); ! graphDef.gprint("in8", "AVERAGE", "Average input: @7.2 @sbits/s"); ! graphDef.gprint("in8", "MAX", "Maximum input: @7.2 @Sbits/s\n"); ! graphDef.gprint("out8", "AVERAGE", "Average output:@7.2 @sbits/s"); ! graphDef.gprint("out8", "MAX", "Maximum output:@7.2 @Sbits/s\n"); ! graphDef.comment("\n"); ! graphDef.comment("Description on device: " + alias); ! graphDef.comment("\n"); ! graphDef.comment("Graph from " + new Date(start * 1000L)); ! graphDef.comment("to " + new Date(stop * 1000L + 1)); ! graph.setGraphDef(graphDef); ! return graph; ! } catch (RrdException e) { ! throw new MrtgException(e); } } } --- 73,97 ---- } ! RrdGraph getRrdGraph(long start, long end) throws MrtgException { ! RrdGraphDef rrdGraphDef; ! // only one template parsed, many threads plotting ! synchronized(rrdGraphDefTemplate) { ! rrdGraphDefTemplate.setVariable("start", start); ! rrdGraphDefTemplate.setVariable("end", end); ! rrdGraphDefTemplate.setVariable("interface", ifDescr); ! rrdGraphDefTemplate.setVariable("host", host); ! rrdGraphDefTemplate.setVariable("rrd", RrdWriter.getRrdFilename(host, ifDescr)); ! rrdGraphDefTemplate.setVariable("alias", alias); ! rrdGraphDefTemplate.setVariable("date_start", new Date(start * 1000L).toString()); ! rrdGraphDefTemplate.setVariable("date_end", new Date(end * 1000L).toString()); ! try { ! rrdGraphDef = rrdGraphDefTemplate.getRrdGraphDef(); ! } catch (RrdException e) { ! throw new MrtgException(e); ! } } + RrdGraph graph = new RrdGraph(true); // use pool + graph.setGraphDef(rrdGraphDef); + return graph; } } Index: RrdWriter.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/mrtg/server/RrdWriter.java,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** RrdWriter.java 9 Dec 2003 12:22:04 -0000 1.1 --- RrdWriter.java 8 Mar 2004 13:14:39 -0000 1.2 *************** *** 27,30 **** --- 27,32 ---- import org.jrobin.core.*; import org.jrobin.mrtg.Debug; + import org.jrobin.mrtg.MrtgConstants; + import org.jrobin.mrtg.MrtgException; import java.io.File; *************** *** 34,38 **** import java.util.List; ! class RrdWriter extends Thread { private int sampleCount, badSavesCount, goodSavesCount; private List queue = Collections.synchronizedList(new LinkedList()); --- 36,41 ---- import java.util.List; ! class RrdWriter extends Thread implements MrtgConstants { ! private RrdDefTemplate rrdDefTemplate; private int sampleCount, badSavesCount, goodSavesCount; private List queue = Collections.synchronizedList(new LinkedList()); *************** *** 42,46 **** private volatile boolean active = true; ! RrdWriter() { start(); } --- 45,57 ---- private volatile boolean active = true; ! RrdWriter() throws MrtgException { ! // get definition from template ! try { ! rrdDefTemplate = new RrdDefTemplate(new File(Config.getRrdTemplateFile())); ! } catch (IOException e) { ! throw new MrtgException(e); ! } catch (RrdException e) { ! throw new MrtgException(e); ! } start(); } *************** *** 112,121 **** } ! void store(RawSample sample) { queue.add(sample); sampleCount++; ! synchronized(this) { ! notify(); ! } } --- 123,130 ---- } ! synchronized void store(RawSample sample) { queue.add(sample); sampleCount++; ! notify(); } *************** *** 128,149 **** else { // create RRD file first ! final RrdDef rrdDef = new RrdDef(rrdFile); ! rrdDef.setStep(300); ! rrdDef.setStartTime(rawSample.getTimestamp() - 10); ! rrdDef.addDatasource("in", "COUNTER", 600, Double.NaN, Double.NaN); ! rrdDef.addDatasource("out", "COUNTER", 600, Double.NaN, Double.NaN); ! rrdDef.addArchive("AVERAGE", 0.5, 1, 600); ! rrdDef.addArchive("AVERAGE", 0.5, 6, 700); ! rrdDef.addArchive("AVERAGE", 0.5, 24, 775); ! rrdDef.addArchive("AVERAGE", 0.5, 288, 797); ! rrdDef.addArchive("MAX", 0.5, 1, 600); ! rrdDef.addArchive("MAX", 0.5, 6, 700); ! rrdDef.addArchive("MAX", 0.5, 24, 775); ! rrdDef.addArchive("MAX", 0.5, 288, 797); ! rrdDef.addArchive("MIN", 0.5, 1, 600); ! rrdDef.addArchive("MIN", 0.5, 6, 700); ! rrdDef.addArchive("MIN", 0.5, 24, 775); ! rrdDef.addArchive("MIN", 0.5, 288, 797); ! Debug.print("Created: " + rrdFile); return pool.requestRrdDb(rrdDef); } --- 137,143 ---- else { // create RRD file first ! rrdDefTemplate.setVariable("path", rrdFile); ! RrdDef rrdDef = rrdDefTemplate.getRrdDef(); ! Debug.print("Creating: " + rrdFile); return pool.requestRrdDb(rrdDef); } Index: Server.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/mrtg/server/Server.java,v retrieving revision 1.7 retrieving revision 1.8 diff -C2 -d -r1.7 -r1.8 *** Server.java 2 Mar 2004 09:47:49 -0000 1.7 --- Server.java 8 Mar 2004 13:14:39 -0000 1.8 *************** *** 26,31 **** import org.jrobin.core.RrdDb; - import org.jrobin.core.RrdDbPool; import org.jrobin.mrtg.MrtgException; import org.w3c.dom.Document; import org.w3c.dom.Element; --- 26,31 ---- import org.jrobin.core.RrdDb; import org.jrobin.mrtg.MrtgException; + import org.jrobin.mrtg.MrtgConstants; import org.w3c.dom.Document; import org.w3c.dom.Element; *************** *** 42,50 **** import java.io.FileOutputStream; import java.io.IOException; import java.util.Date; import java.util.Hashtable; import java.util.Vector; ! public class Server { private static Server instance; --- 42,51 ---- import java.io.FileOutputStream; import java.io.IOException; + import java.io.FileWriter; import java.util.Date; import java.util.Hashtable; import java.util.Vector; ! public class Server implements MrtgConstants { private static Server instance; *************** *** 74,77 **** --- 75,87 ---- throw new MrtgException("Cannot start Server, already started"); } + // create template files + try { + createXmlTemplateIfNecessary(Config.getRrdTemplateFile(), RRD_TEMPLATE_STR); + createXmlTemplateIfNecessary(Config.getGraphTemplateFile(), GRAPH_TEMPLATE_STR); + } + catch(IOException ioe) { + throw new MrtgException(ioe); + } + // load configuration String hwFile = Config.getHardwareFile(); if(new File(hwFile).exists()) { *************** *** 89,92 **** --- 99,113 ---- } + private void createXmlTemplateIfNecessary(String filePath, String fileContent) + throws IOException { + File file = new File(filePath); + if(!file.exists()) { + FileWriter writer = new FileWriter(filePath, false); + writer.write(fileContent); + writer.flush(); + writer.close(); + } + } + public synchronized void stop() throws MrtgException { if(!active) { |
From: <sa...@us...> - 2004-03-08 13:38:59
|
Update of /cvsroot/jrobin/src/org/jrobin/mrtg In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv10511/org/jrobin/mrtg Modified Files: MrtgConstants.java Log Message: XML templates improved Index: MrtgConstants.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/mrtg/MrtgConstants.java,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** MrtgConstants.java 9 Dec 2003 12:22:03 -0000 1.3 --- MrtgConstants.java 8 Mar 2004 13:14:39 -0000 1.4 *************** *** 27,36 **** public interface MrtgConstants { boolean DEBUG = false; int SERVER_PORT = 35353; ! int SCHEDULER_RESOLUTION = 3; // run Scheduler each 3 seconds int GRAPH_WIDTH = 502, GRAPH_HEIGHT = 234; } --- 27,208 ---- public interface MrtgConstants { + // turn debugging on/off boolean DEBUG = false; + // XML-RPC port to listen on int SERVER_PORT = 35353; ! // run Scheduler each 3 seconds ! int SCHEDULER_RESOLUTION = 3; + // graph dimensions int GRAPH_WIDTH = 502, GRAPH_HEIGHT = 234; + + // initial temeplate for RrdDef + String RRD_TEMPLATE_STR = + "<rrd_def> \n" + + " <path>${path}</path> \n" + + " <step>300</step> \n" + + " <datasource> \n" + + " <name>in</name> \n" + + " <type>COUNTER</type> \n" + + " <heartbeat>6000</heartbeat> \n" + + " <min>U</min> \n" + + " <max>U</max> \n" + + " </datasource> \n" + + " <datasource> \n" + + " <name>out</name> \n" + + " <type>COUNTER</type> \n" + + " <heartbeat>6000</heartbeat> \n" + + " <min>U</min> \n" + + " <max>U</max> \n" + + " </datasource> \n" + + " <archive> \n" + + " <cf>AVERAGE</cf> \n" + + " <xff>0.5</xff> \n" + + " <steps>1</steps> \n" + + " <rows>600</rows> \n" + + " </archive> \n" + + " <archive> \n" + + " <cf>AVERAGE</cf> \n" + + " <xff>0.5</xff> \n" + + " <steps>6</steps> \n" + + " <rows>700</rows> \n" + + " </archive> \n" + + " <archive> \n" + + " <cf>AVERAGE</cf> \n" + + " <xff>0.5</xff> \n" + + " <steps>24</steps> \n" + + " <rows>775</rows> \n" + + " </archive> \n" + + " <archive> \n" + + " <cf>AVERAGE</cf> \n" + + " <xff>0.5</xff> \n" + + " <steps>288</steps> \n" + + " <rows>797</rows> \n" + + " </archive> \n" + + " <archive> \n" + + " <cf>MAX</cf> \n" + + " <xff>0.5</xff> \n" + + " <steps>1</steps> \n" + + " <rows>600</rows> \n" + + " </archive> \n" + + " <archive> \n" + + " <cf>MAX</cf> \n" + + " <xff>0.5</xff> \n" + + " <steps>6</steps> \n" + + " <rows>700</rows> \n" + + " </archive> \n" + + " <archive> \n" + + " <cf>MAX</cf> \n" + + " <xff>0.5</xff> \n" + + " <steps>24</steps> \n" + + " <rows>775</rows> \n" + + " </archive> \n" + + " <archive> \n" + + " <cf>MAX</cf> \n" + + " <xff>0.5</xff> \n" + + " <steps>288</steps> \n" + + " <rows>797</rows> \n" + + " </archive> \n" + + " <archive> \n" + + " <cf>MIN</cf> \n" + + " <xff>0.5</xff> \n" + + " <steps>1</steps> \n" + + " <rows>600</rows> \n" + + " </archive> \n" + + " <archive> \n" + + " <cf>MIN</cf> \n" + + " <xff>0.5</xff> \n" + + " <steps>6</steps> \n" + + " <rows>700</rows> \n" + + " </archive> \n" + + " <archive> \n" + + " <cf>MIN</cf> \n" + + " <xff>0.5</xff> \n" + + " <steps>24</steps> \n" + + " <rows>775</rows> \n" + + " </archive> \n" + + " <archive> \n" + + " <cf>MIN</cf> \n" + + " <xff>0.5</xff> \n" + + " <steps>288</steps> \n" + + " <rows>797</rows> \n" + + " </archive> \n" + + "</rrd_def> "; + + // initial RrdGraphDef template + String GRAPH_TEMPLATE_STR = + "<rrd_graph_def> \n" + + " <span> \n" + + " <start>${start}</start> \n" + + " <end>${end}</end> \n" + + " </span> \n" + + " <options> \n" + + " <anti_aliasing>off</anti_aliasing> \n" + + " <border> \n" + + " <color>#FFFFFF</color> \n" + + " <width>0</width> \n" + + " </border> \n" + + " <title>${interface} at ${host}</title> \n" + + " <vertical_label>transfer speed [bits/sec]</vertical_label> \n" + + " </options> \n" + + " <datasources> \n" + + " <def> \n" + + " <name>in</name> \n" + + " <rrd>${rrd}</rrd> \n" + + " <source>in</source> \n" + + " <cf>AVERAGE</cf> \n" + + " </def> \n" + + " <def> \n" + + " <name>out</name> \n" + + " <rrd>${rrd}</rrd> \n" + + " <source>out</source> \n" + + " <cf>AVERAGE</cf> \n" + + " </def> \n" + + " <def> \n" + + " <name>in8</name> \n" + + " <rpn>in,8,*</rpn> \n" + + " </def> \n" + + " <def> \n" + + " <name>out8</name> \n" + + " <rpn>out,8,*</rpn> \n" + + " </def> \n" + + " </datasources> \n" + + " <graph> \n" + + " <area> \n" + + " <datasource>out8</datasource> \n" + + " <color>#00FF00</color> \n" + + " <legend>output traffic@l</legend> \n" + + " </area> \n" + + " <line> \n" + + " <datasource>in8</datasource> \n" + + " <color>#0000FF</color> \n" + + " <legend>input traffic@l</legend> \n" + + " </line> \n" + + " <gprint> \n" + + " <datasource>out8</datasource> \n" + + " <cf>AVERAGE</cf> \n" + + " <format>Average output:@7.2 @sbits/s</format> \n" + + " </gprint> \n" + + " <gprint> \n" + + " <datasource>out8</datasource> \n" + + " <cf>MAX</cf> \n" + + " <format>Maximum output:@7.2 @Sbits/s@l</format> \n" + + " </gprint> \n" + + " <gprint> \n" + + " <datasource>in8</datasource> \n" + + " <cf>AVERAGE</cf> \n" + + " <format>Average input: @7.2 @sbits/s</format> \n" + + " </gprint> \n" + + " <gprint> \n" + + " <datasource>in8</datasource> \n" + + " <cf>MAX</cf> \n" + + " <format>Maximum input: @7.2 @Sbits/s@l</format> \n" + + " </gprint> \n" + + " <comment>@l</comment> \n" + + " <comment>Description on device: ${alias}@l</comment> \n" + + " <comment>[${date_start}] -- [${date_end}]</comment> \n" + + " </graph> \n" + + "</rrd_graph_def> "; } |
From: <sa...@us...> - 2004-03-08 13:38:58
|
Update of /cvsroot/jrobin/src/org/jrobin/graph In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv10511/org/jrobin/graph Modified Files: RrdGraphDefTemplate.java Log Message: XML templates improved Index: RrdGraphDefTemplate.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/graph/RrdGraphDefTemplate.java,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** RrdGraphDefTemplate.java 1 Mar 2004 08:50:25 -0000 1.3 --- RrdGraphDefTemplate.java 8 Mar 2004 13:14:39 -0000 1.4 *************** *** 35,39 **** import java.awt.*; import java.util.GregorianCalendar; - import java.util.Date; /** --- 35,38 ---- *************** *** 753,762 **** } public static void main(String[] args) throws IOException, RrdException { File fileTemplate = new File("work/test2.xml"); RrdGraphDefTemplate template = new RrdGraphDefTemplate(fileTemplate); ! String stringTemplate = template.getRrdGraphDef().exportXmlTemplate(); ! template = new RrdGraphDefTemplate(stringTemplate); System.out.println(template.getRrdGraphDef().exportXmlTemplate()); } } --- 752,763 ---- } + /* public static void main(String[] args) throws IOException, RrdException { File fileTemplate = new File("work/test2.xml"); RrdGraphDefTemplate template = new RrdGraphDefTemplate(fileTemplate); ! template.setVariable("comment1", "[comment 1]"); ! template.setVariable("comment2", "[comment 2]"); System.out.println(template.getRrdGraphDef().exportXmlTemplate()); } + */ } |
From: <sa...@us...> - 2004-03-08 13:38:58
|
Update of /cvsroot/jrobin/src/org/jrobin/core In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv10511/org/jrobin/core Modified Files: RpnCalculator.java XmlTemplate.java XmlWriter.java Log Message: XML templates improved Index: RpnCalculator.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/core/RpnCalculator.java,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** RpnCalculator.java 10 Nov 2003 08:52:27 -0000 1.2 --- RpnCalculator.java 8 Mar 2004 13:14:39 -0000 1.3 *************** *** 397,400 **** --- 397,401 ---- } + /* public static void main(String[] args) throws RrdException { RpnCalculator c = new RpnCalculator("2,3,/,value,+"); *************** *** 402,404 **** --- 403,406 ---- System.out.println(c.calculate()); } + */ } Index: XmlTemplate.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/core/XmlTemplate.java,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** XmlTemplate.java 26 Feb 2004 13:15:54 -0000 1.4 --- XmlTemplate.java 8 Mar 2004 13:14:39 -0000 1.5 *************** *** 35,38 **** --- 35,40 ---- import java.util.Date; import java.util.GregorianCalendar; + import java.util.regex.Pattern; + import java.util.regex.Matcher; import java.awt.*; *************** *** 46,49 **** --- 48,54 ---- */ public abstract class XmlTemplate { + private static final String PATTERN_STRING = "\\$\\{(\\w+)\\}"; + private static final Pattern PATTERN = Pattern.compile(PATTERN_STRING); + protected Element root; private HashMap valueMap = new HashMap(); *************** *** 183,201 **** } ! private String resolveMappings(String value) { ! if(value != null && value.startsWith("${") && value.endsWith("}")) { ! // template variable found, remove leading "${" and trailing "}" ! String var = value.substring(2, value.length() - 1); if(valueMap.containsKey(var)) { // mapping found ! value = valueMap.get(var).toString(); } else { // no mapping found - this is illegal throw new IllegalArgumentException( ! "No mapping found for template variable " + value); } } ! return value; } --- 188,209 ---- } ! private String resolveMappings(String templateValue) { ! Matcher matcher = PATTERN.matcher(templateValue); ! StringBuffer result = new StringBuffer(); ! while(matcher.find()) { ! String var = matcher.group(1); if(valueMap.containsKey(var)) { // mapping found ! matcher.appendReplacement(result, valueMap.get(var).toString()); } else { // no mapping found - this is illegal + // throw runtime exception throw new IllegalArgumentException( ! "No mapping found for template variable ${" + var + "}"); } } ! matcher.appendTail(result); ! return result.toString(); } Index: XmlWriter.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/core/XmlWriter.java,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** XmlWriter.java 1 Mar 2004 08:50:24 -0000 1.5 --- XmlWriter.java 8 Mar 2004 13:14:39 -0000 1.6 *************** *** 195,201 **** return s.replaceAll("<", "<").replaceAll(">", ">"); } - - public static void main(String[] args) { - System.out.println(escape("<->")); - } } --- 195,197 ---- |
From: <sa...@us...> - 2004-03-02 10:07:23
|
Update of /cvsroot/jrobin/src/org/jrobin/mrtg/server In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv14981/org/jrobin/mrtg/server Modified Files: Server.java Log Message: Index: Server.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/mrtg/server/Server.java,v retrieving revision 1.6 retrieving revision 1.7 diff -C2 -d -r1.6 -r1.7 *** Server.java 1 Mar 2004 12:02:46 -0000 1.6 --- Server.java 2 Mar 2004 09:47:49 -0000 1.7 *************** *** 67,71 **** private Server() { RrdDb.setLockMode(RrdDb.NO_LOCKS); ! RrdDbPool.getInstance().setExclusiveMode(true); } --- 67,71 ---- private Server() { RrdDb.setLockMode(RrdDb.NO_LOCKS); ! //RrdDbPool.getInstance().setCapacity(500); } |
From: <sa...@us...> - 2004-03-02 10:07:21
|
Update of /cvsroot/jrobin/src/org/jrobin/core In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv14981/org/jrobin/core Modified Files: RrdDb.java RrdDbPool.java Log Message: Index: RrdDb.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/core/RrdDb.java,v retrieving revision 1.11 retrieving revision 1.12 diff -C2 -d -r1.11 -r1.12 *** RrdDb.java 1 Mar 2004 08:50:24 -0000 1.11 --- RrdDb.java 2 Mar 2004 09:47:49 -0000 1.12 *************** *** 239,242 **** --- 239,250 ---- /** + * Returns true if the underlying RRD file is closed. + * @return true if closed, false otherwise + */ + public boolean isClosed() { + return file == null; + } + + /** * <p>Returns underlying <code>RrdFile</code> object. <code>RrdFile</code> is a light * wrapper around <code>RandomAccessFile</code> class. Index: RrdDbPool.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/core/RrdDbPool.java,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** RrdDbPool.java 1 Mar 2004 12:02:46 -0000 1.4 --- RrdDbPool.java 2 Mar 2004 09:47:49 -0000 1.5 *************** *** 75,87 **** * reference will be returned again.<p> * ! * RrdDbPool has a 'garbage collector' which gets activated only when the number of open ! * RRD files is to big (> 50). Only RRD files with a reference count equal to zero ! * will be eligible for closing. Unreleased RrdDb references will be never invalidated. * RrdDbPool object keeps track of the time when each RRD file * becomes eligible for closing so that the oldest RRD file gets closed first.<p> * ! * Never use close() method on the reference returned from the pool. When the reference ! * is no longer needed, return it to the pool with a {@link #release(RrdDb) release()} ! * method.<p> * * However, you are not forced to use RrdDbPool methods to obtain RrdDb references --- 75,92 ---- * reference will be returned again.<p> * ! * RrdDbPool has a 'garbage collector' which runs in a separate ! * thread and gets activated only when the number of RRD files kept in the ! * pool is too big (greater than number returned from {@link #getCapacity getCapacity()}). ! * Only RRD files with a reference count equal to zero ! * will be eligible for closing. Unreleased RrdDb references are never invalidated. * RrdDbPool object keeps track of the time when each RRD file * becomes eligible for closing so that the oldest RRD file gets closed first.<p> * ! * Initial RrdDbPool capacity is set to 50. Use {@link #setCapacity(int)} method to ! * change it at any time.<p> ! * ! * <b>WARNING:</b>Never use close() method on the reference returned from the pool. ! * When the reference is no longer needed, return it to the pool with the ! * {@link #release(RrdDb) release()} method.<p> * * However, you are not forced to use RrdDbPool methods to obtain RrdDb references *************** *** 90,103 **** * threads and many simultaneously open RRD files.<p> * - * RrdDbPool can be forced to block (force wait on) all threads requesting access - * to a single RRD file which is already in use (not yet returned to the pool). - * If you want such feature, call - * {@link #setExclusiveMode setExclusiveMode()} method with a <code>true</code> argument.<p> - * * The pool is thread-safe.<p> */ ! public class RrdDbPool { private static RrdDbPool ourInstance; private static final boolean DEBUG = false; /** * Constant to represent the maximum number of internally open RRD files --- 95,121 ---- * threads and many simultaneously open RRD files.<p> * * The pool is thread-safe.<p> */ ! public class RrdDbPool implements Runnable { private static RrdDbPool ourInstance; private static final boolean DEBUG = false; + + private static final Comparator ENTRY_COMPARATOR = new Comparator() { + public int compare(Object o1, Object o2) { + RrdEntry r1 = (RrdEntry) o1, r2 = (RrdEntry) o2; + if (!r1.isReleased() && !r2.isReleased()) { + return 0; + } else if (r1.isReleased() && !r2.isReleased()) { + return -1; + } else if (!r1.isReleased() && r2.isReleased()) { + return +1; + } else { + // both released + long diff = r1.getReleaseDate().getTime() - + r2.getReleaseDate().getTime(); + return diff < 0L ? -1 : (diff == 0L ? 0 : +1); + } + } + }; /** * Constant to represent the maximum number of internally open RRD files *************** *** 105,111 **** */ public static final int INITIAL_CAPACITY = 50; ! private static int capacity = INITIAL_CAPACITY; ! ! private boolean exclusiveMode = false; private HashMap rrdMap = new HashMap(); --- 123,127 ---- */ public static final int INITIAL_CAPACITY = 50; ! private volatile int capacity = INITIAL_CAPACITY; private HashMap rrdMap = new HashMap(); *************** *** 118,121 **** --- 134,138 ---- if (ourInstance == null) { ourInstance = new RrdDbPool(); + ourInstance.startGarbageCollector(); } return ourInstance; *************** *** 125,128 **** --- 142,151 ---- } + private void startGarbageCollector() { + Thread gcThread = new Thread(this); + gcThread.setDaemon(true); + gcThread.start(); + } + /** * Returns a reference to an existing RRD file with the specified path. *************** *** 137,162 **** public synchronized RrdDb requestRrdDb(String path) throws IOException, RrdException { String keypath = getCanonicalPath(path); ! for (;;) { // ugly, but it works ! if (rrdMap.containsKey(keypath)) { ! // already open ! RrdEntry rrdEntry = (RrdEntry) rrdMap.get(keypath); ! if(exclusiveMode && rrdEntry.getUsageCount() > 0) { ! // reference already in use, wait until the reference ! // is returned to the pool ! try { ! wait(); ! } catch (InterruptedException e) { } ! // try to obtain the same reference once again ! continue; ! } ! rrdEntry.reportUsage(); ! debug("EXISTING: " + rrdEntry.dump()); ! return rrdEntry.getRrdDb(); ! } else { ! // not found, open it ! RrdDb rrdDb = new RrdDb(path); ! put(keypath, rrdDb); ! return rrdDb; ! } } } --- 160,174 ---- public synchronized RrdDb requestRrdDb(String path) throws IOException, RrdException { String keypath = getCanonicalPath(path); ! if (rrdMap.containsKey(keypath)) { ! // already open ! RrdEntry rrdEntry = (RrdEntry) rrdMap.get(keypath); ! rrdEntry.reportUsage(); ! debug("EXISTING: " + rrdEntry.dump()); ! return rrdEntry.getRrdDb(); ! } else { ! // not found, open it ! RrdDb rrdDb = new RrdDb(path); ! put(keypath, rrdDb); ! return rrdDb; } } *************** *** 198,206 **** } ! private void put(String keypath, RrdDb rrdDb) throws IOException { RrdEntry newEntry = new RrdEntry(rrdDb); debug("NEW: " + newEntry.dump()); rrdMap.put(keypath, newEntry); ! gc(); } --- 210,219 ---- } ! private synchronized void put(String keypath, RrdDb rrdDb) throws IOException { RrdEntry newEntry = new RrdEntry(rrdDb); debug("NEW: " + newEntry.dump()); rrdMap.put(keypath, newEntry); ! // notify garbage collector ! notify(); } *************** *** 237,244 **** return; } ! RrdFile rrdFile = rrdDb.getRrdFile(); ! if(rrdFile == null) { throw new RrdException("Cannot release: already closed"); } String path = rrdFile.getFilePath(); String keypath = getCanonicalPath(path); --- 250,257 ---- return; } ! if(rrdDb.isClosed()) { throw new RrdException("Cannot release: already closed"); } + RrdFile rrdFile = rrdDb.getRrdFile(); String path = rrdFile.getFilePath(); String keypath = getCanonicalPath(path); *************** *** 246,296 **** RrdEntry rrdEntry = (RrdEntry) rrdMap.get(keypath); rrdEntry.release(); - if(exclusiveMode) { - notifyAll(); - } debug("RELEASED: " + rrdEntry.dump()); } else { ! throw new RrdException("RrdDb with path " + keypath + " not in the pool"); } ! gc(); } ! private void gc() throws IOException { ! int mapSize = rrdMap.size(); ! if(mapSize <= capacity) { ! // nothing to do ! debug("GC: no need to run"); ! return; ! } ! // prepare collection of released entries ! debug("GC: finding the oldest released entry"); ! Iterator valueIterator = rrdMap.values().iterator(); ! LinkedList releasedEntries = new LinkedList(); ! while(valueIterator.hasNext()) { ! RrdEntry rrdEntry = (RrdEntry) valueIterator.next(); ! if(rrdEntry.isReleased()) { ! releasedEntries.add(rrdEntry); } } - if(releasedEntries.size() == 0) { - debug("GC: no released entries found, nothing to do"); - return; - } - debug("GC: found " + releasedEntries.size() + " released entries"); - Comparator releaseDateComparator = new Comparator() { - public int compare(Object o1, Object o2) { - RrdEntry r1 = (RrdEntry) o1, r2 = (RrdEntry) o2; - long diff = r1.getReleaseDate().getTime() - r2.getReleaseDate().getTime(); - return diff < 0? -1: (diff == 0? 0: +1); - } - }; - RrdEntry oldestEntry = (RrdEntry) - Collections.min(releasedEntries, releaseDateComparator); - debug("GC: oldest released entry found: " + oldestEntry.dump()); - oldestEntry.close(); - rrdMap.values().remove(oldestEntry); - debug("GC: oldest entry closed and removed. "); - debug("GC: number of entries reduced from " + mapSize + " to " + rrdMap.size()); } --- 259,309 ---- RrdEntry rrdEntry = (RrdEntry) rrdMap.get(keypath); rrdEntry.release(); debug("RELEASED: " + rrdEntry.dump()); } else { ! throw new RrdException("RRD file " + keypath + " not in the pool"); } ! // notify garbage collector ! notify(); } ! /** ! * This method runs garbage collector in a separate thread. If the number of ! * open RRD files kept in the pool is too big (greater than number ! * returned from {@link #getCapacity getCapacity()}), garbage collector will try ! * to close and remove RRD files with a reference count equal to zero. ! * Never call this method directly. ! */ ! public void run() { ! debug("GC: started"); ! synchronized (this) { ! for (;;) { ! while (rrdMap.size() > capacity) { ! debug("GC: should run: (" + rrdMap.size() + " > " + capacity + ")"); ! RrdEntry oldestEntry = (RrdEntry) ! Collections.min(rrdMap.values(), ENTRY_COMPARATOR); ! if (oldestEntry.isReleased()) { ! try { ! debug("GC: closing " + oldestEntry.dump()); ! oldestEntry.close(); ! } catch (IOException e) { ! debug("GC error: " + e); ! e.printStackTrace(); ! } ! rrdMap.values().remove(oldestEntry); ! } else { ! // all references are used ! debug("GC: NOP: all references are active (" + rrdMap.size() + ")"); ! break; ! } ! } ! try { ! // nothing to do ! debug("GC: sleeping (" + rrdMap.size() + ")"); ! wait(); ! debug("GC: running"); ! } catch (InterruptedException e) { } } } } *************** *** 347,351 **** * @return Desired nuber of open files held in the pool. */ ! public static int getCapacity() { return capacity; } --- 360,364 ---- * @return Desired nuber of open files held in the pool. */ ! public int getCapacity() { return capacity; } *************** *** 357,383 **** * @param capacity Desired number of open files to hold in the pool */ ! public static void setCapacity(int capacity) { ! RrdDbPool.capacity = capacity; ! } ! ! /** ! * Checks if RrdDbPool will return a reference to an already open RRD file if it is still ! * in use (not released, not returned to the pool). If true, simultaneous access ! * to the same RRD file will not be possible. ! * @return Current working mode of RrdDbPool (initial working mode is <code>false</code>) ! */ ! public boolean isExclusiveMode() { ! return exclusiveMode; ! } ! ! /** ! * Method used to set the current working mode of RrdDbPool. If set to true, simultaneous ! * access to the same RRD file will not be possible. In case of several threads requesting ! * a reference to the same RRD file, one thread will get the reference, other threads will ! * block until the reference is returned to the pool. ! * @param exclusiveMode Working mode of RrdDbPool ! */ ! public void setExclusiveMode(boolean exclusiveMode) { ! this.exclusiveMode = exclusiveMode; } --- 370,375 ---- * @param capacity Desired number of open files to hold in the pool */ ! public void setCapacity(int capacity) { ! this.capacity = capacity; } |
From: <sa...@us...> - 2004-03-01 13:30:22
|
Update of /cvsroot/jrobin/src/org/jrobin/mrtg/client In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv31804/org/jrobin/mrtg/client Modified Files: GraphFrame.java Log Message: Index: GraphFrame.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/mrtg/client/GraphFrame.java,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** GraphFrame.java 10 Nov 2003 08:52:29 -0000 1.2 --- GraphFrame.java 1 Mar 2004 13:11:26 -0000 1.3 *************** *** 230,234 **** leftButton.setMnemonic(KeyEvent.VK_L); rightButton.setMnemonic(KeyEvent.VK_R); ! setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); try { setIconImage(Resources.getImage(Client.ICON)); --- 230,234 ---- leftButton.setMnemonic(KeyEvent.VK_L); rightButton.setMnemonic(KeyEvent.VK_R); ! setDefaultCloseOperation(DISPOSE_ON_CLOSE); try { setIconImage(Resources.getImage(Client.ICON)); |
From: <sa...@us...> - 2004-03-01 12:21:40
|
Update of /cvsroot/jrobin/src/org/jrobin/core In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv20110/org/jrobin/core Modified Files: RrdDbPool.java Log Message: Improved RrdDbPool, removed bug in Grapher (RRD files were never closed or returned to the pool) Index: RrdDbPool.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/core/RrdDbPool.java,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** RrdDbPool.java 12 Nov 2003 10:22:09 -0000 1.3 --- RrdDbPool.java 1 Mar 2004 12:02:46 -0000 1.4 *************** *** 90,95 **** * threads and many simultaneously open RRD files.<p> * ! * The pool is thread-safe. * */ public class RrdDbPool { --- 90,99 ---- * threads and many simultaneously open RRD files.<p> * ! * RrdDbPool can be forced to block (force wait on) all threads requesting access ! * to a single RRD file which is already in use (not yet returned to the pool). ! * If you want such feature, call ! * {@link #setExclusiveMode setExclusiveMode()} method with a <code>true</code> argument.<p> * + * The pool is thread-safe.<p> */ public class RrdDbPool { *************** *** 103,106 **** --- 107,112 ---- private static int capacity = INITIAL_CAPACITY; + private boolean exclusiveMode = false; + private HashMap rrdMap = new HashMap(); *************** *** 131,146 **** public synchronized RrdDb requestRrdDb(String path) throws IOException, RrdException { String keypath = getCanonicalPath(path); ! if(rrdMap.containsKey(keypath)) { ! // already open ! RrdEntry rrdEntry = (RrdEntry) rrdMap.get(keypath); ! rrdEntry.reportUsage(); ! debug("EXISTING: " + rrdEntry.dump()); ! return rrdEntry.getRrdDb(); ! } ! else { ! // not found, open it ! RrdDb rrdDb = new RrdDb(path); ! put(keypath, rrdDb); ! return rrdDb; } } --- 137,162 ---- public synchronized RrdDb requestRrdDb(String path) throws IOException, RrdException { String keypath = getCanonicalPath(path); ! for (;;) { // ugly, but it works ! if (rrdMap.containsKey(keypath)) { ! // already open ! RrdEntry rrdEntry = (RrdEntry) rrdMap.get(keypath); ! if(exclusiveMode && rrdEntry.getUsageCount() > 0) { ! // reference already in use, wait until the reference ! // is returned to the pool ! try { ! wait(); ! } catch (InterruptedException e) { } ! // try to obtain the same reference once again ! continue; ! } ! rrdEntry.reportUsage(); ! debug("EXISTING: " + rrdEntry.dump()); ! return rrdEntry.getRrdDb(); ! } else { ! // not found, open it ! RrdDb rrdDb = new RrdDb(path); ! put(keypath, rrdDb); ! return rrdDb; ! } } } *************** *** 230,237 **** RrdEntry rrdEntry = (RrdEntry) rrdMap.get(keypath); rrdEntry.release(); debug("RELEASED: " + rrdEntry.dump()); } else { ! throw new RrdException("RrdDb with path " + keypath + " not in pool"); } gc(); --- 246,256 ---- RrdEntry rrdEntry = (RrdEntry) rrdMap.get(keypath); rrdEntry.release(); + if(exclusiveMode) { + notifyAll(); + } debug("RELEASED: " + rrdEntry.dump()); } else { ! throw new RrdException("RrdDb with path " + keypath + " not in the pool"); } gc(); *************** *** 342,345 **** --- 361,385 ---- } + /** + * Checks if RrdDbPool will return a reference to an already open RRD file if it is still + * in use (not released, not returned to the pool). If true, simultaneous access + * to the same RRD file will not be possible. + * @return Current working mode of RrdDbPool (initial working mode is <code>false</code>) + */ + public boolean isExclusiveMode() { + return exclusiveMode; + } + + /** + * Method used to set the current working mode of RrdDbPool. If set to true, simultaneous + * access to the same RRD file will not be possible. In case of several threads requesting + * a reference to the same RRD file, one thread will get the reference, other threads will + * block until the reference is returned to the pool. + * @param exclusiveMode Working mode of RrdDbPool + */ + public void setExclusiveMode(boolean exclusiveMode) { + this.exclusiveMode = exclusiveMode; + } + private class RrdEntry { private RrdDb rrdDb; |
From: <sa...@us...> - 2004-03-01 12:21:39
|
Update of /cvsroot/jrobin/src/org/jrobin/mrtg/server In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv20110/org/jrobin/mrtg/server Modified Files: Server.java Log Message: Improved RrdDbPool, removed bug in Grapher (RRD files were never closed or returned to the pool) Index: Server.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/mrtg/server/Server.java,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** Server.java 20 Jan 2004 10:07:50 -0000 1.5 --- Server.java 1 Mar 2004 12:02:46 -0000 1.6 *************** *** 26,29 **** --- 26,30 ---- import org.jrobin.core.RrdDb; + import org.jrobin.core.RrdDbPool; import org.jrobin.mrtg.MrtgException; import org.w3c.dom.Document; *************** *** 66,69 **** --- 67,71 ---- private Server() { RrdDb.setLockMode(RrdDb.NO_LOCKS); + RrdDbPool.getInstance().setExclusiveMode(true); } |
From: <sa...@us...> - 2004-03-01 12:21:39
|
Update of /cvsroot/jrobin/src/org/jrobin/graph In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv20110/org/jrobin/graph Modified Files: Grapher.java RrdGraph.java Log Message: Improved RrdDbPool, removed bug in Grapher (RRD files were never closed or returned to the pool) Index: Grapher.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/graph/Grapher.java,v retrieving revision 1.6 retrieving revision 1.7 diff -C2 -d -r1.6 -r1.7 *** Grapher.java 15 Jan 2004 22:24:30 -0000 1.6 --- Grapher.java 1 Mar 2004 12:02:46 -0000 1.7 *************** *** 307,311 **** // Get the rrdDb src = (FetchSource) fetchSources.next(); ! rrd = rrdGraph.getRrd( src.getRrdFile() ); // If the endtime is 0, use the last time a database was updated --- 307,312 ---- // Get the rrdDb src = (FetchSource) fetchSources.next(); ! String rrdFile = src.getRrdFile(); ! rrd = rrdGraph.getRrd( rrdFile ); // If the endtime is 0, use the last time a database was updated *************** *** 321,325 **** ve = src.fetch( rrd, startTime, endTime ); varList = ve.getNames(); ! for (int i= 0; i < varList.length; i++) { sources[tblPos] = new Def(varList[i], numPoints); --- 322,329 ---- ve = src.fetch( rrd, startTime, endTime ); varList = ve.getNames(); ! ! // BUGFIX: Release the rrdDb ! rrdGraph.releaseRrd(rrd); ! for (int i= 0; i < varList.length; i++) { sources[tblPos] = new Def(varList[i], numPoints); Index: RrdGraph.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/graph/RrdGraph.java,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** RrdGraph.java 20 Nov 2003 20:56:32 -0000 1.3 --- RrdGraph.java 1 Mar 2004 12:02:46 -0000 1.4 *************** *** 383,387 **** return new RrdDb( rrdFile ); } ! // ================================================================ // -- Private methods --- 383,396 ---- return new RrdDb( rrdFile ); } ! ! void releaseRrd(RrdDb rrdDb) throws RrdException, IOException { ! if(pool != null) { ! pool.release(rrdDb); ! } ! else { ! rrdDb.close(); ! } ! } ! // ================================================================ // -- Private methods |
Update of /cvsroot/jrobin/src/org/jrobin/graph In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv19077/org/jrobin/graph Modified Files: Area.java Cdef.java Comment.java CustomArea.java CustomLine.java FetchSource.java Gprint.java GridRange.java Line.java PlotDef.java RrdGraphDef.java RrdGraphDefTemplate.java Stack.java TimeAxisLabel.java TimeAxisUnit.java TimeGrid.java Title.java ValueAxisUnit.java Log Message: XML templates for RrdDef and RrdGraphDef completed. Index: Area.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/graph/Area.java,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** Area.java 15 Jan 2004 22:24:30 -0000 1.3 --- Area.java 1 Mar 2004 08:50:25 -0000 1.4 *************** *** 25,28 **** --- 25,30 ---- package org.jrobin.graph; + import org.jrobin.core.XmlWriter; + import java.awt.Color; *************** *** 123,139 **** } ! String getXml( String legend ) { ! StringBuffer xml = new StringBuffer(); ! ! xml.append( "\t\t<area>\n" ); ! xml.append( "\t\t\t<datasource>" + sourceName + "</datasource>\n" ); ! if ( color != null ) ! xml.append( "\t\t\t<color r=\"" + color.getRed() + "\" g=\"" + color.getGreen() + "\" b=\"" + color.getBlue() + "\" />\n" ); ! if ( legend != null ) ! xml.append( "\t\t\t<legend>" + legend + "</legend>\n" ); ! xml.append( "\t\t</area>\n" ); ! ! return xml.toString(); } } --- 125,135 ---- } ! void exportXmlTemplate( XmlWriter xml, String legend ) { ! xml.startTag("area"); ! xml.writeTag("datasource", sourceName); ! xml.writeTag("color", color); ! xml.writeTag("legend", legend); ! xml.closeTag(); // area } } Index: Cdef.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/graph/Cdef.java,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** Cdef.java 15 Jan 2004 22:24:30 -0000 1.3 --- Cdef.java 1 Mar 2004 08:50:25 -0000 1.4 *************** *** 29,32 **** --- 29,33 ---- import org.jrobin.core.RrdException; + import org.jrobin.core.XmlWriter; /** *************** *** 221,233 **** } - public String getXml() - { - StringBuffer xml = new StringBuffer( "" ); - - xml.append( "\t\t<cdef name=\"" + this.getName() + "\">" + getRpnString() + "</cdef>\n"); - - return xml.toString(); - } - // ================================================================ // -- Private methods --- 222,225 ---- *************** *** 250,252 **** --- 242,251 ---- } } + + void exportXml(XmlWriter xml) { + xml.startTag("def"); + xml.writeTag("name", getName()); + xml.writeTag("rpn", getRpnString()); + xml.closeTag(); // def + } } Index: Comment.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/graph/Comment.java,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** Comment.java 15 Jan 2004 22:24:30 -0000 1.2 --- Comment.java 1 Mar 2004 08:50:25 -0000 1.3 *************** *** 28,31 **** --- 28,32 ---- import org.jrobin.core.RrdException; + import org.jrobin.core.XmlWriter; /** *************** *** 249,260 **** return trimString; } ! ! String getXml() ! { ! StringBuffer xml = new StringBuffer(); ! ! xml.append( "\t\t<comment>" + text + "</comment>\n" ); ! ! return xml.toString(); } } --- 250,260 ---- return trimString; } ! ! String getText() { ! return text; ! } ! ! void exportXmlTemplate(XmlWriter xml) { ! xml.writeTag("comment", getText()); } } Index: CustomArea.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/graph/CustomArea.java,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** CustomArea.java 15 Jan 2004 22:24:30 -0000 1.2 --- CustomArea.java 1 Mar 2004 08:50:25 -0000 1.3 *************** *** 29,32 **** --- 29,33 ---- import org.jrobin.core.RrdException; + import org.jrobin.core.XmlWriter; /** *************** *** 169,185 **** } ! String getXml( String legend ) ! { ! StringBuffer xml = new StringBuffer(); ! ! xml.append( "\t\t<custom-area>\n" ); ! xml.append( "\t\t\t<datasource>" + sourceName + "</datasource>\n" ); ! if ( color != null ) ! xml.append( "\t\t\t<color r=\"" + color.getRed() + "\" g=\"" + color.getGreen() + "\" b=\"" + color.getBlue() + "\" />\n" ); ! if ( legend != null ) ! xml.append( "\t\t\t<legend>" + legend + "</legend>\n" ); ! xml.append( "\t\t</custom-area>\n" ); ! ! return xml.toString(); } } --- 170,182 ---- } ! void exportXmlTemplate( XmlWriter xml, String legend ) { ! xml.startTag("area"); ! xml.writeTag("time1", xVal1); ! xml.writeTag("value1", yVal1); ! xml.writeTag("time2", xVal2); ! xml.writeTag("value2", yVal2); ! xml.writeTag("color", color); ! xml.writeTag("legend", legend); ! xml.closeTag(); //area } } Index: CustomLine.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/graph/CustomLine.java,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** CustomLine.java 7 Nov 2003 08:23:19 -0000 1.1 --- CustomLine.java 1 Mar 2004 08:50:25 -0000 1.2 *************** *** 30,33 **** --- 30,34 ---- import org.jrobin.core.RrdException; + import org.jrobin.core.XmlWriter; /** *************** *** 206,208 **** --- 207,242 ---- void setSource( Source[] sources, HashMap sourceIndex ) throws RrdException { } + + void exportXmlTemplate( XmlWriter xml, String legend ) { + if(yVal1 == yVal2 && xVal1 != xVal2) { + // hrule + xml.startTag("hrule"); + xml.writeTag("value", yVal1); + xml.writeTag("color", color); + xml.writeTag("legend", legend); + xml.writeTag("width", lineWidth); + xml.closeTag(); // hrule + } + else if(yVal1 != yVal2 && xVal1 == xVal2) { + // vrule + xml.startTag("vrule"); + xml.writeTag("time", xVal1); + xml.writeTag("color", color); + xml.writeTag("legend", legend); + xml.writeTag("width", lineWidth); + xml.closeTag(); // vrule + } + else if(yVal1 != yVal2 && xVal1 != xVal2) { + // general line + xml.startTag("line"); + xml.writeTag("time1", xVal1); + xml.writeTag("value1", yVal1); + xml.writeTag("time2", xVal2); + xml.writeTag("value2", yVal2); + xml.writeTag("color", color); + xml.writeTag("legend", legend); + xml.writeTag("width", lineWidth); + xml.closeTag(); //line + } + } } Index: FetchSource.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/graph/FetchSource.java,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** FetchSource.java 15 Jan 2004 22:24:30 -0000 1.2 --- FetchSource.java 1 Mar 2004 08:50:25 -0000 1.3 *************** *** 28,35 **** import java.io.IOException; ! import org.jrobin.core.RrdDb; ! import org.jrobin.core.FetchData; ! import org.jrobin.core.FetchRequest; ! import org.jrobin.core.RrdException; /** --- 28,32 ---- import java.io.IOException; ! import org.jrobin.core.*; /** *************** *** 92,116 **** } - public String getXml() - { - StringBuffer xml = new StringBuffer( "" ); - - for ( int i = 0; i < datasources.length; i++ ) { - for ( int j = 0; j < datasources[i].size(); j++ ) { - String[] pair = (String[]) datasources[i].elementAt(j); - - xml.append( "\t\t<def name=\"" + pair[1] + "\">\n" ); - xml.append( "\t\t\t<file>" + rrdFile + "</file>\n" ); - xml.append( "\t\t\t<ds-name>" + pair[0] + "</ds-name>\n" ); - xml.append( "\t\t\t<cf>" + cfNames[i] + "</cf>\n" ); - xml.append( "\t\t</def>\n" ); - //<file>test.rrd</file> - //<ds-name>ifInOctets</ds-name> - //<cf>AVERAGE</cf> - } - } - return xml.toString(); - } - // ================================================================ // -- Protected methods --- 89,92 ---- *************** *** 188,191 **** protected String getRrdFile() { return rrdFile; ! } } --- 164,181 ---- protected String getRrdFile() { return rrdFile; ! } ! ! public void exportXml(XmlWriter xml) { ! for ( int i = 0; i < datasources.length; i++ ) { ! for ( int j = 0; j < datasources[i].size(); j++ ) { ! String[] pair = (String[]) datasources[i].elementAt(j); ! xml.startTag("def"); ! xml.writeTag("name", pair[1]); ! xml.writeTag("rrd", rrdFile); ! xml.writeTag("source", pair[0]); ! xml.writeTag("cf", cfNames[i]); ! xml.closeTag(); // def ! } ! } ! } } Index: Gprint.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/graph/Gprint.java,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** Gprint.java 15 Jan 2004 22:24:30 -0000 1.2 --- Gprint.java 1 Mar 2004 08:50:25 -0000 1.3 *************** *** 30,33 **** --- 30,34 ---- import org.jrobin.core.RrdException; + import org.jrobin.core.XmlWriter; /** *************** *** 175,193 **** } ! /** ! * ! */ ! String getXml() ! { ! StringBuffer xml = new StringBuffer(); ! ! xml.append( "\t\t<gprint>\n" ); ! xml.append( "\t\t\t<datasource>" + sourceName + "</datasource>\n" ); ! xml.append( "\t\t\t<cf>" + Source.aggregates[aggregate] + "</cf>\n" ); ! xml.append( "\t\t\t<text>" + text + "</text>\n" ); ! xml.append( "\t\t</gprint>\n" ); ! ! return xml.toString(); } ! } --- 176,186 ---- } ! void exportXmlTemplate(XmlWriter xml) { ! xml.startTag("gprint"); ! xml.writeTag("datasource", sourceName); ! xml.writeTag("cf", Source.aggregates[aggregate]); ! xml.writeTag("format", text); ! xml.closeTag(); // gprint } ! } Index: GridRange.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/graph/GridRange.java,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** GridRange.java 7 Nov 2003 08:23:19 -0000 1.1 --- GridRange.java 1 Mar 2004 08:50:25 -0000 1.2 *************** *** 25,28 **** --- 25,30 ---- package org.jrobin.graph; + import org.jrobin.core.XmlWriter; + /** * <p>Represents Y grid specifications for the chart area.</p> *************** *** 87,89 **** --- 89,99 ---- return rigid; } + + void exportXmlTemplate(XmlWriter xml) { + xml.startTag("grid_range"); + xml.writeTag("lower", getLowerValue()); + xml.writeTag("upper", getUpperValue()); + xml.writeTag("rigid", isRigid()); + xml.closeTag(); // grid_range + } } Index: Line.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/graph/Line.java,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** Line.java 15 Jan 2004 22:24:30 -0000 1.3 --- Line.java 1 Mar 2004 08:50:25 -0000 1.4 *************** *** 29,32 **** --- 29,33 ---- import org.jrobin.core.RrdException; + import org.jrobin.core.XmlWriter; /** *************** *** 132,149 **** } ! String getXml( String legend ) { ! StringBuffer xml = new StringBuffer(); ! ! xml.append( "\t\t<line>\n" ); ! xml.append( "\t\t\t<datasource>" + sourceName + "</datasource>\n" ); ! if ( color != null ) ! xml.append( "\t\t\t<color r=\"" + color.getRed() + "\" g=\"" + color.getGreen() + "\" b=\"" + color.getBlue() + "\" />\n" ); ! if ( legend != null ) ! xml.append( "\t\t\t<legend>" + legend + "</legend>\n" ); ! xml.append( "\t\t\t<width>" + lineWidth + "</width>\n" ); ! xml.append( "\t\t</line>\n" ); ! ! return xml.toString(); } } --- 133,144 ---- } ! void exportXmlTemplate( XmlWriter xml, String legend ) { ! xml.startTag("line"); ! xml.writeTag("datasource", sourceName); ! xml.writeTag("color", color); ! xml.writeTag("legend", legend); ! xml.writeTag("width", lineWidth); ! xml.closeTag(); // area } } Index: PlotDef.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/graph/PlotDef.java,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** PlotDef.java 15 Jan 2004 22:24:30 -0000 1.2 --- PlotDef.java 1 Mar 2004 08:50:25 -0000 1.3 *************** *** 29,32 **** --- 29,33 ---- import org.jrobin.core.RrdException; + import org.jrobin.core.XmlWriter; /** *************** *** 129,138 **** abstract void draw( ChartGraphics g, int[] xValues, int[] stackValues, int lastPlotType ) throws RrdException; - /** - * Abstract getXml method, must be implemented in all child classes. - * This method is reponsible for returning a corresponding JRobin XML string for the PlotDef. - */ - abstract String getXml( String legend ); - Source getSource() { return source; --- 130,133 ---- *************** *** 150,152 **** --- 145,151 ---- return color; } + + void exportXmlTemplate(XmlWriter xml, String legend) { + + } } Index: RrdGraphDef.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/graph/RrdGraphDef.java,v retrieving revision 1.7 retrieving revision 1.8 diff -C2 -d -r1.7 -r1.8 *** RrdGraphDef.java 26 Feb 2004 10:33:30 -0000 1.7 --- RrdGraphDef.java 1 Mar 2004 08:50:25 -0000 1.8 *************** *** 25,30 **** package org.jrobin.graph; ! import java.io.File; ! import java.io.Serializable; import java.awt.Font; import java.awt.Color; --- 25,29 ---- package org.jrobin.graph; ! import java.io.*; import java.awt.Font; import java.awt.Color; *************** *** 39,42 **** --- 38,42 ---- import org.jrobin.core.Util; import org.jrobin.core.RrdException; + import org.jrobin.core.XmlWriter; /** *************** *** 543,546 **** --- 543,550 ---- } + int getUnitsExponent() { + return (6 - scaleIndex) * 3; + } + /** * Sets value range that will be presented in the graph. If not set, graph limits will be autoscaled. *************** *** 899,1007 **** addComment( new Gprint(sourceName, consolFun, format) ); } ! ! /* ! public String getJRobinXml() ! { ! StringBuffer xml = new StringBuffer( "" ); ! ! // -- Create the general block ! xml.append( "\t<general>\n" ); ! ! // Time period ! xml.append( "\t\t<period>\n" ); ! xml.append( "\t\t\t<start>" + startTime + "</start>\n" ); ! xml.append( "\t\t\t<end>" + endTime + "</end>\n" ); ! xml.append( "\t\t</period>\n" ); ! ! // Labels ! if ( title != null || valueAxisLabel != null || timeAxisLabel != null ) ! { ! xml.append( "\t\t<labels>\n" ); ! if ( title != null ) ! xml.append( "\t\t\t<title>" + title.text + "</title>\n" ); ! if ( valueAxisLabel != null ) ! xml.append( "\t\t\t<vertical-label>" + valueAxisLabel + "</vertical-label>\n" ); ! if ( timeAxisLabel != null ) ! xml.append( "\t\t\t<horizontal-label>" + timeAxisLabel.text + "</horizontal-label>\n" ); ! xml.append( "\t\t</labels>\n" ); } ! ! // General colors ! xml.append( "\t\t<colors>\n" ); ! xml.append( "\t\t\t<background r=\"" + backColor.getRed() + "\" g=\"" + backColor.getGreen() + "\" b=\"" + backColor.getBlue() + "\" />\n" ); ! xml.append( "\t\t\t<canvas r=\"" + canvasColor.getRed() + "\" g=\"" + canvasColor.getGreen() + "\" b=\"" + canvasColor.getBlue() + "\" />\n" ); ! xml.append( "\t\t</colors>\n" ); ! ! // General data information ! ! // General visual options ! xml.append( "\t\t<visual>\n" ); ! xml.append( "\t\t\t<show-legend>" + (showLegend ? "yes" : "no") + "</show-legend>\n" ); ! if ( background != null ) ! xml.append( "\t\t\t<background-image>" + background.getAbsolutePath() + "</background-image>\n" ); ! if ( overlay != null ) ! xml.append( "\t\t\t<overlay-image>" + overlay.getAbsolutePath() + "</overlay-image>\n" ); ! if ( borderStroke != null ) ! { ! xml.append( "\t\t\t<image-border>\n" ); ! xml.append( "\t\t\t\t<width>" + borderStroke.getLineWidth() + "</width>\n" ); ! xml.append( "\t\t\t\t<color r=\"" + borderColor.getRed() + "\" g=\"" + borderColor.getGreen() + "\" b=\"" + borderColor.getBlue() + "\" />\n" ); ! xml.append( "\t\t\t</image-border>\n" ); } ! if ( gridRange != null ) ! { ! xml.append( "\t\t\t<grid>\n" ); ! xml.append( "\t\t\t\t<lower>" + gridRange.getLowerValue() + "</lower>\n" ); ! xml.append( "\t\t\t\t<upper>" + gridRange.getUpperValue() + "</upper>\n" ); ! xml.append( "\t\t\t\t<rigid>" + (gridRange.isRigid() ? "yes" : "no") + "</rigid>\n" ); ! xml.append( "\t\t\t</grid>\n" ); } ! //xml.append( "\t\t\t<canvas r=\"" + canvasColor.getRed() + "\" g=\"" + canvasColor.getGreen() + "\" b=\"" + canvasColor.getBlue() + "\" />\n" ); ! xml.append( "\t\t</visual>\n" ); ! ! xml.append( "\t</general>\n" ); ! // ------------------------------------------------------------- ! ! ! // -- Create the datasources block ! xml.append( "\t<datasources>\n" ); ! ! // Add all defs Iterator fsIterator = fetchSources.values().iterator(); ! while ( fsIterator.hasNext() ) ! xml.append( ((FetchSource) fsIterator.next()).getXml() ); ! ! // Add all cdefs ! for ( int i = 0; i < cdefList.size(); i++ ) ! xml.append( ((Cdef) cdefList.elementAt(i)).getXml() ); ! ! xml.append( "\t</datasources>\n" ); ! // ------------------------------------------------------------- ! ! ! // -- Create the graphing block ! // Run through the comments, if its a legend or nolegend, get the plotdef xml ! // else get the comment or gprint xml ! xml.append( "\t<graphing>\n" ); for ( int i = 0; i < comments.size(); i++ ) { Comment cmt = (Comment) comments.elementAt(i); ! if ( cmt.commentType == Comment.CMT_LEGEND || cmt.commentType == Comment.CMT_NOLEGEND ) { PlotDef pDef = (PlotDef) plotDefs.elementAt( ((Legend) cmt).getPlofDefIndex() ); ! xml.append( pDef.getXml(cmt.text) ); } - else - xml.append( cmt.getXml() ); } ! xml.append( "\t</graphing>\n" ); ! // ------------------------------------------------------------- ! ! xml.insert( 0, "<jrobin-graph>\n"); ! xml.append( "</jrobin-graph>\n" ); ! ! return xml.toString(); } ! */ // ================================================================ // -- Protected (package) methods --- 903,1040 ---- addComment( new Gprint(sourceName, consolFun, format) ); } ! ! /** ! * Exports RrdGraphDef (graph definition) object in XML format to output stream. ! * Generated code can be parsed with {@link RrdGraphDefTemplate} class. ! * @param stream Output stream to send XML code to ! */ ! public void exportXmlTemplate(OutputStream stream) { ! XmlWriter xml = new XmlWriter(stream); ! xml.startTag("rrd_graph_def"); ! // SPAN ! xml.startTag("span"); ! xml.writeTag("start", startTime); ! xml.writeTag("end", endTime); ! xml.closeTag(); // span ! // OPTIONS ! xml.startTag("options"); ! xml.writeTag("anti_aliasing", antiAliasing); ! xml.writeTag("arrow_color", arrowColor); ! xml.writeTag("axis_color", axisColor); ! xml.writeTag("back_color", backColor); ! if(background != null) { ! xml.writeTag("background", background); } ! xml.writeTag("base_value", baseValue); ! xml.writeTag("canvas", canvasColor); ! xml.writeTag("left_padding", chart_lpadding); ! if(normalFont != null) { ! xml.writeTag("default_font", normalFont); } ! xml.writeTag("default_font_color", normalFontColor); ! xml.writeTag("frame_color", frameColor); ! xml.writeTag("front_grid", frontGrid); ! if(gridRange != null) { ! gridRange.exportXmlTemplate(xml); } ! xml.writeTag("grid_x", gridX); ! xml.writeTag("grid_y", gridY); ! if(borderStroke != null) { ! xml.startTag("border"); ! xml.writeTag("color", borderColor); ! xml.writeTag("width", (int)borderStroke.getLineWidth()); ! xml.closeTag(); // border ! } ! xml.writeTag("major_grid_color", majorGridColor); ! xml.writeTag("major_grid_x", majorGridX); ! xml.writeTag("major_grid_y", majorGridY); ! xml.writeTag("minor_grid_color", minorGridColor); ! xml.writeTag("minor_grid_x", minorGridX); ! xml.writeTag("minor_grid_y", minorGridY); ! if(overlay != null) { ! xml.writeTag("overlay", overlay); ! } ! xml.writeTag("show_legend", showLegend); ! xml.writeTag("show_signature", drawSignature); ! if(tAxis != null) { ! tAxis.exportXmlTemplate(xml); ! } ! if(timeAxisLabel != null) { ! timeAxisLabel.exportXmlTemplate(xml); ! } ! if(title != null) { ! title.exportXmlTemplate(xml); ! } ! if(titleFont != null) { ! xml.writeTag("title_font", titleFont); ! } ! xml.writeTag("title_font_color", titleFontColor); ! if(scaleIndex != ValueFormatter.NO_SCALE) { ! xml.writeTag("units_exponent", getUnitsExponent()); ! } ! if(vAxis != null) { ! vAxis.exportXmlTemplate(xml); ! } ! if(valueAxisLabel != null) { ! xml.writeTag("vertical_label", valueAxisLabel); ! } ! xml.closeTag(); // options ! // DATASOURCES ! xml.startTag("datasources"); ! // defs Iterator fsIterator = fetchSources.values().iterator(); ! while (fsIterator.hasNext()) { ! FetchSource fs = (FetchSource) fsIterator.next(); ! fs.exportXml(xml); ! } ! // cdefs ! for (int i = 0; i < cdefList.size(); i++ ) { ! Cdef cdef = (Cdef) cdefList.elementAt(i); ! cdef.exportXml(xml); ! } ! xml.closeTag(); // datasources ! xml.startTag("graph"); for ( int i = 0; i < comments.size(); i++ ) { Comment cmt = (Comment) comments.elementAt(i); ! if ( cmt.commentType == Comment.CMT_LEGEND || cmt.commentType == Comment.CMT_NOLEGEND) { PlotDef pDef = (PlotDef) plotDefs.elementAt( ((Legend) cmt).getPlofDefIndex() ); ! pDef.exportXmlTemplate(xml, cmt.text); ! } ! else if(cmt instanceof TimeAxisLabel) { ! // NOP: already exported in the options section ! } ! else { ! cmt.exportXmlTemplate(xml); } } ! xml.closeTag(); // graph ! xml.closeTag(); // rrd_graph_def ! xml.flush(); } ! ! /** ! * Exports RrdGraphDef (graph definition) object in XML format to string. ! * Generated code can be parsed with {@link RrdGraphDefTemplate} class. ! * @return String representing graph definition in XML format ! */ ! public String exportXmlTemplate() { ! ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ! exportXmlTemplate(outputStream); ! return outputStream.toString(); ! } ! ! /** ! * Exports RrdGraphDef (graph definition) object in XML format to file. ! * Generated code can be parsed with {@link RrdGraphDefTemplate} class. ! * @param filePath destination file ! */ ! public void exportXmlTemplate(String filePath) throws IOException { ! FileOutputStream outputStream = new FileOutputStream(filePath, false); ! exportXmlTemplate(outputStream); ! outputStream.close(); ! } ! // ================================================================ // -- Protected (package) methods Index: RrdGraphDefTemplate.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/graph/RrdGraphDefTemplate.java,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** RrdGraphDefTemplate.java 26 Feb 2004 10:33:30 -0000 1.2 --- RrdGraphDefTemplate.java 1 Mar 2004 08:50:25 -0000 1.3 *************** *** 555,559 **** else if(option.equals("default_font")) { Font f = resolveFont(optionNode); ! rrdGraphDef.setTitleFont(f); } // DEFAULT FONT COLOR --- 555,559 ---- else if(option.equals("default_font")) { Font f = resolveFont(optionNode); ! rrdGraphDef.setDefaultFont(f); } // DEFAULT FONT COLOR *************** *** 754,761 **** public static void main(String[] args) throws IOException, RrdException { ! File f = new File("work/test2.xml"); ! RrdGraphDefTemplate t = new RrdGraphDefTemplate(f); ! t.setVariable("date", new Date()); ! t.getRrdGraphDef(); } } --- 754,762 ---- public static void main(String[] args) throws IOException, RrdException { ! File fileTemplate = new File("work/test2.xml"); ! RrdGraphDefTemplate template = new RrdGraphDefTemplate(fileTemplate); ! String stringTemplate = template.getRrdGraphDef().exportXmlTemplate(); ! template = new RrdGraphDefTemplate(stringTemplate); ! System.out.println(template.getRrdGraphDef().exportXmlTemplate()); } } Index: Stack.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/graph/Stack.java,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** Stack.java 15 Jan 2004 22:24:30 -0000 1.2 --- Stack.java 1 Mar 2004 08:50:25 -0000 1.3 *************** *** 28,31 **** --- 28,32 ---- import org.jrobin.core.RrdException; + import org.jrobin.core.XmlWriter; /** *************** *** 83,102 **** } ! /** ! * ! */ ! String getXml( String legend ) ! { ! StringBuffer xml = new StringBuffer(); ! ! xml.append( "\t\t<stack>\n" ); ! xml.append( "\t\t\t<datasource>" + sourceName + "</datasource>\n" ); ! if ( color != null ) ! xml.append( "\t\t\t<color r=\"" + color.getRed() + "\" g=\"" + color.getGreen() + "\" b=\"" + color.getBlue() + "\" />\n" ); ! if ( legend != null ) ! xml.append( "\t\t\t<legend>" + legend + "</legend>\n" ); ! xml.append( "\t\t</stack>\n" ); ! ! return xml.toString(); } } --- 84,93 ---- } ! void exportXmlTemplate( XmlWriter xml, String legend ) { ! xml.startTag("stack"); ! xml.writeTag("datasource", sourceName); ! xml.writeTag("color", color); ! xml.writeTag("legend", legend); ! xml.closeTag(); // stack } } Index: TimeAxisLabel.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/graph/TimeAxisLabel.java,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** TimeAxisLabel.java 15 Jan 2004 22:24:30 -0000 1.2 --- TimeAxisLabel.java 1 Mar 2004 08:50:25 -0000 1.3 *************** *** 26,29 **** --- 26,30 ---- import org.jrobin.core.RrdException; + import org.jrobin.core.XmlWriter; /** *************** *** 60,66 **** } } ! ! String getXml() { ! return ""; } } --- 61,68 ---- } } ! ! void exportXmlTemplate(XmlWriter xml) { ! xml.writeTag("time_axis_label", getText()); } + } Index: TimeAxisUnit.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/graph/TimeAxisUnit.java,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** TimeAxisUnit.java 19 Nov 2003 11:37:40 -0000 1.3 --- TimeAxisUnit.java 1 Mar 2004 08:50:25 -0000 1.4 *************** *** 22,25 **** --- 22,27 ---- package org.jrobin.graph; + import org.jrobin.core.XmlWriter; + import java.util.*; import java.text.SimpleDateFormat; *************** *** 71,82 **** /** constant for years */ public static final int YEAR = 6; ! ! private int gridTime = HOUR; // minor grid ! private int gridUnits = 1; ! private int mGridTime = HOUR; // major grid ! private int mGridUnits = 6; private boolean centerLabels = false; ! private SimpleDateFormat df = new SimpleDateFormat("HH:mm", Locale.ENGLISH ); --- 73,88 ---- /** constant for years */ public static final int YEAR = 6; ! ! private static final String[] UNIT_NAMES = { ! "SECOND", "MINUTE", "HOUR", "DAY", "WEEK", "MONTH", "YEAR" ! }; ! ! private int minGridTimeUnit = HOUR; // minor grid ! private int minGridUnitSteps = 1; ! private int majGridTimeUnit = HOUR; // major grid ! private int majGridUnitSteps = 6; private boolean centerLabels = false; ! private SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm", Locale.ENGLISH ); *************** *** 93,111 **** * WEEK, MONTH</i> and <i>YEAR</i>. * ! * @param gridTime Time unit for the minor grid lines. ! * @param gridUnits Time unit steps for the minor grid lines. ! * @param mGridTime Time unit for the major grid lines. ! * @param mGridUnits Time unit steps for the major grid lines. ! * @param df Format to use to convert the specific time into a label string. * @param centerLabels True if labels (major grid) should be centered between two major grid lines. */ ! TimeAxisUnit( int gridTime, int gridUnits, int mGridTime, int mGridUnits, SimpleDateFormat df, boolean centerLabels ) { ! this.gridTime = gridTime; ! this.gridUnits = gridUnits; ! this.mGridTime = mGridTime; ! this.mGridUnits = mGridUnits; ! this.df = new SimpleDateFormat( df.toPattern(), Locale.ENGLISH ); ! this.centerLabels = centerLabels; } --- 99,119 ---- * WEEK, MONTH</i> and <i>YEAR</i>. * ! * @param minGridTimeUnit Time unit for the minor grid lines. ! * @param minGridUnitSteps Time unit steps for the minor grid lines. ! * @param majGridTimeUnit Time unit for the major grid lines. ! * @param majGridUnitSteps Time unit steps for the major grid lines. ! * @param dateFormat Format to use to convert the specific time into a label string. * @param centerLabels True if labels (major grid) should be centered between two major grid lines. */ ! TimeAxisUnit( int minGridTimeUnit, int minGridUnitSteps, ! int majGridTimeUnit, int majGridUnitSteps, ! SimpleDateFormat dateFormat, boolean centerLabels ) { ! this.minGridTimeUnit = minGridTimeUnit; ! this.minGridUnitSteps = minGridUnitSteps; ! this.majGridTimeUnit = majGridTimeUnit; ! this.majGridUnitSteps = majGridUnitSteps; ! this.dateFormat = new SimpleDateFormat( dateFormat.toPattern(), Locale.ENGLISH ); ! this.centerLabels = centerLabels; } *************** *** 130,135 **** // Set the start calculation point for the grids ! setStartPoint(cMaj, mGridTime, start); ! setStartPoint(cMin, gridTime, start); // Find first visible grid point --- 138,143 ---- // Set the start calculation point for the grids ! setStartPoint(cMaj, majGridTimeUnit, start); ! setStartPoint(cMin, minGridTimeUnit, start); // Find first visible grid point *************** *** 138,144 **** while ( majPoint < start ) ! majPoint = getNextPoint(cMaj, mGridTime, mGridUnits); while ( minPoint < start ) ! minPoint = getNextPoint(cMin, gridTime, gridUnits); ArrayList markerList = new ArrayList(); --- 146,152 ---- while ( majPoint < start ) ! majPoint = getNextPoint(cMaj, majGridTimeUnit, majGridUnitSteps); while ( minPoint < start ) ! minPoint = getNextPoint(cMin, minGridTimeUnit, minGridUnitSteps); ArrayList markerList = new ArrayList(); *************** *** 155,170 **** { markerList.add( new TimeMarker( minPoint, "", false ) ); ! minPoint = getNextPoint( cMin, gridTime, gridUnits ); } else if ( minPoint == majPoint ) // Special case, but will happen most of the time { ! markerList.add( new TimeMarker( majPoint, df.format(cMaj.getTime()), true ) ); ! majPoint = getNextPoint( cMaj, mGridTime, mGridUnits ); ! minPoint = getNextPoint( cMin, gridTime, gridUnits ); } else { ! markerList.add( new TimeMarker( majPoint, df.format(cMaj.getTime()), true ) ); ! majPoint = getNextPoint( cMaj, mGridTime, mGridUnits ); } } --- 163,178 ---- { markerList.add( new TimeMarker( minPoint, "", false ) ); ! minPoint = getNextPoint( cMin, minGridTimeUnit, minGridUnitSteps ); } else if ( minPoint == majPoint ) // Special case, but will happen most of the time { ! markerList.add( new TimeMarker( majPoint, dateFormat.format(cMaj.getTime()), true ) ); ! majPoint = getNextPoint( cMaj, majGridTimeUnit, majGridUnitSteps ); ! minPoint = getNextPoint( cMin, minGridTimeUnit, minGridUnitSteps ); } else { ! markerList.add( new TimeMarker( majPoint, dateFormat.format(cMaj.getTime()), true ) ); ! majPoint = getNextPoint( cMaj, majGridTimeUnit, majGridUnitSteps ); } } *************** *** 173,183 **** { markerList.add( new TimeMarker( minPoint, "", false ) ); ! minPoint = getNextPoint( cMin, gridTime, gridUnits ); } while ( majPoint <= stop ) { ! markerList.add( new TimeMarker( majPoint, df.format(cMaj.getTime()), true ) ); ! majPoint = getNextPoint( cMaj, mGridTime, mGridUnits ); } --- 181,191 ---- { markerList.add( new TimeMarker( minPoint, "", false ) ); ! minPoint = getNextPoint( cMin, minGridTimeUnit, minGridUnitSteps ); } while ( majPoint <= stop ) { ! markerList.add( new TimeMarker( majPoint, dateFormat.format(cMaj.getTime()), true ) ); ! majPoint = getNextPoint( cMaj, majGridTimeUnit, majGridUnitSteps ); } *************** *** 195,208 **** long now = c.getTimeInMillis() / 1000; ! c.add( calendarUnit[mGridTime], mGridUnits ); return (c.getTimeInMillis() / 1000) - now; } ! boolean centerLabels() { return centerLabels; } ! ! // ================================================================ // -- Private methods --- 203,240 ---- long now = c.getTimeInMillis() / 1000; ! c.add( calendarUnit[majGridTimeUnit], majGridUnitSteps ); return (c.getTimeInMillis() / 1000) - now; } ! boolean getCenterLabels() { return centerLabels; } ! ! int getMinGridTimeUnit() { ! return minGridTimeUnit; ! } ! ! int getMinGridUnitSteps() { ! return minGridUnitSteps; ! } ! ! int getMajGridTimeUnit() { ! return majGridTimeUnit; ! } ! ! int getMajGridUnitSteps() { ! return majGridUnitSteps; ! } ! ! boolean isCenterLabels() { ! return centerLabels; ! } ! ! public SimpleDateFormat getDateFormat() { ! return dateFormat; ! } ! ! // ================================================================ // -- Private methods *************** *** 236,240 **** return t.getTimeInMillis(); } ! ! } --- 268,286 ---- return t.getTimeInMillis(); } ! ! static String getUnitName(int unit) { ! return UNIT_NAMES[unit]; ! } ! ! void exportXmlTemplate(XmlWriter xml) { ! xml.startTag("time_axis"); ! xml.writeTag("min_grid_time_unit", TimeAxisUnit.getUnitName(getMinGridTimeUnit())); ! xml.writeTag("min_grid_unit_steps", getMinGridUnitSteps()); ! xml.writeTag("maj_grid_time_unit", TimeAxisUnit.getUnitName(getMajGridTimeUnit())); ! xml.writeTag("maj_grid_unit_steps", getMajGridUnitSteps()); ! xml.writeTag("date_format", getDateFormat().toPattern()); ! xml.writeTag("center_labels", getCenterLabels()); ! xml.closeTag(); // time_axis ! } ! } Index: TimeGrid.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/graph/TimeGrid.java,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** TimeGrid.java 7 Nov 2003 08:23:19 -0000 1.1 --- TimeGrid.java 1 Mar 2004 08:50:25 -0000 1.2 *************** *** 85,89 **** boolean centerLabels() { ! return tAxis.centerLabels(); } --- 85,89 ---- boolean centerLabels() { ! return tAxis.getCenterLabels(); } Index: Title.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/graph/Title.java,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** Title.java 7 Nov 2003 08:23:19 -0000 1.1 --- Title.java 1 Mar 2004 08:50:25 -0000 1.2 *************** *** 26,29 **** --- 26,30 ---- import org.jrobin.core.RrdException; + import org.jrobin.core.XmlWriter; /** *************** *** 49,51 **** --- 50,56 ---- super.parseComment(); } + + void exportXmlTemplate(XmlWriter xml) { + xml.writeTag("title", getText()); + } } Index: ValueAxisUnit.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/graph/ValueAxisUnit.java,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** ValueAxisUnit.java 10 Nov 2003 08:52:27 -0000 1.2 --- ValueAxisUnit.java 1 Mar 2004 08:50:25 -0000 1.3 *************** *** 28,31 **** --- 28,33 ---- package org.jrobin.graph; + import org.jrobin.core.XmlWriter; + import java.util.*; *************** *** 40,49 **** // -- Members // ================================================================ ! private double labelStep = 2; ! private double markStep = 1; ! private int roundStep = 2; ! private double gridStep = 2; ! private double mGridStep = 10; --- 42,48 ---- // -- Members // ================================================================ ! private double gridStep = 2; ! private double labelStep = 10; *************** *** 61,68 **** { this.gridStep = gridStep; ! this.mGridStep = labelStep; } ! ! // ================================================================ // -- Protected methods --- 60,75 ---- { this.gridStep = gridStep; ! this.labelStep = labelStep; } ! ! double getGridStep() { ! return gridStep; ! } ! ! double getLabelStep() { ! return labelStep; ! } ! ! // ================================================================ // -- Protected methods *************** *** 83,93 **** if ( lower > 0 ) { while ( minPoint < lower ) minPoint += gridStep; ! while ( majPoint < lower ) majPoint += mGridStep; } else { while ( minPoint > lower ) minPoint -= gridStep; ! while ( majPoint > lower ) majPoint -= mGridStep; // Go one up to make it visible if (minPoint != lower ) minPoint += gridStep; ! if (majPoint != lower ) majPoint += mGridStep; } --- 90,100 ---- if ( lower > 0 ) { while ( minPoint < lower ) minPoint += gridStep; ! while ( majPoint < lower ) majPoint += labelStep; } else { while ( minPoint > lower ) minPoint -= gridStep; ! while ( majPoint > lower ) majPoint -= labelStep; // Go one up to make it visible if (minPoint != lower ) minPoint += gridStep; ! if (majPoint != lower ) majPoint += labelStep; } *************** *** 109,118 **** markerList.add( new ValueMarker(majPoint, true) ); minPoint = round( minPoint + gridStep ); ! majPoint = round( majPoint + mGridStep ); } else { markerList.add( new ValueMarker(majPoint, true) ); ! majPoint = round( majPoint + mGridStep ); } } --- 116,125 ---- markerList.add( new ValueMarker(majPoint, true) ); minPoint = round( minPoint + gridStep ); ! majPoint = round( majPoint + labelStep ); } else { markerList.add( new ValueMarker(majPoint, true) ); ! majPoint = round( majPoint + labelStep ); } } *************** *** 128,132 **** { markerList.add( new ValueMarker(majPoint, true) ); ! majPoint = round( majPoint + mGridStep ); } --- 135,139 ---- { markerList.add( new ValueMarker(majPoint, true) ); ! majPoint = round( majPoint + labelStep ); } *************** *** 147,151 **** double gridStep = this.gridStep; ! double mGridStep = this.mGridStep; if ( gridStep < 1.0 ) { --- 154,158 ---- double gridStep = this.gridStep; ! double mGridStep = this.labelStep; if ( gridStep < 1.0 ) { *************** *** 164,168 **** if ( roundStep == 0 ) roundStep = 1; int num = valueInt / roundStep; ! int mod = valueInt % roundStep; double gridValue = (roundStep * num) * 1.0d; if ( gridValue > value ) --- 171,175 ---- if ( roundStep == 0 ) roundStep = 1; int num = valueInt / roundStep; ! // int mod = valueInt % roundStep; double gridValue = (roundStep * num) * 1.0d; if ( gridValue > value ) *************** *** 178,182 **** if ( roundStep == 0 ) roundStep = 1; num = valueInt / roundStep; ! mod = valueInt % roundStep; double mGridValue = (roundStep * num) * 1.0d; if ( mGridValue > value ) --- 185,189 ---- if ( roundStep == 0 ) roundStep = 1; num = valueInt / roundStep; ! // mod = valueInt % roundStep; double mGridValue = (roundStep * num) * 1.0d; if ( mGridValue > value ) *************** *** 207,211 **** double gridStep = this.gridStep; ! double mGridStep = this.mGridStep; if ( gridStep < 1.0 ) { --- 214,218 ---- double gridStep = this.gridStep; ! double mGridStep = this.labelStep; if ( gridStep < 1.0 ) { *************** *** 224,228 **** if ( roundStep == 0 ) roundStep = 1; int num = valueInt / roundStep; ! int mod = valueInt % roundStep; double gridValue = (roundStep * (num + 1)) * 1.0d; if ( gridValue - value < (gridStep) / 8 ) --- 231,235 ---- if ( roundStep == 0 ) roundStep = 1; int num = valueInt / roundStep; ! // int mod = valueInt % roundStep; double gridValue = (roundStep * (num + 1)) * 1.0d; if ( gridValue - value < (gridStep) / 8 ) *************** *** 233,237 **** if ( roundStep == 0 ) roundStep = 1; num = valueInt / roundStep; ! mod = valueInt % roundStep; double mGridValue = (roundStep * (num + 1)) * 1.0d; --- 240,244 ---- if ( roundStep == 0 ) roundStep = 1; num = valueInt / roundStep; ! // mod = valueInt % roundStep; double mGridValue = (roundStep * (num + 1)) * 1.0d; *************** *** 272,274 **** --- 279,288 ---- return new java.math.BigDecimal(value).setScale(numDecs , java.math.BigDecimal.ROUND_HALF_EVEN).doubleValue(); } + + void exportXmlTemplate(XmlWriter xml) { + xml.startTag("value_axis"); + xml.writeTag("grid_step", getGridStep()); + xml.writeTag("label_step", getLabelStep()); + xml.closeTag(); // value_axis + } } |
From: <sa...@us...> - 2004-03-01 09:09:08
|
Update of /cvsroot/jrobin/src/org/jrobin/core In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv19077/org/jrobin/core Modified Files: FetchData.java RrdDb.java RrdDef.java XmlWriter.java Log Message: XML templates for RrdDef and RrdGraphDef completed. Index: FetchData.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/core/FetchData.java,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** FetchData.java 19 Feb 2004 12:23:57 -0000 1.3 --- FetchData.java 1 Mar 2004 08:50:24 -0000 1.4 *************** *** 381,385 **** writer.closeTag(); // data writer.closeTag(); // fetch_data ! writer.finish(); } --- 381,385 ---- writer.closeTag(); // data writer.closeTag(); // fetch_data ! writer.flush(); } Index: RrdDb.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/core/RrdDb.java,v retrieving revision 1.10 retrieving revision 1.11 diff -C2 -d -r1.10 -r1.11 *** RrdDb.java 19 Feb 2004 12:23:57 -0000 1.10 --- RrdDb.java 1 Mar 2004 08:50:24 -0000 1.11 *************** *** 513,517 **** } writer.closeTag(); ! writer.finish(); } --- 513,517 ---- } writer.closeTag(); ! writer.flush(); } Index: RrdDef.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/core/RrdDef.java,v retrieving revision 1.8 retrieving revision 1.9 diff -C2 -d -r1.8 -r1.9 *** RrdDef.java 26 Feb 2004 13:15:54 -0000 1.8 --- RrdDef.java 1 Mar 2004 08:50:24 -0000 1.9 *************** *** 388,392 **** } xml.closeTag(); // rrd_def ! xml.finish(); } --- 388,392 ---- } xml.closeTag(); // rrd_def ! xml.flush(); } Index: XmlWriter.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/core/XmlWriter.java,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** XmlWriter.java 26 Feb 2004 13:15:54 -0000 1.4 --- XmlWriter.java 1 Mar 2004 08:50:24 -0000 1.5 *************** *** 28,34 **** import java.io.OutputStream; import java.io.PrintWriter; import java.util.Stack; ! class XmlWriter { static final String INDENT_STR = " "; --- 28,39 ---- import java.io.OutputStream; import java.io.PrintWriter; + import java.io.File; import java.util.Stack; + import java.awt.*; ! /** ! * Extremely simple utility class used to create XML documents. ! */ ! public class XmlWriter { static final String INDENT_STR = " "; *************** *** 37,45 **** private Stack openTags = new Stack(); ! XmlWriter(OutputStream stream) { writer = new PrintWriter(stream); } ! void startTag(String tag) { writer.println(indent + "<" + tag + ">"); openTags.push(tag); --- 42,58 ---- private Stack openTags = new Stack(); ! /** ! * Creates XmlWriter with the specified output stream to send XML code to. ! * @param stream Output stream which receives XML code ! */ ! public XmlWriter(OutputStream stream) { writer = new PrintWriter(stream); } ! /** ! * Opens XML tag ! * @param tag XML tag name ! */ ! public void startTag(String tag) { writer.println(indent + "<" + tag + ">"); openTags.push(tag); *************** *** 47,51 **** } ! void closeTag() { String tag = (String) openTags.pop(); indent.setLength(indent.length() - INDENT_STR.length()); --- 60,67 ---- } ! /** ! * Closes the corresponding XML tag ! */ ! public void closeTag() { String tag = (String) openTags.pop(); indent.setLength(indent.length() - INDENT_STR.length()); *************** *** 53,59 **** } ! void writeTag(String tag, Object value) { if(value != null) { ! writer.println(indent + "<" + tag + ">" + value + "</" + tag + ">"); } else { --- 69,81 ---- } ! /** ! * Writes <tag>value</tag> to output stream ! * @param tag XML tag name ! * @param value value to be placed between <code><tag></code> and <code></tag></code> ! */ ! public void writeTag(String tag, Object value) { if(value != null) { ! writer.println(indent + "<" + tag + ">" + ! escape(value.toString()) + "</" + tag + ">"); } else { *************** *** 62,82 **** } ! void writeTag(String tag, int value) { writeTag(tag, "" + value); } ! void writeTag(String tag, long value) { writeTag(tag, "" + value); } ! void writeTag(String tag, double value, String nanString) { writeTag(tag, Util.formatDouble(value, nanString, true)); } ! void writeTag(String tag, double value) { writeTag(tag, Util.formatDouble(value, true)); } ! void finish() { writer.flush(); } --- 84,180 ---- } ! /** ! * Writes <tag>value</tag> to output stream ! * @param tag XML tag name ! * @param value value to be placed between <code><tag></code> and <code></tag></code> ! */ ! public void writeTag(String tag, int value) { writeTag(tag, "" + value); } ! /** ! * Writes <tag>value</tag> to output stream ! * @param tag XML tag name ! * @param value value to be placed between <code><tag></code> and <code></tag></code> ! */ ! public void writeTag(String tag, long value) { writeTag(tag, "" + value); } ! /** ! * Writes <tag>value</tag> to output stream ! * @param tag XML tag name ! * @param value value to be placed between <code><tag></code> and <code></tag></code> ! */ ! public void writeTag(String tag, double value, String nanString) { writeTag(tag, Util.formatDouble(value, nanString, true)); } ! /** ! * Writes <tag>value</tag> to output stream ! * @param tag XML tag name ! * @param value value to be placed between <code><tag></code> and <code></tag></code> ! */ ! public void writeTag(String tag, double value) { writeTag(tag, Util.formatDouble(value, true)); } ! /** ! * Writes <tag>value</tag> to output stream ! * @param tag XML tag name ! * @param value value to be placed between <code><tag></code> and <code></tag></code> ! */ ! public void writeTag(String tag, boolean value) { ! writeTag(tag, "" + value); ! } ! ! /** ! * Writes <tag>value</tag> to output stream ! * @param tag XML tag name ! * @param value value to be placed between <code><tag></code> and <code></tag></code> ! */ ! public void writeTag(String tag, Color value) { ! int rgb = value.getRGB() & 0xFFFFFF; ! writeTag(tag, "#" + Integer.toHexString(rgb).toUpperCase()); ! } ! ! /** ! * Writes <tag>value</tag> to output stream ! * @param tag XML tag name ! * @param value value to be placed between <code><tag></code> and <code></tag></code> ! */ ! public void writeTag(String tag, Font value) { ! startTag(tag); ! writeTag("name", value.getName()); ! int style = value.getStyle(); ! if((style & Font.BOLD) != 0 && (style & Font.ITALIC) != 0) { ! writeTag("style", "BOLDITALIC"); ! } ! else if((style & Font.BOLD) != 0) { ! writeTag("style", "BOLD"); ! } ! else if((style & Font.ITALIC) != 0) { ! writeTag("style", "ITALIC"); ! } ! else { ! writeTag("style", "PLAIN"); ! } ! writeTag("size", value.getSize()); ! closeTag(); ! } ! ! /** ! * Writes <tag>value</tag> to output stream ! * @param tag XML tag name ! * @param value value to be placed between <code><tag></code> and <code></tag></code> ! */ ! public void writeTag(String tag, File value) { ! writeTag(tag, value.getPath()); ! } ! ! /** ! * Flushes the output stream ! */ ! public void flush() { writer.flush(); } *************** *** 86,91 **** } ! void writeComment(Object comment) { ! writer.println(indent + "<!-- " + comment + " -->"); } } --- 184,201 ---- } ! /** ! * Writes XML comment to output stream ! * @param comment comment string ! */ ! public void writeComment(Object comment) { ! writer.println(indent + "<!-- " + escape(comment.toString()) + " -->"); ! } ! ! private static String escape(String s) { ! return s.replaceAll("<", "<").replaceAll(">", ">"); ! } ! ! public static void main(String[] args) { ! System.out.println(escape("<->")); } } |
From: <sa...@us...> - 2004-02-26 13:31:42
|
Update of /cvsroot/jrobin/src/org/jrobin/core In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv22676/org/jrobin/core Modified Files: RrdDef.java RrdDefTemplate.java Util.java XmlTemplate.java XmlWriter.java Log Message: exportXmlTemplate added to RrdDef class Index: RrdDef.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/core/RrdDef.java,v retrieving revision 1.7 retrieving revision 1.8 diff -C2 -d -r1.7 -r1.8 *** RrdDef.java 26 Feb 2004 10:33:29 -0000 1.7 --- RrdDef.java 26 Feb 2004 13:15:54 -0000 1.8 *************** *** 29,32 **** --- 29,33 ---- import java.util.Date; import java.util.GregorianCalendar; + import java.io.*; /** *************** *** 354,356 **** --- 355,414 ---- throw new RrdException("Could not find archive " + consolFun + "/" + steps); } + + /** + * Exports RrdDef object to output stream in XML format. Generated XML code can be parsed + * with {@link RrdDefTemplate} class. + * @param out Output stream + */ + public void exportXmlTemplate(OutputStream out) { + XmlWriter xml = new XmlWriter(out); + xml.startTag("rrd_def"); + xml.writeTag("path", getPath()); + xml.writeTag("step", getStep()); + xml.writeTag("start", getStartTime()); + // datasources + DsDef[] dsDefs = getDsDefs(); + for(int i = 0; i < dsDefs.length; i++) { + xml.startTag("datasource"); + xml.writeTag("name", dsDefs[i].getDsName()); + xml.writeTag("type", dsDefs[i].getDsType()); + xml.writeTag("heartbeat", dsDefs[i].getHeartbeat()); + xml.writeTag("min", dsDefs[i].getMinValue(), "U"); + xml.writeTag("max", dsDefs[i].getMaxValue(), "U"); + xml.closeTag(); // datasource + } + ArcDef[] arcDefs = getArcDefs(); + for(int i = 0; i < arcDefs.length; i++) { + xml.startTag("archive"); + xml.writeTag("cf", arcDefs[i].getConsolFun()); + xml.writeTag("xff", arcDefs[i].getXff()); + xml.writeTag("steps", arcDefs[i].getSteps()); + xml.writeTag("rows", arcDefs[i].getRows()); + xml.closeTag(); // archive + } + xml.closeTag(); // rrd_def + xml.finish(); + } + + /** + * Exports RrdDef object to string in XML format. Generated XML string can be parsed + * with {@link RrdDefTemplate} class. + * @return XML formatted string representing this RrdDef object + */ + public String exportXmlTemplate() { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + exportXmlTemplate(out); + return out.toString(); + } + + /** + * Exports RrdDef object to a file in XML format. Generated XML code can be parsed + * with {@link RrdDefTemplate} class. + * @param filePath Path to the file + */ + public void exportXmlTemplate(String filePath) throws IOException { + FileOutputStream out = new FileOutputStream(filePath, false); + exportXmlTemplate(out); + out.close(); + } } Index: RrdDefTemplate.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/core/RrdDefTemplate.java,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** RrdDefTemplate.java 26 Feb 2004 10:33:29 -0000 1.3 --- RrdDefTemplate.java 26 Feb 2004 13:15:54 -0000 1.4 *************** *** 228,254 **** return rrdDef; } - - /* - public static void main(String[] args) throws RrdException, IOException { - File f = new File("work/test.xml"); - RrdDefTemplate t = new RrdDefTemplate(f); - - t.setVariable("path", "work/test1.rrd"); - t.setVariable("start", new GregorianCalendar(2004, 2, 12, 12, 23, 34)); - t.setVariable("step", 310); - t.setVariable("hb", 123); - - RrdDef def = t.getRrdDef(); - System.out.println(def.dump()); - - t.setVariable("path", "work/test2.rrd"); - t.setVariable("step", 320); - t.setVariable("hb", 321); - t.setVariable("start", new GregorianCalendar()); - - RrdDef def2 = t.getRrdDef(); - System.out.println(def2.dump()); - - } - */ } --- 228,230 ---- Index: Util.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/core/Util.java,v retrieving revision 1.11 retrieving revision 1.12 diff -C2 -d -r1.11 -r1.12 *** Util.java 26 Feb 2004 10:33:29 -0000 1.11 --- Util.java 26 Feb 2004 13:15:54 -0000 1.12 *************** *** 363,367 **** static String getValue(Node node) { ! return node.getFirstChild().getNodeValue().trim(); } --- 363,375 ---- static String getValue(Node node) { ! String value = null; ! Node child = node.getFirstChild(); ! if(child != null) { ! value = child.getNodeValue(); ! if(value != null) { ! value = value.trim(); ! } ! } ! return value; } Index: XmlTemplate.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/core/XmlTemplate.java,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** XmlTemplate.java 26 Feb 2004 10:33:29 -0000 1.3 --- XmlTemplate.java 26 Feb 2004 13:15:54 -0000 1.4 *************** *** 184,188 **** private String resolveMappings(String value) { ! if(value.startsWith("${") && value.endsWith("}")) { // template variable found, remove leading "${" and trailing "}" String var = value.substring(2, value.length() - 1); --- 184,188 ---- private String resolveMappings(String value) { ! if(value != null && value.startsWith("${") && value.endsWith("}")) { // template variable found, remove leading "${" and trailing "}" String var = value.substring(2, value.length() - 1); Index: XmlWriter.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/core/XmlWriter.java,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** XmlWriter.java 13 Nov 2003 11:45:35 -0000 1.3 --- XmlWriter.java 26 Feb 2004 13:15:54 -0000 1.4 *************** *** 54,58 **** void writeTag(String tag, Object value) { ! writer.println(indent + "<" + tag + ">" + value + "</" + tag + ">"); } --- 54,63 ---- void writeTag(String tag, Object value) { ! if(value != null) { ! writer.println(indent + "<" + tag + ">" + value + "</" + tag + ">"); ! } ! else { ! writer.println(indent + "<" + tag + "></" + tag + ">"); ! } } |
From: <sa...@us...> - 2004-02-26 12:40:32
|
Update of /cvsroot/jrobin/src In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv12847 Modified Files: PlottableDemo.java Log Message: Plottable demo (final) Index: PlottableDemo.java =================================================================== RCS file: /cvsroot/jrobin/src/PlottableDemo.java,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** PlottableDemo.java 19 Feb 2004 13:05:04 -0000 1.3 --- PlottableDemo.java 26 Feb 2004 12:24:45 -0000 1.4 *************** *** 1,2 **** --- 1,3 ---- + import org.jrobin.graph.*; import org.jrobin.core.RrdException; *************** *** 6,12 **** import java.io.IOException; import java.util.Date; class PlottableDemo { ! public static void main(String[] args) throws RrdException, IOException { final long t0 = new Date().getTime() / 1000L, dt = 86400L; final int n = 10; --- 7,19 ---- import java.io.IOException; import java.util.Date; + import java.util.GregorianCalendar; class PlottableDemo { ! private PlottableDemo() throws RrdException, IOException { ! createGraph1(); ! createGraph2(); ! } ! ! private void createGraph1() throws RrdException, IOException { final long t0 = new Date().getTime() / 1000L, dt = 86400L; final int n = 10; *************** *** 14,18 **** Plottable p = new Plottable() { public double getValue(long t) { ! double x = (t - t0) / (double)(t1 - t0); return Math.exp(-x * 2) * Math.cos(x * 7 * Math.PI); } --- 21,25 ---- Plottable p = new Plottable() { public double getValue(long t) { ! double x = (t - t0) / (double) (t1 - t0); return Math.exp(-x * 2) * Math.cos(x * 7 * Math.PI); } *************** *** 21,25 **** long t[] = new long[n]; double x[] = new double[n]; ! for(int i = 0; i < n; i++) { t[i] = t0 + i * dt; x[i] = p.getValue(t[i]); --- 28,32 ---- long t[] = new long[n]; double x[] = new double[n]; ! for (int i = 0; i < n; i++) { t[i] = t0 + i * dt; x[i] = p.getValue(t[i]); *************** *** 40,46 **** gdef.setTimeAxis(TimeAxisUnit.DAY, 1, TimeAxisUnit.DAY, 1, "dd", true); RrdGraph g = new RrdGraph(gdef); ! String filename = Util.getJRobinDemoPath("plottable.png"); g.saveAsPNG(filename, 400, 200); ! System.out.println("Graph saved to " + filename); } } --- 47,88 ---- gdef.setTimeAxis(TimeAxisUnit.DAY, 1, TimeAxisUnit.DAY, 1, "dd", true); RrdGraph g = new RrdGraph(gdef); ! String filename = Util.getJRobinDemoPath("plottable1.png"); g.saveAsPNG(filename, 400, 200); ! System.out.println("Graph1 saved to " + filename); ! } ! ! private void createGraph2() throws RrdException, IOException { ! GregorianCalendar[] timestamps = { ! new GregorianCalendar(2004, 2, 1, 0, 0, 0), ! new GregorianCalendar(2004, 2, 1, 2, 0, 0), ! new GregorianCalendar(2004, 2, 1, 7, 0, 0), ! new GregorianCalendar(2004, 2, 1, 14, 0, 0), ! new GregorianCalendar(2004, 2, 1, 17, 0, 0), ! new GregorianCalendar(2004, 2, 1, 19, 0, 0), ! new GregorianCalendar(2004, 2, 1, 23, 0, 0), ! new GregorianCalendar(2004, 2, 1, 24, 0, 0) ! }; ! double[] values = {100, 250, 230, 370, 350, 300, 340, 350}; ! LinearInterpolator linear = new LinearInterpolator(timestamps, values); ! linear.setInterpolationMethod(LinearInterpolator.INTERPOLATE_LEFT); ! CubicSplineInterpolator spline = new CubicSplineInterpolator(timestamps, values); ! RrdGraphDef gDef = new RrdGraphDef(timestamps[0], timestamps[timestamps.length - 1]); ! gDef.setTitle("Plottable demonstration"); ! gDef.setTimeAxisLabel("time"); ! gDef.setVerticalLabel("water level [inches]"); ! gDef.datasource("linear", linear); ! gDef.datasource("spline", spline); ! gDef.area("spline", Color.ORANGE, "Spline interpolation"); ! gDef.line("linear", Color.RED, "Linear inteprolation@r", 2); ! gDef.gprint("spline", "AVERAGE", "Average spline value: @0 inches@r"); ! gDef.gprint("linear", "AVERAGE", "Average linear value: @0 inches@r"); ! RrdGraph graph = new RrdGraph(gDef); ! String filename = Util.getJRobinDemoPath("plottable2.png"); ! graph.saveAsPNG(filename, 300, 100); ! System.out.println("Graph2 saved to " + filename); ! } ! ! public static void main(String[] args) throws RrdException, IOException { ! new PlottableDemo(); } } |
From: <sa...@us...> - 2004-02-26 12:29:50
|
Update of /cvsroot/jrobin/src In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv10786 Modified Files: Demo.java Added Files: TemplatesDemo.java Log Message: XML templates demo --- NEW FILE: TemplatesDemo.java --- /* ============================================================ * JRobin : Pure java implementation of RRDTool's functionality * ============================================================ * * Project Info: http://www.jrobin.org * Project Lead: Sasa Markovic (sa...@jr...); * * (C) Copyright 2003, by Sasa Markovic. * * This library is free software; you can redistribute it and/or modify it under the terms * of the GNU Lesser General Public License as published by the Free Software Foundation; * either version 2.1 of the License, or (at your option) any later version. * * Developers: Sasa Markovic (sa...@jr...) * Arne Vandamme (cob...@jr...) * * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with this * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, * Boston, MA 02111-1307, USA. */ import org.jrobin.core.*; import org.jrobin.graph.RrdGraph; import org.jrobin.graph.RrdGraphDef; import org.jrobin.graph.RrdGraphDefTemplate; import java.io.BufferedOutputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintWriter; import java.util.Random; class TemplatesDemo { static final String RRD_TEMPLATE = "<rrd_def> " + " <path>${path}</path> " + " <start>${start}</start> " + " <step>300</step> " + " <datasource> " + " <name>sun</name> " + " <type>GAUGE</type> " + " <heartbeat>600</heartbeat> " + " <min>0</min> " + " <max>U</max> " + " </datasource> " + " <datasource> " + " <name>shade</name> " + " <type>GAUGE</type> " + " <heartbeat>600</heartbeat> " + " <min>0</min> " + " <max>U</max> " + " </datasource> " + " <archive> " + " <cf>AVERAGE</cf> " + " <xff>0.5</xff> " + " <steps>1</steps> " + " <rows>600</rows> " + " </archive> " + " <archive> " + " <cf>AVERAGE</cf> " + " <xff>0.5</xff> " + " <steps>6</steps> " + " <rows>700</rows> " + " </archive> " + " <archive> " + " <cf>AVERAGE</cf> " + " <xff>0.5</xff> " + " <steps>24</steps> " + " <rows>775</rows> " + " </archive> " + " <archive> " + " <cf>AVERAGE</cf> " + " <xff>0.5</xff> " + " <steps>288</steps> " + " <rows>797</rows> " + " </archive> " + " <archive> " + " <cf>MAX</cf> " + " <xff>0.5</xff> " + " <steps>1</steps> " + " <rows>600</rows> " + " </archive> " + " <archive> " + " <cf>MAX</cf> " + " <xff>0.5</xff> " + " <steps>6</steps> " + " <rows>700</rows> " + " </archive> " + " <archive> " + " <cf>MAX</cf> " + " <xff>0.5</xff> " + " <steps>24</steps> " + " <rows>775</rows> " + " </archive> " + " <archive> " + " <cf>MAX</cf> " + " <xff>0.5</xff> " + " <steps>288</steps> " + " <rows>797</rows> " + " </archive> " + "</rrd_def> " ; static final String GRAPH_TEMPLATE = "<rrd_graph_def> " + " <span> " + " <start>${start}</start> " + " <end>${end}</end> " + " </span> " + " <options> " + " <title>${title}</title> " + " <vertical_label>temperature</vertical_label> " + " </options> " + " <datasources> " + " <def> " + " <name>sun</name> " + " <rrd>${rrd}</rrd> " + " <source>sun</source> " + " <cf>AVERAGE</cf> " + " </def> " + " <def> " + " <name>shade</name> " + " <rrd>${rrd}</rrd> " + " <source>shade</source> " + " <cf>AVERAGE</cf> " + " </def> " + " <def> " + " <name>median</name> " + " <rpn>sun,shade,+,2,/</rpn> " + " </def> " + " <def> " + " <name>diff</name> " + " <rpn>sun,shade,-,ABS,-1,*</rpn> " + " </def> " + " <def> " + " <name>sine</name> " + " <rpn>${sine}</rpn> " + " </def> " + " </datasources> " + " <graph> " + " <line> " + " <datasource>sun</datasource> " + " <color>#00FF00</color> " + " <legend>sun temp</legend> " + " </line> " + " <line> " + " <datasource>shade</datasource> " + " <color>#0000FF</color> " + " <legend>shade temp</legend> " + " </line> " + " <line> " + " <datasource>median</datasource> " + " <color>#FF00FF</color> " + " <legend>median value@L</legend> " + " </line> " + " <area> " + " <datasource>diff</datasource> " + " <color>#FFFF00</color> " + " <legend>difference@r</legend> " + " </area> " + " <line> " + " <datasource>diff</datasource> " + " <color>#FF0000</color> " + " <legend/> " + " </line> " + " <line> " + " <datasource>sine</datasource> " + " <color>#00FFFF</color> " + " <legend>sine function demo@L</legend> " + " </line> " + " <gprint> " + " <datasource>sun</datasource> " + " <cf>MAX</cf> " + " <format>maxSun = @3@s</format> " + " </gprint> " + " <gprint> " + " <datasource>sun</datasource> " + " <cf>AVERAGE</cf> " + " <format>avgSun = @3@S@r</format> " + " </gprint> " + " <gprint> " + " <datasource>shade</datasource> " + " <cf>MAX</cf> " + " <format>maxShade = @3@S</format> " + " </gprint> " + " <gprint> " + " <datasource>shade</datasource> " + " <cf>AVERAGE</cf> " + " <format>avgShade = @3@S@r</format> " + " </gprint> " + " </graph> " + "</rrd_graph_def> " ; static final long SEED = 1909752002L; static final Random RANDOM = new Random(SEED); static final String FILE = "templates_demo"; static final long START = Util.getTimestamp(2003, 4, 1); static final long END = Util.getTimestamp(2003, 5, 1); static final int MAX_STEP = 300; public static void main(String[] args) throws RrdException, IOException { // setup println("== Starting demo"); RrdDb.setLockMode(RrdDb.NO_LOCKS); long startMillis = System.currentTimeMillis(); long start = START; long end = END; String rrdPath = Util.getJRobinDemoPath(FILE + ".rrd"); String xmlPath = Util.getJRobinDemoPath(FILE + ".xml"); String rrdRestoredPath = Util.getJRobinDemoPath(FILE + "_restored.rrd"); String pngPath = Util.getJRobinDemoPath(FILE + ".png"); String jpegPath = Util.getJRobinDemoPath(FILE + ".jpeg"); String gifPath = Util.getJRobinDemoPath(FILE + ".gif"); String logPath = Util.getJRobinDemoPath(FILE + ".log"); PrintWriter log = new PrintWriter( new BufferedOutputStream(new FileOutputStream(logPath, false)) ); // creation from the template println("== Creating RRD file " + rrdPath); RrdDefTemplate defTemplate = new RrdDefTemplate(RRD_TEMPLATE); defTemplate.setVariable("path", rrdPath); defTemplate.setVariable("start", start - 1); RrdDef rrdDef = defTemplate.getRrdDef(); println(rrdDef.dump()); log.println(rrdDef.dump()); RrdDb rrdDb = new RrdDb(rrdDef); rrdDb.close(); println("== RRD file created and closed."); // update database GaugeSource sunSource = new GaugeSource(1200, 20); GaugeSource shadeSource = new GaugeSource(300, 10); println("== Simulating one month of RRD file updates with step not larger than " + MAX_STEP + " seconds (* denotes 1000 updates)"); long t = start; int n = 0; rrdDb = new RrdDb(rrdPath); Sample sample = rrdDb.createSample(); while(t <= end + 86400L) { sample.setTime(t); sample.setValue("sun", sunSource.getValue()); sample.setValue("shade", shadeSource.getValue()); log.println(sample.dump()); sample.update(); t += RANDOM.nextDouble() * MAX_STEP + 1; if(((++n) % 1000) == 0) { System.out.print("*"); }; } System.out.println(""); println("== Finished. RRD file updated " + n + " times"); println("== Last update time was: " + rrdDb.getLastUpdateTime()); // fetch data println("== Fetching data for the whole month"); FetchRequest request = rrdDb.createFetchRequest("AVERAGE", start, end); println(request.dump()); log.println(request.dump()); FetchData fetchData = request.fetchData(); println("== Data fetched. " + fetchData.getRowCount() + " points obtained"); for(int i = 0; i < fetchData.getRowCount(); i++) { println(fetchData.getRow(i).dump()); } println("== Dumping fetch data to XML format"); println(fetchData.exportXml()); println("== Fetch completed"); // dump to XML file println("== Dumping RRD file to XML file " + xmlPath + " (can be restored with RRDTool)"); rrdDb.exportXml(xmlPath); println("== Creating RRD file " + rrdRestoredPath + " from XML file " + xmlPath); RrdDb rrdRestoredDb = new RrdDb(rrdRestoredPath, xmlPath); // close files println("== Closing both RRD files"); rrdDb.close(); rrdRestoredDb.close(); // create graph println("== Creating graph from the second file"); RrdGraphDefTemplate graphTemplate = new RrdGraphDefTemplate(GRAPH_TEMPLATE); graphTemplate.setVariable("start", start); graphTemplate.setVariable("end", end); graphTemplate.setVariable("title", "Temperatures in May 2003"); graphTemplate.setVariable("rrd", rrdRestoredPath); // RPN expressions can be created at runtime and put into a template graphTemplate.setVariable("sine", "TIME," + start + ",-," + (end - start) + ",/,2,PI,*,*,SIN,1000,*"); // create graph finally RrdGraphDef gDef = graphTemplate.getRrdGraphDef(); RrdGraph graph = new RrdGraph(gDef); println("== Graph created"); println("== Saving graph as PNG file " + pngPath); graph.saveAsPNG(pngPath, 400, 250); println("== Saving graph as JPEG file " + jpegPath); graph.saveAsJPEG(jpegPath, 400, 250, 0.5F); println("== Saving graph as GIF file " + gifPath); graph.saveAsGIF(gifPath, 400, 250); // demo ends log.close(); println("== Demo completed in " + ((System.currentTimeMillis() - startMillis) / 1000.0) + " sec"); } static void println(String msg) { System.out.println(msg); } static class GaugeSource { private double value; private double step; GaugeSource(double value, double step) { this.value = value; this.step = step; } long getValue() { double oldValue = value; double increment = RANDOM.nextDouble() * step; if (RANDOM.nextDouble() > 0.5) { increment *= -1; } value += increment; if (value <= 0) { value = 0; } return Math.round(oldValue); } } } Index: Demo.java =================================================================== RCS file: /cvsroot/jrobin/src/Demo.java,v retrieving revision 1.10 retrieving revision 1.11 diff -C2 -d -r1.10 -r1.11 *** Demo.java 19 Feb 2004 13:05:04 -0000 1.10 --- Demo.java 26 Feb 2004 12:14:06 -0000 1.11 *************** *** 174,201 **** System.out.println(msg); } - } - - class GaugeSource { - private double value; - private double step; ! GaugeSource(double value, double step) { ! this.value = value; ! this.step = step; ! } ! long getValue() { ! double oldValue = value; ! double increment = Demo.RANDOM.nextDouble() * step; ! if(Demo.RANDOM.nextDouble() > 0.5) { ! increment *= -1; } ! value += increment; ! if(value <= 0) { ! value = 0; } - return Math.round(oldValue); } } --- 174,203 ---- System.out.println(msg); } ! static class GaugeSource { ! private double value; ! private double step; ! GaugeSource(double value, double step) { ! this.value = value; ! this.step = step; } ! ! long getValue() { ! double oldValue = value; ! double increment = RANDOM.nextDouble() * step; ! if(RANDOM.nextDouble() > 0.5) { ! increment *= -1; ! } ! value += increment; ! if(value <= 0) { ! value = 0; ! } ! return Math.round(oldValue); } } } + + |
From: <sa...@us...> - 2004-02-26 10:49:11
|
Update of /cvsroot/jrobin/src/org/jrobin/core In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv24419/org/jrobin/core Modified Files: RrdDef.java RrdDefTemplate.java Util.java XmlTemplate.java Log Message: XML templates (finished) Index: RrdDef.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/core/RrdDef.java,v retrieving revision 1.6 retrieving revision 1.7 diff -C2 -d -r1.6 -r1.7 *** RrdDef.java 8 Dec 2003 13:47:40 -0000 1.6 --- RrdDef.java 26 Feb 2004 10:33:29 -0000 1.7 *************** *** 27,30 **** --- 27,32 ---- import java.util.ArrayList; + import java.util.Date; + import java.util.GregorianCalendar; /** *************** *** 141,146 **** /** ! * Sets RRD starting timestamp. ! * @param startTime RRD starting timestamp. */ public void setStartTime(long startTime) { --- 143,148 ---- /** ! * Sets RRD's starting timestamp. ! * @param startTime starting timestamp. */ public void setStartTime(long startTime) { *************** *** 149,153 **** /** ! * Sets RRD time step. * @param step RRD time step. */ --- 151,171 ---- /** ! * Sets RRD's starting timestamp. ! * @param date starting date ! */ ! public void setStartTime(Date date) { ! this.startTime = Util.getTimestamp(date); ! } ! ! /** ! * Sets RRD's starting timestamp. ! * @param gc starting date ! */ ! public void setStartTime(GregorianCalendar gc) { ! this.startTime = Util.getTimestamp(gc); ! } ! ! /** ! * Sets RRD's time step. * @param step RRD time step. */ Index: RrdDefTemplate.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/core/RrdDefTemplate.java,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** RrdDefTemplate.java 25 Feb 2004 15:28:05 -0000 1.2 --- RrdDefTemplate.java 26 Feb 2004 10:33:29 -0000 1.3 *************** *** 30,48 **** import java.io.IOException; import java.io.File; /** ! * Class to represent RrdDef XML template. Use this class to produce similar RRD definitions ! * (RrdDef objects) from the same XML template. Use <code>${placeholder_name}</code> placeholders ! * in the XML source to mark XML code which will be modified (replaced) at run time.<p> ! * ! * Here is a self-explaining example of a valid XML definition:<p> * ! * <pre><code> * <rrd_def> ! * <path>${path}</path> * <!-- not mandatory --> * <start>1000123456</start> * <!-- not mandatory --> ! * <step>${step}</step> * <!-- at least one datasource must be supplied --> * <datasource> --- 30,49 ---- import java.io.IOException; import java.io.File; + import java.util.GregorianCalendar; /** ! * Class used to create an arbitrary number of RrdDef (RRD file definition) objects ! * from a single XML template. XML template can be supplied as an XML InputSource, ! * XML file or XML formatted string.<p> * ! * Here is an example of a properly formatted XML template with all available options in it ! * (unwanted options can be removed):<p> ! * <pre> * <rrd_def> ! * <path>test.rrd</path> * <!-- not mandatory --> * <start>1000123456</start> * <!-- not mandatory --> ! * <step>300</step> * <!-- at least one datasource must be supplied --> * <datasource> *************** *** 65,69 **** * <xff>0.5</xff> * <steps>1</steps> ! * <rows>${rows}</rows> * </archive> * <archive> --- 66,70 ---- * <xff>0.5</xff> * <steps>1</steps> ! * <rows>600</rows> * </archive> * <archive> *************** *** 74,123 **** * </archive> * </rrd_def> ! * </code></pre> ! * XML template can be embedded in a String or a file - the class provides constructors in both ! * cases. <p> ! * ! * Note that the above XML definition contains three placeholders (<code>${path}</code>, ! * <code>${step}</code> and <code>${rows}</code>) - these placeholders must be replaced with ! * real values before the RrdDef object is requested by calling {@link #getRrdDef getRrdDef()} ! * method. To replace placeholders with real values at run time use inhereted ! * (and overloaded) public {@link XmlTemplate#setMapping(String, String) setMapping()} ! * methods.<p> ! * ! * You are free to use the same template object to create as many RrdDef objects as needed ! * (probably with different placeholder-value mappings).<p> ! * ! * Here is an example how to create two different RRD files using the template given above:<p> * * <pre> - * // 'template.xml' file contains XML template already specified - * File file = new File("template.xml"); - * RrdDefTemplate t = new RrdDefTemplate(file); - * - * // replace ${path} placeholder with the real value (test1.rrd) - * t.setMapping("path", "test1.rrd"); - * - * // replace ${step} placeholder with the real value (600) - * t.setMapping("step", 600); - * - * // replace ${rows} placeholder with the real value (800) - * t.setMapping("rows", 800); - * - * // get RrdDef from the template object... * RrdDef def = t.getRrdDef(); ! * ! * // ...and use it to construct the first RRD file ! * RrdDb rrd = new RrdDb(def); rrd.close(); ! * ! * // note that all mappings are still active ! * // change the value for some (or all) placeholders ! * // to construct the second database ! * // with different parameters ! * t.setMapping("path", "test2.rrd"); ! * def = t.getRrdDef(); ! * ! * // the second RRD file will be also created with step=600, rows=800 ! * rrd = new RrdDb(def); rrd.close(); * </pre> */ public class RrdDefTemplate extends XmlTemplate { --- 75,131 ---- * </archive> * </rrd_def> ! * </pre> ! * Notes on the template syntax:<p> ! * <ul> ! * <li>There is a strong relation between the XML template syntax and the syntax of ! * {@link RrdDef} class methods. If you are not sure what some XML tag means, check javadoc ! * for the corresponding class. ! * <li>starting timestamp can be supplied either as a long integer ! * (like: 1000243567) or as an ISO formatted string (like: 2004-02-21 12:25:45) ! * <li>whitespaces are not harmful ! * <li>floating point values: anything that cannot be parsed will be treated as Double.NaN ! * (like: U, unknown, 12r.23) ! * <li>comments are allowed. ! * </ul> ! * Any template value (text between <code><some_tag></code> and ! * <code></some_tag></code>) can be replaced with ! * a variable of the following form: <code>${variable_name}</code>. Use ! * {@link XmlTemplate#setVariable(String, String) setVariable()} ! * methods from the base class to replace template variables with real values ! * at runtime.<p> * + * Typical usage scenario:<p> + * <ul> + * <li>Create your XML template and save it to a file (template.xml, for example) + * <li>Replace hardcoded template values with variables if you want to change them during runtime. + * For example, file path should not be hardcoded in the template - you probably want to create + * many different RRD files from the same XML template. For example, your XML + * template could start with: + * <pre> + * <rrd_def> + * <path>${path}</path> + * <step>300</step> + * ... + * </pre> + * <li>In your Java code, create RrdDefTemplate object using your XML template file: + * <pre> + * RrdDefTemplate t = new RrdDefTemplate(new File(template.xml)); + * </pre> + * <li>Then, specify real values for template variables: + * <pre> + * t.setVariable("path", "demo/test.rrd"); + * </pre> + * <li>Once all template variables are set, just use the template object to create RrdDef + * object. This object is actually used to create JRobin RRD files: * <pre> * RrdDef def = t.getRrdDef(); ! * RrdDb rrd = new RrdDb(def); ! * rrd.close(); * </pre> + * </ul> + * You should create new RrdDefTemplate object only once for each XML template. Single template + * object can be reused to create as many RrdDef objects as needed, with different values + * specified for template variables. XML synatax check is performed only once - the first + * definition object gets created relatively slowly, but it will be created much faster next time. */ public class RrdDefTemplate extends XmlTemplate { *************** *** 159,163 **** * is called, values for all non-optional placeholders must be supplied. To specify * placeholder values at runtime, use some of the overloaded ! * {@link XmlTemplate#setMapping(String, String) setMapping()} methods. Once this method * returns, all placeholder values are preserved. To remove them all, call inhereted * {@link XmlTemplate#clearValues() clearValues()} method explicitly.<p> --- 167,171 ---- * is called, values for all non-optional placeholders must be supplied. To specify * placeholder values at runtime, use some of the overloaded ! * {@link XmlTemplate#setVariable(String, String) setVariable()} methods. Once this method * returns, all placeholder values are preserved. To remove them all, call inhereted * {@link XmlTemplate#clearValues() clearValues()} method explicitly.<p> *************** *** 167,171 **** * of the new RrdDb object. * @throws RrdException Thrown (in most cases) if the value for some placeholder ! * was not supplied through {@link XmlTemplate#setMapping(String, String) setMapping()} * method call */ --- 175,179 ---- * of the new RrdDb object. * @throws RrdException Thrown (in most cases) if the value for some placeholder ! * was not supplied through {@link XmlTemplate#setVariable(String, String) setVariable()} * method call */ *************** *** 174,183 **** throw new RrdException("XML definition must start with <rrd_def>"); } // PATH must be supplied or exception is thrown String path = getChildValue(root, "path"); RrdDef rrdDef = new RrdDef(path); try { ! long start = getChildValueAsLong(root, "start"); ! rrdDef.setStartTime(start); } catch (RrdException e) { // START is not mandatory --- 182,195 ---- throw new RrdException("XML definition must start with <rrd_def>"); } + validateTagsOnlyOnce(root, new String[] { + "path", "start", "step", "datasource*", "archive*" + }); // PATH must be supplied or exception is thrown String path = getChildValue(root, "path"); RrdDef rrdDef = new RrdDef(path); try { ! String startStr = getChildValue(root, "start"); ! GregorianCalendar startGc = Util.getGregorianCalendar(startStr); ! rrdDef.setStartTime(startGc); } catch (RrdException e) { // START is not mandatory *************** *** 192,195 **** --- 204,210 ---- Node[] dsNodes = getChildNodes(root, "datasource"); for (int i = 0; i < dsNodes.length; i++) { + validateTagsOnlyOnce(dsNodes[i], new String[] { + "name", "type", "heartbeat", "min", "max" + }); String name = getChildValue(dsNodes[i], "name"); String type = getChildValue(dsNodes[i], "type"); *************** *** 202,205 **** --- 217,223 ---- Node[] arcNodes = getChildNodes(root, "archive"); for (int i = 0; i < arcNodes.length; i++) { + validateTagsOnlyOnce(arcNodes[i], new String[] { + "cf", "xff", "steps", "rows" + }); String consolFun = getChildValue(arcNodes[i], "cf"); double xff = getChildValueAsDouble(arcNodes[i], "xff"); *************** *** 211,226 **** } ! public static void main(String[] args) throws RrdException, IOException { File f = new File("work/test.xml"); RrdDefTemplate t = new RrdDefTemplate(f); ! t.setMapping("path", "test1.rrd"); ! t.setMapping("step", 310); ! t.setMapping("hb", 123); RrdDef def = t.getRrdDef(); System.out.println(def.dump()); - } } --- 229,254 ---- } ! /* public static void main(String[] args) throws RrdException, IOException { File f = new File("work/test.xml"); RrdDefTemplate t = new RrdDefTemplate(f); ! t.setVariable("path", "work/test1.rrd"); ! t.setVariable("start", new GregorianCalendar(2004, 2, 12, 12, 23, 34)); ! t.setVariable("step", 310); ! t.setVariable("hb", 123); RrdDef def = t.getRrdDef(); System.out.println(def.dump()); + t.setVariable("path", "work/test2.rrd"); + t.setVariable("step", 320); + t.setVariable("hb", 321); + t.setVariable("start", new GregorianCalendar()); + + RrdDef def2 = t.getRrdDef(); + System.out.println(def2.dump()); + + } + */ } Index: Util.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/core/Util.java,v retrieving revision 1.10 retrieving revision 1.11 diff -C2 -d -r1.10 -r1.11 *** Util.java 25 Feb 2004 15:28:05 -0000 1.10 --- Util.java 26 Feb 2004 10:33:29 -0000 1.11 *************** *** 38,41 **** --- 38,43 ---- import java.text.DecimalFormat; import java.text.NumberFormat; + import java.text.SimpleDateFormat; + import java.text.ParseException; import java.util.Date; import java.util.Locale; *************** *** 43,47 **** import java.util.ArrayList; import java.io.*; - import java.awt.*; /** --- 45,48 ---- *************** *** 166,169 **** --- 167,171 ---- */ public static long getTimestamp(Date date) { + // round to whole seconds, ignore milliseconds return (date.getTime() + 499L) / 1000L; } *************** *** 288,291 **** --- 290,321 ---- } + static final String ISO_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss"; // ISO + + /** + * Creates GregorianCalendar object from a string. The string should represent + * either a long integer (UNIX timestamp in seconds without milliseconds, + * like "1002354657") or a human readable date string in the format "yyyy-MM-dd HH:mm:ss" + * (like "2004-02-25 12:23:45"). + * @param timeStr Input string + * @return GregorianCalendar object + */ + public static GregorianCalendar getGregorianCalendar(String timeStr) { + // try to parse it as long + try { + long timestamp = Long.parseLong(timeStr); + return Util.getGregorianCalendar(timestamp); + } catch (NumberFormatException e) { } + // not a long timestamp, try to parse it as data + SimpleDateFormat df = new SimpleDateFormat(ISO_DATE_FORMAT); + df.setLenient(false); + try { + Date date = df.parse(timeStr); + return Util.getGregorianCalendar(date); + } catch (ParseException e) { + throw new IllegalArgumentException("Time/date not in " + ISO_DATE_FORMAT + + " format: " + timeStr); + } + } + /** * Various DOM utility functions Index: XmlTemplate.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/core/XmlTemplate.java,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** XmlTemplate.java 25 Feb 2004 15:28:05 -0000 1.2 --- XmlTemplate.java 26 Feb 2004 10:33:29 -0000 1.3 *************** *** 76,80 **** * @param value value to be set in the XML template */ ! public void setMapping(String name, String value) { valueMap.put(name, value); } --- 76,80 ---- * @param value value to be set in the XML template */ ! public void setVariable(String name, String value) { valueMap.put(name, value); } *************** *** 87,91 **** * @param value value to be set in the XML template */ ! public void setMapping(String name, int value) { valueMap.put(name, new Integer(value)); } --- 87,91 ---- * @param value value to be set in the XML template */ ! public void setVariable(String name, int value) { valueMap.put(name, new Integer(value)); } *************** *** 98,102 **** * @param value value to be set in the XML template */ ! public void setMapping(String name, long value) { valueMap.put(name, new Long(value)); } --- 98,102 ---- * @param value value to be set in the XML template */ ! public void setVariable(String name, long value) { valueMap.put(name, new Long(value)); } *************** *** 109,113 **** * @param value value to be set in the XML template */ ! public void setMapping(String name, double value) { valueMap.put(name, new Double(value)); } --- 109,113 ---- * @param value value to be set in the XML template */ ! public void setVariable(String name, double value) { valueMap.put(name, new Double(value)); } *************** *** 120,124 **** * @param value value to be set in the XML template */ ! public void setMapping(String name, Color value) { valueMap.put(name, "#" + Integer.toHexString(value.getRGB() & 0xFFFFFF)); } --- 120,124 ---- * @param value value to be set in the XML template */ ! public void setVariable(String name, Color value) { valueMap.put(name, "#" + Integer.toHexString(value.getRGB() & 0xFFFFFF)); } *************** *** 131,136 **** * @param value value to be set in the XML template */ ! public void setMapping(String name, Date value) { ! setMapping(name, Util.getTimestamp(value)); } --- 131,136 ---- * @param value value to be set in the XML template */ ! public void setVariable(String name, Date value) { ! setVariable(name, Util.getTimestamp(value)); } *************** *** 142,147 **** * @param value value to be set in the XML template */ ! public void setMapping(String name, GregorianCalendar value) { ! setMapping(name, Util.getTimestamp(value)); } --- 142,147 ---- * @param value value to be set in the XML template */ ! public void setVariable(String name, GregorianCalendar value) { ! setVariable(name, Util.getTimestamp(value)); } *************** *** 153,157 **** * @param value value to be set in the XML template */ ! public void setMapping(String name, boolean value) { valueMap.put(name, "" + value); } --- 153,157 ---- * @param value value to be set in the XML template */ ! public void setVariable(String name, boolean value) { valueMap.put(name, "" + value); } *************** *** 193,197 **** else { // no mapping found - this is illegal ! throw new IllegalArgumentException("No mapping found for template variable " + value); } } --- 193,198 ---- else { // no mapping found - this is illegal ! throw new IllegalArgumentException( ! "No mapping found for template variable " + value); } } *************** *** 245,252 **** } ! protected void validateOnce(Node parentNode, String[] allowedChildNames) throws RrdException { // validate node only once if(validatedNodes.contains(parentNode)) { - //System.out.println("Already validated"); return; } --- 246,252 ---- } ! protected void validateTagsOnlyOnce(Node parentNode, String[] allowedChildNames) throws RrdException { // validate node only once if(validatedNodes.contains(parentNode)) { return; } *************** *** 256,260 **** String childName = childs[i].getNodeName(); for(int j = 0; j < allowedChildNames.length; j++) { ! if(childName.equals(allowedChildNames[j])) { continue main; } --- 256,266 ---- String childName = childs[i].getNodeName(); for(int j = 0; j < allowedChildNames.length; j++) { ! if(allowedChildNames[j].equals(childName)) { ! // only one such tag is allowed ! allowedChildNames[j] = "<--removed-->"; ! continue main; ! } ! else if(allowedChildNames[j].equals(childName + "*")) { ! // several tags allowed continue main; } *************** *** 264,267 **** --- 270,274 ---- } } + // everything is OK validatedNodes.add(parentNode); } |
From: <sa...@us...> - 2004-02-26 10:49:11
|
Update of /cvsroot/jrobin/src/org/jrobin/graph In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv24419/org/jrobin/graph Modified Files: RrdGraphDef.java RrdGraphDefTemplate.java Removed Files: XmlGraphDefConvertor.java Log Message: XML templates (finished) Index: RrdGraphDef.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/graph/RrdGraphDef.java,v retrieving revision 1.6 retrieving revision 1.7 diff -C2 -d -r1.6 -r1.7 *** RrdGraphDef.java 25 Feb 2004 15:28:06 -0000 1.6 --- RrdGraphDef.java 26 Feb 2004 10:33:30 -0000 1.7 *************** *** 131,139 **** } - public RrdGraphDef( String jrobinXml ) throws RrdException - { - new XmlGraphDefConvertor( jrobinXml, this ); - } - /** * Constructs a new JRobin graph object, with a specified time span to be presented on the graph. --- 131,134 ---- *************** *** 905,912 **** } ! /** ! * ! * @return ! */ public String getJRobinXml() { --- 900,904 ---- } ! /* public String getJRobinXml() { *************** *** 1011,1015 **** return xml.toString(); } ! // ================================================================ // -- Protected (package) methods --- 1003,1007 ---- return xml.toString(); } ! */ // ================================================================ // -- Protected (package) methods Index: RrdGraphDefTemplate.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/graph/RrdGraphDefTemplate.java,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** RrdGraphDefTemplate.java 25 Feb 2004 15:28:06 -0000 1.1 --- RrdGraphDefTemplate.java 26 Feb 2004 10:33:30 -0000 1.2 *************** *** 36,44 **** import java.util.GregorianCalendar; import java.util.Date; - import java.text.SimpleDateFormat; - import java.text.ParseException; /** ! * Class used to create an arbitrary number of RrdGraphDefs (graph definition) objects * from a single XML template. XML template can be supplied as an XML InputSource, * XML file or XML formatted string.<p> --- 36,42 ---- import java.util.GregorianCalendar; import java.util.Date; /** ! * Class used to create an arbitrary number of RrdGraphDef (graph definition) objects * from a single XML template. XML template can be supplied as an XML InputSource, * XML file or XML formatted string.<p> *************** *** 214,218 **** * <li>hard-coded timestamps in templates should be long integeres * (like: 1000243567) or ISO formatted strings (like: 2004-02-21 12:25:45) ! * <li>all leading and trailing whitespaces are removed * <li>use <code>true</code>, <code>on</code>, <code>yes</code>, <code>y</code>, * or <code>1</code> to specify boolean <code>true</code> value (anything else will --- 212,216 ---- * <li>hard-coded timestamps in templates should be long integeres * (like: 1000243567) or ISO formatted strings (like: 2004-02-21 12:25:45) ! * <li>whitespaces are not harmful * <li>use <code>true</code>, <code>on</code>, <code>yes</code>, <code>y</code>, * or <code>1</code> to specify boolean <code>true</code> value (anything else will *************** *** 221,224 **** --- 219,223 ---- * (like: U, unknown, 12r.23) * <li>use #RRGGBB format to specify colors. + * <li>valid font styles are: PLAIN, ITALIC, BOLD, BOLD ITALIC * <li>comments are allowed. * </ul> *************** *** 226,230 **** * <code></some_tag></code>) can be replaced with * a variable of the following form: <code>${variable_name}</code>. Use ! * {@link XmlTemplate#setMapping(String, String) setMapping()} methods from the base class to replace * template variables with real values at runtime.<p> * --- 225,230 ---- * <code></some_tag></code>) can be replaced with * a variable of the following form: <code>${variable_name}</code>. Use ! * {@link XmlTemplate#setVariable(String, String) setVariable()} ! * methods from the base class to replace * template variables with real values at runtime.<p> * *************** *** 234,238 **** * <li>Replace template values with variables if you want to change them during runtime. * For example, time span should not be hard-coded in the template - you probably want to create ! * many different graphs with different time spans, but starting from the same XML template. * For example, your XML template could start with: * <pre> --- 234,238 ---- * <li>Replace template values with variables if you want to change them during runtime. * For example, time span should not be hard-coded in the template - you probably want to create ! * many different graphs with different time spans from the same XML template. * For example, your XML template could start with: * <pre> *************** *** 250,255 **** * <li>Then, specify real values for template variables: * <pre> ! * t.setMapping("start", new GregorianCalendar(2004, 2, 25)); ! * t.setMapping("end", new GregorianCalendar(2004, 2, 26)); * </pre> * <li>Once all template variables are set, just use the template object to create RrdGraphDef --- 250,255 ---- * <li>Then, specify real values for template variables: * <pre> ! * t.setVariable("start", new GregorianCalendar(2004, 2, 25)); ! * t.setVariable("end", new GregorianCalendar(2004, 2, 26)); * </pre> * <li>Once all template variables are set, just use the template object to create RrdGraphDef *************** *** 267,271 **** */ public class RrdGraphDefTemplate extends XmlTemplate { - static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss"; // ISO format private RrdGraphDef rrdGraphDef; --- 267,270 ---- *************** *** 305,309 **** * object (actual JRobin graphs). Before this method is called, all template variables (if any) * must be resolved (replaced with real values). ! * See {@link XmlTemplate#setMapping(String, String) setMapping()} method information to * understand how to supply values for template variables. * @return Graph definition which can be used to create RrdGraph object (actual JRobin graphs) --- 304,308 ---- * object (actual JRobin graphs). Before this method is called, all template variables (if any) * must be resolved (replaced with real values). ! * See {@link XmlTemplate#setVariable(String, String) setVariable()} method information to * understand how to supply values for template variables. * @return Graph definition which can be used to create RrdGraph object (actual JRobin graphs) *************** *** 315,319 **** throw new RrdException("XML definition must start with <rrd_graph_def>"); } ! validateOnce(root, new String[] {"span", "options", "datasources", "graph"}); rrdGraphDef = new RrdGraphDef(); // traverse all nodes --- 314,318 ---- throw new RrdException("XML definition must start with <rrd_graph_def>"); } ! validateTagsOnlyOnce(root, new String[] {"span", "options", "datasources", "graph"}); rrdGraphDef = new RrdGraphDef(); // traverse all nodes *************** *** 342,347 **** private void resolveGraphElements(Node graphNode) throws RrdException { ! validateOnce(graphNode, new String[] { ! "area", "line", "stack", "gprint", "hrule", "vrule", "comment" }); Node[] childs = getChildNodes(graphNode); --- 341,346 ---- private void resolveGraphElements(Node graphNode) throws RrdException { ! validateTagsOnlyOnce(graphNode, new String[] { ! "area*", "line*", "stack*", "gprint*", "hrule*", "vrule*", "comment*" }); Node[] childs = getChildNodes(graphNode); *************** *** 355,359 **** } else if(nodeName.equals("stack")) { ! validateOnce(childs[i], new String[] { "datasource", "color", "legend" }); String datasource = getChildValue(childs[i], "datasource"); String colorStr = getChildValue(childs[i], "color"); --- 354,358 ---- } else if(nodeName.equals("stack")) { ! validateTagsOnlyOnce(childs[i], new String[] { "datasource", "color", "legend" }); String datasource = getChildValue(childs[i], "datasource"); String colorStr = getChildValue(childs[i], "color"); *************** *** 367,371 **** } else if(nodeName.equals("gprint")) { ! validateOnce(childs[i], new String[] { "datasource", "cf", "format" }); String datasource = getChildValue(childs[i], "datasource"); String consolFun = getChildValue(childs[i], "cf"); --- 366,370 ---- } else if(nodeName.equals("gprint")) { ! validateTagsOnlyOnce(childs[i], new String[] { "datasource", "cf", "format" }); String datasource = getChildValue(childs[i], "datasource"); String consolFun = getChildValue(childs[i], "cf"); *************** *** 374,378 **** } else if(nodeName.equals("hrule")) { ! validateOnce(childs[i], new String[] { "value", "color", "legend", "width" }); double value = getChildValueAsDouble(childs[i], "value"); String colorStr = getChildValue(childs[i], "color"); --- 373,377 ---- } else if(nodeName.equals("hrule")) { ! validateTagsOnlyOnce(childs[i], new String[] { "value", "color", "legend", "width" }); double value = getChildValueAsDouble(childs[i], "value"); String colorStr = getChildValue(childs[i], "color"); *************** *** 386,392 **** } else if(nodeName.equals("vrule")) { ! validateOnce(childs[i], new String[] { "time", "color", "legend", "width" }); String timeStr = getChildValue(childs[i], "time"); ! GregorianCalendar gc = resolveTime(timeStr); String colorStr = getChildValue(childs[i], "color"); Color color = Color.decode(colorStr); --- 385,391 ---- } else if(nodeName.equals("vrule")) { ! validateTagsOnlyOnce(childs[i], new String[] { "time", "color", "legend", "width" }); String timeStr = getChildValue(childs[i], "time"); ! GregorianCalendar gc = Util.getGregorianCalendar(timeStr); String colorStr = getChildValue(childs[i], "color"); Color color = Color.decode(colorStr); *************** *** 404,408 **** if(hasChildNode(lineNode, "datasource")) { // ordinary line definition ! validateOnce(lineNode, new String[] { "datasource", "color", "legend", "width" }); String datasource = getChildValue(lineNode, "datasource"); String colorStr = getChildValue(lineNode, "color"); --- 403,407 ---- if(hasChildNode(lineNode, "datasource")) { // ordinary line definition ! validateTagsOnlyOnce(lineNode, new String[] { "datasource", "color", "legend", "width" }); String datasource = getChildValue(lineNode, "datasource"); String colorStr = getChildValue(lineNode, "color"); *************** *** 418,428 **** else if(hasChildNode(lineNode, "time1")) { // two point definition ! validateOnce(lineNode, new String[] { "time1", "time2", "value1", "value2", "color", "legend", "width" }); String t1str = getChildValue(lineNode, "time1"); ! GregorianCalendar gc1 = resolveTime(t1str); String t2str = getChildValue(lineNode, "time2"); ! GregorianCalendar gc2 = resolveTime(t2str); double v1 = getChildValueAsDouble(lineNode, "value1"); double v2 = getChildValueAsDouble(lineNode, "value2"); --- 417,427 ---- else if(hasChildNode(lineNode, "time1")) { // two point definition ! validateTagsOnlyOnce(lineNode, new String[] { "time1", "time2", "value1", "value2", "color", "legend", "width" }); String t1str = getChildValue(lineNode, "time1"); ! GregorianCalendar gc1 = Util.getGregorianCalendar(t1str); String t2str = getChildValue(lineNode, "time2"); ! GregorianCalendar gc2 = Util.getGregorianCalendar(t2str); double v1 = getChildValueAsDouble(lineNode, "value1"); double v2 = getChildValueAsDouble(lineNode, "value2"); *************** *** 443,447 **** private void resolveArea(Node areaNode) throws RrdException { if(hasChildNode(areaNode, "datasource")) { ! validateOnce(areaNode, new String[] { "datasource", "color", "legend" }); // ordinary area definition String datasource = getChildValue(areaNode, "datasource"); --- 442,446 ---- private void resolveArea(Node areaNode) throws RrdException { if(hasChildNode(areaNode, "datasource")) { ! validateTagsOnlyOnce(areaNode, new String[] { "datasource", "color", "legend" }); // ordinary area definition String datasource = getChildValue(areaNode, "datasource"); *************** *** 453,463 **** else if(hasChildNode(areaNode, "time1")) { // two point definition ! validateOnce(areaNode, new String[] { "time1", "time2", "value1", "value2", "color", "legend", "width" }); String t1str = getChildValue(areaNode, "time1"); ! GregorianCalendar gc1 = resolveTime(t1str); String t2str = getChildValue(areaNode, "time2"); ! GregorianCalendar gc2 = resolveTime(t2str); double v1 = getChildValueAsDouble(areaNode, "value1"); double v2 = getChildValueAsDouble(areaNode, "value2"); --- 452,462 ---- else if(hasChildNode(areaNode, "time1")) { // two point definition ! validateTagsOnlyOnce(areaNode, new String[] { "time1", "time2", "value1", "value2", "color", "legend", "width" }); String t1str = getChildValue(areaNode, "time1"); ! GregorianCalendar gc1 = Util.getGregorianCalendar(t1str); String t2str = getChildValue(areaNode, "time2"); ! GregorianCalendar gc2 = Util.getGregorianCalendar(t2str); double v1 = getChildValueAsDouble(areaNode, "value1"); double v2 = getChildValueAsDouble(areaNode, "value2"); *************** *** 472,482 **** } ! private void resolveDatasources(Node dsNode) throws RrdException { ! validateOnce(dsNode, new String[] { "def" }); ! Node[] nodes = getChildNodes(dsNode, "def"); for(int i = 0; i < nodes.length; i++) { if(hasChildNode(nodes[i], "rrd")) { // RRD datasource ! validateOnce(nodes[i], new String[] {"name", "rrd", "source", "cf"}); String name = getChildValue(nodes[i], "name"); String rrd = getChildValue(nodes[i], "rrd"); --- 471,481 ---- } ! private void resolveDatasources(Node datasourceNode) throws RrdException { ! validateTagsOnlyOnce(datasourceNode, new String[] { "def*" }); ! Node[] nodes = getChildNodes(datasourceNode, "def"); for(int i = 0; i < nodes.length; i++) { if(hasChildNode(nodes[i], "rrd")) { // RRD datasource ! validateTagsOnlyOnce(nodes[i], new String[] {"name", "rrd", "source", "cf"}); String name = getChildValue(nodes[i], "name"); String rrd = getChildValue(nodes[i], "rrd"); *************** *** 487,491 **** else if(hasChildNode(nodes[i], "rpn")) { // RPN datasource ! validateOnce(nodes[i], new String[] {"name", "rpn"}); String name = getChildValue(nodes[i], "name"); String rpn = getChildValue(nodes[i], "rpn"); --- 486,490 ---- else if(hasChildNode(nodes[i], "rpn")) { // RPN datasource ! validateTagsOnlyOnce(nodes[i], new String[] {"name", "rpn"}); String name = getChildValue(nodes[i], "name"); String rpn = getChildValue(nodes[i], "rpn"); *************** *** 499,503 **** private void resolveOptions(Node rootOptionNode) throws RrdException { ! validateOnce(rootOptionNode, new String[] { "anti_aliasing", "arrow_color", "axis_color", "back_color", "background", "base_value", "canvas", "left_padding", "default_font", "default_font_color", --- 498,502 ---- private void resolveOptions(Node rootOptionNode) throws RrdException { ! validateTagsOnlyOnce(rootOptionNode, new String[] { "anti_aliasing", "arrow_color", "axis_color", "back_color", "background", "base_value", "canvas", "left_padding", "default_font", "default_font_color", *************** *** 575,579 **** // GRID RANGE else if(option.equals("grid_range")) { ! validateOnce(optionNode, new String[] { "lower", "upper", "rigid" }); double lower = getChildValueAsDouble(optionNode, "lower"); double upper = getChildValueAsDouble(optionNode, "upper"); --- 574,578 ---- // GRID RANGE else if(option.equals("grid_range")) { ! validateTagsOnlyOnce(optionNode, new String[] { "lower", "upper", "rigid" }); double lower = getChildValueAsDouble(optionNode, "lower"); double upper = getChildValueAsDouble(optionNode, "upper"); *************** *** 593,597 **** // BORDER else if(option.equals("border")) { ! validateOnce(optionNode, new String[] {"color", "width"}); String colorStr = getChildValue(optionNode, "color"); int width = getChildValueAsInt(optionNode, "width"); --- 592,596 ---- // BORDER else if(option.equals("border")) { ! validateTagsOnlyOnce(optionNode, new String[] {"color", "width"}); String colorStr = getChildValue(optionNode, "color"); int width = getChildValueAsInt(optionNode, "width"); *************** *** 645,649 **** // TIME AXIS else if(option.equals("time_axis")) { ! validateOnce(optionNode, new String[] { "min_grid_time_unit", "min_grid_unit_steps", "maj_grid_time_unit", "maj_grid_unit_steps", "date_format", "center_labels" --- 644,648 ---- // TIME AXIS else if(option.equals("time_axis")) { ! validateTagsOnlyOnce(optionNode, new String[] { "min_grid_time_unit", "min_grid_unit_steps", "maj_grid_time_unit", "maj_grid_unit_steps", "date_format", "center_labels" *************** *** 684,688 **** // VALUE AXIS else if(option.equals("value_axis")) { ! validateOnce(optionNode, new String[] {"grid_step", "label_step"}); double gridStep = getChildValueAsDouble(optionNode, "grid_step"); double labelStep = getChildValueAsDouble(optionNode, "label_step"); --- 683,687 ---- // VALUE AXIS else if(option.equals("value_axis")) { ! validateTagsOnlyOnce(optionNode, new String[] {"grid_step", "label_step"}); double gridStep = getChildValueAsDouble(optionNode, "grid_step"); double labelStep = getChildValueAsDouble(optionNode, "label_step"); *************** *** 725,738 **** private void resolveSpan(Node spanNode) throws RrdException { ! validateOnce(spanNode, new String[] {"start", "end"}); String startStr = getChildValue(spanNode, "start"); String endStr = getChildValue(spanNode, "end"); ! GregorianCalendar gc1 = resolveTime(startStr); ! GregorianCalendar gc2 = resolveTime(endStr); rrdGraphDef.setTimePeriod(gc1, gc2); } private Font resolveFont(Node fontNode) throws RrdException { ! validateOnce(fontNode, new String[] {"name", "style", "size"}); String name = getChildValue(fontNode, "name"); String style = getChildValue(fontNode, "style"); --- 724,737 ---- private void resolveSpan(Node spanNode) throws RrdException { ! validateTagsOnlyOnce(spanNode, new String[] {"start", "end"}); String startStr = getChildValue(spanNode, "start"); String endStr = getChildValue(spanNode, "end"); ! GregorianCalendar gc1 = Util.getGregorianCalendar(startStr); ! GregorianCalendar gc2 = Util.getGregorianCalendar(endStr); rrdGraphDef.setTimePeriod(gc1, gc2); } private Font resolveFont(Node fontNode) throws RrdException { ! validateTagsOnlyOnce(fontNode, new String[] {"name", "style", "size"}); String name = getChildValue(fontNode, "name"); String style = getChildValue(fontNode, "style"); *************** *** 754,779 **** } - private GregorianCalendar resolveTime(String timeStr) { - // try to parse it as long - try { - long timestamp = Long.parseLong(timeStr); - return Util.getGregorianCalendar(timestamp); - } catch (NumberFormatException e) { } - // not a long timestamp, try to parse it as data - SimpleDateFormat df = new SimpleDateFormat(DATE_FORMAT); - df.setLenient(false); - try { - Date date = df.parse(timeStr); - return Util.getGregorianCalendar(date); - } catch (ParseException e) { - throw new IllegalArgumentException("Time/date not in " + DATE_FORMAT + - " format: " + timeStr); - } - } - public static void main(String[] args) throws IOException, RrdException { File f = new File("work/test2.xml"); RrdGraphDefTemplate t = new RrdGraphDefTemplate(f); ! t.setMapping("date", new Date()); t.getRrdGraphDef(); } --- 753,760 ---- } public static void main(String[] args) throws IOException, RrdException { File f = new File("work/test2.xml"); RrdGraphDefTemplate t = new RrdGraphDefTemplate(f); ! t.setVariable("date", new Date()); t.getRrdGraphDef(); } --- XmlGraphDefConvertor.java DELETED --- |
From: <sa...@us...> - 2004-02-25 15:43:10
|
Update of /cvsroot/jrobin/src/org/jrobin/graph In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv11738/org/jrobin/graph Modified Files: RrdGraphDef.java Added Files: RrdGraphDefTemplate.java Log Message: XML templates revisited (80% done) --- NEW FILE: RrdGraphDefTemplate.java --- /* ============================================================ * JRobin : Pure java implementation of RRDTool's functionality * ============================================================ * * Project Info: http://www.jrobin.org * Project Lead: Sasa Markovic (sa...@jr...); * * (C) Copyright 2003, by Sasa Markovic. * * Developers: Sasa Markovic (sa...@jr...) * Arne Vandamme (cob...@jr...) * * This library is free software; you can redistribute it and/or modify it under the terms * of the GNU Lesser General Public License as published by the Free Software Foundation; * either version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with this * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, * Boston, MA 02111-1307, USA. */ package org.jrobin.graph; import org.jrobin.core.XmlTemplate; import org.jrobin.core.RrdException; import org.jrobin.core.Util; import org.xml.sax.InputSource; import org.w3c.dom.Node; import java.io.IOException; import java.io.File; import java.awt.*; import java.util.GregorianCalendar; import java.util.Date; import java.text.SimpleDateFormat; import java.text.ParseException; /** * Class used to create an arbitrary number of RrdGraphDefs (graph definition) objects * from a single XML template. XML template can be supplied as an XML InputSource, * XML file or XML formatted string.<p> * * Here is an example of a properly formatted XML template with all available options in it * (unwanted options can be removed):<p> * <pre> * <rrd_graph_def> * <span> * <!-- ISO FORMAT: yyyy-MM-dd HH:mm:ss --> * <start>2004-02-27 13:35:00</start> * <!-- timestamp in seconds is also allowed --> * <end>1234567890</end> * </span> * <options> * <anti_aliasing>true</anti_aliasing> * <arrow_color>#FF0000</arrow_color> * <axis_color>#00FF00</axis_color> * <back_color>#00FF00</back_color> * <background>#FFFFFF</background> * <base_value>1024</base_value> * <canvas>#112211</canvas> * <left_padding>55</left_padding> * <default_font> * <name>Times</name> * <style>BOLD ITALIC</style> * <size>15</size> * </default_font> * <default_font_color>#000000</default_font_color> * <frame_color>#0000FF</frame_color> * <front_grid>true</front_grid> * <grid_range> * <lower>100</lower> * <upper>200</upper> * <rigid>false</rigid> * </grid_range> * <grid_x>true</grid_x> * <grid_y>false</grid_y> * <border> * <color>#00FFFF</color> * <width>2</width> * </border> * <major_grid_color>#00FF00</major_grid_color> * <major_grid_x>true</major_grid_x> * <major_grid_y>false</major_grid_y> * <minor_grid_color>#00FFFF</minor_grid_color> * <minor_grid_x>true</minor_grid_x> * <minor_grid_y>false</minor_grid_y> * <overlay>overlay_image.png</overlay> * <show_legend>true</show_legend> * <show_signature>false</show_signature> * <time_axis> * <!-- ALLOWED TIME UNITS: SECOND, MINUTE, HOUR, DAY, WEEK, MONTH, YEAR --> * <min_grid_time_unit>HOUR</min_grid_time_unit> * <min_grid_unit_steps>4</min_grid_unit_steps> * <maj_grid_time_unit>DAY</maj_grid_time_unit> * <maj_grid_unit_steps>2</maj_grid_unit_steps> * <date_format>HH:mm</date_format> * <center_labels>true</center_labels> * </time_axis> * <time_axis_label>time</time_axis_label> * <title>Graph title</title> * <title_font> * <name>Verdana</name> * <style>BOLD</style> * <size>17</size> * </title_font> * <title_font_color>#FF0000</title_font_color> * <units_exponent>6</units_exponent> * <value_axis> * <grid_step>100</grid_step> * <label_step>200</label_step> * </value_axis> * <vertical_label>voltage [V]</vertical_label> * </options> * <datasources> * <def> * <name>input</name> * <rrd>test1.rrd</rrd> * <source>inOctets</source> * <cf>AVERAGE</cf> * </def> * <def> * <name>output</name> * <rrd>test2.rrd</rrd> * <source>outOctets</source> * <cf>MAX</cf> * </def> * <def> * <name>input8</name> * <rpn>input,8,*</rpn> * </def> * <def> * <name>output8</name> * <rpn>output,8,*,-1,*</rpn> * </def> * </datasources> * <graph> * <area> * <datasource>input</datasource> * <color>#FF0000</color> * <legend>Input traffic</legend> * </area> * <area> * <datasource>output</datasource> * <color>#00FF00</color> * <legend>Output traffic</legend> * </area> * <stack> * <datasource>input8</datasource> * <color>#AA00AA</color> * <legend>Stacked input@r</legend> * </stack> * <line> * <datasource>input</datasource> * <color>#AB7777</color> * <legend>Input traffic@l</legend> * </line> * <line> * <datasource>output</datasource> * <color>#AA00AA</color> * <legend>Output traffic@r</legend> * <width>2</width> * </line> * <area> * <time1>2004-02-25 12:00:01</time1> * <time2>1000222333</time2> * <value1>1001.23</value1> * <value2>2765.45</value2> * <color>#AABBCC</color> * <legend>simeple two point area</legend> * </area> * <line> * <time1>1000111444</time1> * <time2>2004-02-25 12:00:01</time2> * <value1>1009.23</value1> * <value2>9002.45</value2> * <color>#AABB33</color> * <legend>simple two point line</legend> * <width>5</width> * </line> * <gprint> * <datasource>input</datasource> * <cf>AVERAGE</cf> * <format>Average input: @2@c</format> * </gprint> * <gprint> * <datasource>output</datasource> * <cf>MAX</cf> * <format>Average output: @2@r</format> * </gprint> * <hrule> * <value>1234.5678</value> * <color>#112233</color> * <legend>horizontal rule</legend> * <width>3</width> * </hrule> * <vrule> * <time>2004-02-22 17:43:57</time> * <color>#112299</color> * <legend>vertical rule</legend> * <width>6</width> * </vrule> * <comment>Created with JRobin</comment> * </graph> * </rrd_graph_def> * </pre> * Notes on the template syntax:<p> * <ul> * <li>There is a strong relation between the XML template syntax and the syntax of * {@link RrdGraphDef} class methods. If you are not sure what some XML tag means, check javadoc * for the corresponding class. * <li>hard-coded timestamps in templates should be long integeres * (like: 1000243567) or ISO formatted strings (like: 2004-02-21 12:25:45) * <li>all leading and trailing whitespaces are removed * <li>use <code>true</code>, <code>on</code>, <code>yes</code>, <code>y</code>, * or <code>1</code> to specify boolean <code>true</code> value (anything else will * be treated as <code>false</code>). * <li>floating point values: anything that cannot be parsed will be treated as Double.NaN * (like: U, unknown, 12r.23) * <li>use #RRGGBB format to specify colors. * <li>comments are allowed. * </ul> * Any template value (text between <code><some_tag></code> and * <code></some_tag></code>) can be replaced with * a variable of the following form: <code>${variable_name}</code>. Use * {@link XmlTemplate#setMapping(String, String) setMapping()} methods from the base class to replace * template variables with real values at runtime.<p> * * Typical usage scenario:<p> * <ul> * <li>Create your XML template and save it to a file (template.xml, for example) * <li>Replace template values with variables if you want to change them during runtime. * For example, time span should not be hard-coded in the template - you probably want to create * many different graphs with different time spans, but starting from the same XML template. * For example, your XML template could start with: * <pre> * <rrd_graph_def> * <span> * <start>${start}</start> * <end>${end}</end> * </span> * ... * </pre> * <li>In your Java code, create RrdGraphDefTemplate object using your XML template file: * <pre> * RrdGraphDefTemplate t = new RrdGraphDefTemplate(new File(template.xml)); * </pre> * <li>Then, specify real values for template variables: * <pre> * t.setMapping("start", new GregorianCalendar(2004, 2, 25)); * t.setMapping("end", new GregorianCalendar(2004, 2, 26)); * </pre> * <li>Once all template variables are set, just use the template object to create RrdGraphDef * object. This object is actually used to create JRobin grahps: * <pre> * RrdGraphDef gdef = t.getRrdGraphDef(); * RrdGraph g = new RrdGraph(gdef); * g.saveAsPNG("graph.png"); * </pre> * </ul> * You should create new RrdGraphDefTemplate object only once for each XML template. Single template * object can be reused to create as many RrdGraphDef objects as needed, with different values * specified for template variables. XML synatax check is performed only once - the first graph * definition object gets created relatively slowly, but it will be created much faster next time. */ public class RrdGraphDefTemplate extends XmlTemplate { static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss"; // ISO format private RrdGraphDef rrdGraphDef; /** * Creates template object from any parsable XML source * @param inputSource XML source * @throws IOException thrown in case of I/O error * @throws RrdException usually thrown in case of XML related error */ public RrdGraphDefTemplate(InputSource inputSource) throws IOException, RrdException { super(inputSource); } /** * Creates template object from the file containing XML template code * @param xmlFile file containing XML template * @throws IOException thrown in case of I/O error * @throws RrdException usually thrown in case of XML related error */ public RrdGraphDefTemplate(File xmlFile) throws IOException, RrdException { super(xmlFile); } /** * Creates template object from the string containing XML template code * @param xmlString string containing XML template * @throws IOException thrown in case of I/O error * @throws RrdException usually thrown in case of XML related error */ public RrdGraphDefTemplate(String xmlString) throws IOException, RrdException { super(xmlString); } /** * Creates RrdGraphDef object which can be used to create RrdGraph * object (actual JRobin graphs). Before this method is called, all template variables (if any) * must be resolved (replaced with real values). * See {@link XmlTemplate#setMapping(String, String) setMapping()} method information to * understand how to supply values for template variables. * @return Graph definition which can be used to create RrdGraph object (actual JRobin graphs) * @throws RrdException Thrown if parsed XML template contains invalid (unrecognized) tags */ public RrdGraphDef getRrdGraphDef() throws RrdException { // basic check if(!root.getTagName().equals("rrd_graph_def")) { throw new RrdException("XML definition must start with <rrd_graph_def>"); } validateOnce(root, new String[] {"span", "options", "datasources", "graph"}); rrdGraphDef = new RrdGraphDef(); // traverse all nodes Node[] childs = getChildNodes(root); for(int i = 0; i < childs.length; i++) { // SPAN String nodeName = childs[i].getNodeName(); if(nodeName.equals("span")) { resolveSpan(childs[i]); } // OPTIONS else if(nodeName.equals("options")) { resolveOptions(childs[i]); } // DATASOURCES else if(nodeName.equals("datasources")) { resolveDatasources(childs[i]); } // GRAPH ELEMENTS else if(nodeName.equals("graph")) { resolveGraphElements(childs[i]); } } return rrdGraphDef; } private void resolveGraphElements(Node graphNode) throws RrdException { validateOnce(graphNode, new String[] { "area", "line", "stack", "gprint", "hrule", "vrule", "comment" }); Node[] childs = getChildNodes(graphNode); for(int i = 0; i < childs.length; i++) { String nodeName = childs[i].getNodeName(); if(nodeName.equals("area")) { resolveArea(childs[i]); } else if(nodeName.equals("line")) { resolveLine(childs[i]); } else if(nodeName.equals("stack")) { validateOnce(childs[i], new String[] { "datasource", "color", "legend" }); String datasource = getChildValue(childs[i], "datasource"); String colorStr = getChildValue(childs[i], "color"); Color color = Color.decode(colorStr); String legend = getChildValue(childs[i], "legend"); rrdGraphDef.stack(datasource, color, legend); } else if(nodeName.equals("comment")) { String comment = getValue(childs[i]); rrdGraphDef.comment(comment); } else if(nodeName.equals("gprint")) { validateOnce(childs[i], new String[] { "datasource", "cf", "format" }); String datasource = getChildValue(childs[i], "datasource"); String consolFun = getChildValue(childs[i], "cf"); String format = getChildValue(childs[i], "format"); rrdGraphDef.gprint(datasource, consolFun, format); } else if(nodeName.equals("hrule")) { validateOnce(childs[i], new String[] { "value", "color", "legend", "width" }); double value = getChildValueAsDouble(childs[i], "value"); String colorStr = getChildValue(childs[i], "color"); Color color = Color.decode(colorStr); String legend = getChildValue(childs[i], "legend"); int width = 1; try { width = getChildValueAsInt(childs[i], "width"); } catch(RrdException e) { } rrdGraphDef.hrule(value, color, legend, width); } else if(nodeName.equals("vrule")) { validateOnce(childs[i], new String[] { "time", "color", "legend", "width" }); String timeStr = getChildValue(childs[i], "time"); GregorianCalendar gc = resolveTime(timeStr); String colorStr = getChildValue(childs[i], "color"); Color color = Color.decode(colorStr); String legend = getChildValue(childs[i], "legend"); int width = 1; try { width = getChildValueAsInt(childs[i], "width"); } catch(RrdException e) { } rrdGraphDef.vrule(gc, color, legend, width); } } } private void resolveLine(Node lineNode) throws RrdException { if(hasChildNode(lineNode, "datasource")) { // ordinary line definition validateOnce(lineNode, new String[] { "datasource", "color", "legend", "width" }); String datasource = getChildValue(lineNode, "datasource"); String colorStr = getChildValue(lineNode, "color"); Color color = Color.decode(colorStr); String legend = getChildValue(lineNode, "legend"); // line width is not mandatory int width = 1; try { width = getChildValueAsInt(lineNode, "width"); } catch(RrdException e) { } rrdGraphDef.line(datasource, color, legend, width); } else if(hasChildNode(lineNode, "time1")) { // two point definition validateOnce(lineNode, new String[] { "time1", "time2", "value1", "value2", "color", "legend", "width" }); String t1str = getChildValue(lineNode, "time1"); GregorianCalendar gc1 = resolveTime(t1str); String t2str = getChildValue(lineNode, "time2"); GregorianCalendar gc2 = resolveTime(t2str); double v1 = getChildValueAsDouble(lineNode, "value1"); double v2 = getChildValueAsDouble(lineNode, "value2"); String colorStr = getChildValue(lineNode, "color"); Color color = Color.decode(colorStr); String legend = getChildValue(lineNode, "legend"); int width = 1; try { width = getChildValueAsInt(lineNode, "width"); } catch(RrdException e) { } rrdGraphDef.line(gc1, v1, gc2, v2, color, legend, width); } else { throw new RrdException("Unrecognized <line> format"); } } private void resolveArea(Node areaNode) throws RrdException { if(hasChildNode(areaNode, "datasource")) { validateOnce(areaNode, new String[] { "datasource", "color", "legend" }); // ordinary area definition String datasource = getChildValue(areaNode, "datasource"); String colorStr = getChildValue(areaNode, "color"); Color color = Color.decode(colorStr); String legend = getChildValue(areaNode, "legend"); rrdGraphDef.area(datasource, color, legend); } else if(hasChildNode(areaNode, "time1")) { // two point definition validateOnce(areaNode, new String[] { "time1", "time2", "value1", "value2", "color", "legend", "width" }); String t1str = getChildValue(areaNode, "time1"); GregorianCalendar gc1 = resolveTime(t1str); String t2str = getChildValue(areaNode, "time2"); GregorianCalendar gc2 = resolveTime(t2str); double v1 = getChildValueAsDouble(areaNode, "value1"); double v2 = getChildValueAsDouble(areaNode, "value2"); String colorStr = getChildValue(areaNode, "color"); Color color = Color.decode(colorStr); String legend = getChildValue(areaNode, "legend"); rrdGraphDef.area(gc1, v1, gc2, v2, color, legend); } else { throw new RrdException("Unrecognized <area> format"); } } private void resolveDatasources(Node dsNode) throws RrdException { validateOnce(dsNode, new String[] { "def" }); Node[] nodes = getChildNodes(dsNode, "def"); for(int i = 0; i < nodes.length; i++) { if(hasChildNode(nodes[i], "rrd")) { // RRD datasource validateOnce(nodes[i], new String[] {"name", "rrd", "source", "cf"}); String name = getChildValue(nodes[i], "name"); String rrd = getChildValue(nodes[i], "rrd"); String dsName = getChildValue(nodes[i], "source"); String consolFun = getChildValue(nodes[i], "cf"); rrdGraphDef.datasource(name, rrd, dsName, consolFun); } else if(hasChildNode(nodes[i], "rpn")) { // RPN datasource validateOnce(nodes[i], new String[] {"name", "rpn"}); String name = getChildValue(nodes[i], "name"); String rpn = getChildValue(nodes[i], "rpn"); rrdGraphDef.datasource(name, rpn); } else { throw new RrdException("Unrecognized <def> format"); } } } private void resolveOptions(Node rootOptionNode) throws RrdException { validateOnce(rootOptionNode, new String[] { "anti_aliasing", "arrow_color", "axis_color", "back_color", "background", "base_value", "canvas", "left_padding", "default_font", "default_font_color", "frame_color", "front_grid", "grid_range", "grid_x", "grid_y", "border", "major_grid_color", "major_grid_x", "major_grid_y", "minor_grid_color", "minor_grid_x", "minor_grid_y", "overlay", "show_legend", "show_signature", "time_axis", "time_axis_label", "title", "title_font", "title_font_color", "units_exponent", "value_axis", "vertical_label" }); Node[] optionNodes = getChildNodes(rootOptionNode); for(int i = 0; i < optionNodes.length; i++) { String option = optionNodes[i].getNodeName(); Node optionNode = optionNodes[i]; // ANTI ALIASING if(option.equals("anti_aliasing")) { boolean antiAliasing = getValueAsBoolean(optionNode); rrdGraphDef.setAntiAliasing(antiAliasing); } // ARROW COLOR else if(option.equals("arrow_color")) { String colorStr = getValue(optionNode); rrdGraphDef.setArrowColor(Color.decode(colorStr)); } // AXIS COLOR else if(option.equals("axis_color")) { String colorStr = getValue(optionNode); rrdGraphDef.setAxisColor(Color.decode(colorStr)); } // BACK COLOR else if(option.equals("back_color")) { String colorStr = getValue(optionNode); rrdGraphDef.setBackColor(Color.decode(colorStr)); } // BACKGROUND else if(option.equals("background")) { String backgroundFile = getValue(optionNode); rrdGraphDef.setBackground(backgroundFile); } // BASE VALUE else if(option.equals("base_value")) { double baseValue = getValueAsDouble(optionNode); rrdGraphDef.setBaseValue(baseValue); } // CANVAS else if(option.equals("canvas")) { String colorStr = getValue(optionNode); rrdGraphDef.setCanvasColor(Color.decode(colorStr)); } // LEFT PADDING else if(option.equals("left_padding")) { int padding = getValueAsInt(optionNode); rrdGraphDef.setChartLeftPadding(padding); } // DEFAULT FONT else if(option.equals("default_font")) { Font f = resolveFont(optionNode); rrdGraphDef.setTitleFont(f); } // DEFAULT FONT COLOR else if(option.equals("default_font_color")) { String colorStr = getValue(optionNode); rrdGraphDef.setDefaultFontColor(Color.decode(colorStr)); } // FRAME COLOR else if(option.equals("frame_color")) { String colorStr = getValue(optionNode); rrdGraphDef.setFrameColor(Color.decode(colorStr)); } // FRONT GRID else if(option.equals("front_grid")) { boolean frontGrid = getValueAsBoolean(optionNode); rrdGraphDef.setFrontGrid(frontGrid); } // GRID RANGE else if(option.equals("grid_range")) { validateOnce(optionNode, new String[] { "lower", "upper", "rigid" }); double lower = getChildValueAsDouble(optionNode, "lower"); double upper = getChildValueAsDouble(optionNode, "upper"); boolean rigid = getChildValueAsBoolean(optionNode, "rigid"); rrdGraphDef.setGridRange(lower, upper, rigid); } // GRID X? else if(option.equals("grid_x")) { boolean gx = getValueAsBoolean(optionNode); rrdGraphDef.setGridX(gx); } // GRID Y? else if(option.equals("grid_y")) { boolean gy = getValueAsBoolean(optionNode); rrdGraphDef.setGridY(gy); } // BORDER else if(option.equals("border")) { validateOnce(optionNode, new String[] {"color", "width"}); String colorStr = getChildValue(optionNode, "color"); int width = getChildValueAsInt(optionNode, "width"); rrdGraphDef.setImageBorder(Color.decode(colorStr), width); } // MAJOR GRID COLOR else if(option.equals("major_grid_color")) { String colorStr = getValue(optionNode); rrdGraphDef.setMajorGridColor(Color.decode(colorStr)); } // MAJOR GRID X? else if(option.equals("major_grid_x")) { boolean gx = getValueAsBoolean(optionNode); rrdGraphDef.setMajorGridX(gx); } // MAJOR GRID Y? else if(option.equals("major_grid_y")) { boolean gy = getValueAsBoolean(optionNode); rrdGraphDef.setMajorGridY(gy); } // MINOR GRID COLOR else if(option.equals("minor_grid_color")) { String colorStr = getValue(optionNode); rrdGraphDef.setMinorGridColor(Color.decode(colorStr)); } // MINOR GRID X? else if(option.equals("minor_grid_x")) { boolean gx = getValueAsBoolean(optionNode); rrdGraphDef.setMinorGridX(gx); } // MINOR GRID Y? else if(option.equals("minor_grid_y")) { boolean gy = getValueAsBoolean(optionNode); rrdGraphDef.setMinorGridY(gy); } // OVERLAY else if(option.equals("overlay")) { String overlay = getValue(optionNode); rrdGraphDef.setOverlay(overlay); } // SHOW LEGEND? else if(option.equals("show_legend")) { boolean show = getValueAsBoolean(optionNode); rrdGraphDef.setShowLegend(show); } // SHOW SIGNATURE? else if(option.equals("show_signature")) { boolean show = getValueAsBoolean(optionNode); rrdGraphDef.setShowSignature(show); } // TIME AXIS else if(option.equals("time_axis")) { validateOnce(optionNode, new String[] { "min_grid_time_unit", "min_grid_unit_steps", "maj_grid_time_unit", "maj_grid_unit_steps", "date_format", "center_labels" }); int unit1 = resolveUnit(getChildValue(optionNode, "min_grid_time_unit")); int step1 = getChildValueAsInt(optionNode, "min_grid_unit_steps"); int unit2 = resolveUnit(getChildValue(optionNode, "maj_grid_time_unit")); int step2 = getChildValueAsInt(optionNode, "maj_grid_unit_steps"); String format = getChildValue(optionNode, "date_format"); boolean center = getChildValueAsBoolean(optionNode, "center_labels"); rrdGraphDef.setTimeAxis(unit1, step1, unit2, step2, format, center); } // TIME AXIS LABEL else if(option.equals("time_axis_label")) { String label = getValue(optionNode); rrdGraphDef.setTimeAxisLabel(label); } // TITLE else if(option.equals("title")) { String title = getValue(optionNode); rrdGraphDef.setTitle(title); } // TITLE FONT else if(option.equals("title_font")) { Font f = resolveFont(optionNode); rrdGraphDef.setTitleFont(f); } // TITLE FONT COLOR else if(option.equals("title_font_color")) { String colorStr = getValue(optionNode); rrdGraphDef.setTitleFontColor(Color.decode(colorStr)); } // UNITS EXPONENT else if(option.equals("units_exponent")) { int exp = getValueAsInt(optionNode); rrdGraphDef.setUnitsExponent(exp); } // VALUE AXIS else if(option.equals("value_axis")) { validateOnce(optionNode, new String[] {"grid_step", "label_step"}); double gridStep = getChildValueAsDouble(optionNode, "grid_step"); double labelStep = getChildValueAsDouble(optionNode, "label_step"); rrdGraphDef.setValueAxis(gridStep, labelStep); } // VERTICAL LABEL else if(option.equals("vertical_label")) { String label = getValue(optionNode); rrdGraphDef.setVerticalLabel(label); } } } private int resolveUnit(String unit) { if(unit.equalsIgnoreCase("second")) { return TimeAxisUnit.SECOND; } else if(unit.equalsIgnoreCase("minute")) { return TimeAxisUnit.MINUTE; } else if(unit.equalsIgnoreCase("hour")) { return TimeAxisUnit.HOUR; } else if(unit.equalsIgnoreCase("day")) { return TimeAxisUnit.DAY; } else if(unit.equalsIgnoreCase("week")) { return TimeAxisUnit.WEEK; } else if(unit.equalsIgnoreCase("month")) { return TimeAxisUnit.MONTH; } else if(unit.equalsIgnoreCase("year")) { return TimeAxisUnit.YEAR; } else { throw new IllegalArgumentException("Invalid unit specified: " + unit); } } private void resolveSpan(Node spanNode) throws RrdException { validateOnce(spanNode, new String[] {"start", "end"}); String startStr = getChildValue(spanNode, "start"); String endStr = getChildValue(spanNode, "end"); GregorianCalendar gc1 = resolveTime(startStr); GregorianCalendar gc2 = resolveTime(endStr); rrdGraphDef.setTimePeriod(gc1, gc2); } private Font resolveFont(Node fontNode) throws RrdException { validateOnce(fontNode, new String[] {"name", "style", "size"}); String name = getChildValue(fontNode, "name"); String style = getChildValue(fontNode, "style"); int size = getChildValueAsInt(fontNode, "size"); int stl = Font.PLAIN; if(style.equalsIgnoreCase("BOLD")) { stl = Font.BOLD; } else if(style.equalsIgnoreCase("ITALIC")) { stl = Font.ITALIC; } else if(style.equalsIgnoreCase("BOLDITALIC") || style.equalsIgnoreCase("ITALICBOLD") || style.equalsIgnoreCase("BOLD ITALIC") || style.equalsIgnoreCase("ITALIC BOLD")) { stl = Font.ITALIC + Font.BOLD; } return new Font(name, stl, size); } private GregorianCalendar resolveTime(String timeStr) { // try to parse it as long try { long timestamp = Long.parseLong(timeStr); return Util.getGregorianCalendar(timestamp); } catch (NumberFormatException e) { } // not a long timestamp, try to parse it as data SimpleDateFormat df = new SimpleDateFormat(DATE_FORMAT); df.setLenient(false); try { Date date = df.parse(timeStr); return Util.getGregorianCalendar(date); } catch (ParseException e) { throw new IllegalArgumentException("Time/date not in " + DATE_FORMAT + " format: " + timeStr); } } public static void main(String[] args) throws IOException, RrdException { File f = new File("work/test2.xml"); RrdGraphDefTemplate t = new RrdGraphDefTemplate(f); t.setMapping("date", new Date()); t.getRrdGraphDef(); } } Index: RrdGraphDef.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/graph/RrdGraphDef.java,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** RrdGraphDef.java 16 Jan 2004 16:36:54 -0000 1.5 --- RrdGraphDef.java 25 Feb 2004 15:28:06 -0000 1.6 *************** *** 65,69 **** // -- Members // ================================================================ ! private long endTime = Util.getTime(); // default time spam of the last 24 hours private long startTime = Util.getTime() - 86400L; --- 65,69 ---- // -- Members // ================================================================ ! private long endTime = Util.getTime(); // default time span of the last 24 hours private long startTime = Util.getTime() - 86400L; |
From: <sa...@us...> - 2004-02-25 15:43:10
|
Update of /cvsroot/jrobin/src/org/jrobin/core In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv11738/org/jrobin/core Modified Files: RrdDefTemplate.java Util.java XmlTemplate.java Log Message: XML templates revisited (80% done) Index: RrdDefTemplate.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/core/RrdDefTemplate.java,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** RrdDefTemplate.java 23 Feb 2004 15:49:46 -0000 1.1 --- RrdDefTemplate.java 25 Feb 2004 15:28:05 -0000 1.2 *************** *** 211,269 **** } ! /* public static void main(String[] args) throws RrdException, IOException { ! String s = ! "<rrd_def> " + ! " <path>${path}</path> " + ! " <start>1000000000</start> " + ! " <step>${step}</step> " + ! " <datasource> " + ! " <name>input</name> " + ! " <type>COUNTER</type> " + ! " <heartbeat>300</heartbeat> " + ! " <min>10</min> " + ! " <max>U</max> " + ! " </datasource> " + ! " <datasource> " + ! " <name>temperature</name> " + ! " <type>GAUGE</type> " + ! " <heartbeat>400</heartbeat> " + ! " <min>U</min> " + ! " <max>1000</max> " + ! " </datasource> " + ! " <archive> " + ! " <cf>AVERAGE</cf> " + ! " <xff>0.5</xff> " + ! " <steps>1</steps> " + ! " <rows>${rows}</rows> " + ! " </archive> " + ! " <archive> " + ! " <cf>MAX</cf> " + ! " <xff>0.6</xff> " + ! " <steps>6</steps> " + ! " <rows>7000</rows> " + ! " </archive> " + ! "</rrd_def> "; ! RrdDefTemplate t = new RrdDefTemplate(s); ! // works as well: ! // File f = new File("test.xml"); ! // RrdDefTemplate t = new RrdDefTemplate(f); t.setMapping("path", "test1.rrd"); t.setMapping("step", 310); ! t.setMapping("rows", 888); RrdDef def = t.getRrdDef(); System.out.println(def.dump()); - new RrdDb(def).close(); - - t.setMapping("path", "test2.rrd"); - t.setMapping("step", 320); - t.setMapping("rows", 999); - def = t.getRrdDef(); - System.out.println(def.dump()); - new RrdDb(def).close(); } - */ } --- 211,226 ---- } ! public static void main(String[] args) throws RrdException, IOException { ! File f = new File("work/test.xml"); ! RrdDefTemplate t = new RrdDefTemplate(f); t.setMapping("path", "test1.rrd"); t.setMapping("step", 310); ! t.setMapping("hb", 123); RrdDef def = t.getRrdDef(); System.out.println(def.dump()); } } Index: Util.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/core/Util.java,v retrieving revision 1.9 retrieving revision 1.10 diff -C2 -d -r1.9 -r1.10 *** Util.java 23 Feb 2004 15:48:42 -0000 1.9 --- Util.java 25 Feb 2004 15:28:05 -0000 1.10 *************** *** 43,46 **** --- 43,47 ---- import java.util.ArrayList; import java.io.*; + import java.awt.*; /** *************** *** 136,139 **** --- 137,163 ---- } + /** + * Returns <code>GregorianCalendar</code> object for the given timestamp + * (in seconds, without milliseconds) + * @param timestamp Timestamp in seconds. + * @return Corresponding GregorianCalendar object. + */ + public static GregorianCalendar getGregorianCalendar(long timestamp) { + GregorianCalendar gc = new GregorianCalendar(); + gc.setTimeInMillis(timestamp * 1000L); + return gc; + } + + /** + * Returns <code>GregorianCalendar</code> object for the given Date object + * @param date Date object + * @return Corresponding GregorianCalendar object. + */ + public static GregorianCalendar getGregorianCalendar(Date date) { + GregorianCalendar gc = new GregorianCalendar(); + gc.setTime(date); + return gc; + } + /** * Returns timestamp (unix epoch) for the given Date object *************** *** 142,146 **** */ public static long getTimestamp(Date date) { ! return (date.getTime() + 500L) / 1000L; } --- 166,170 ---- */ public static long getTimestamp(Date date) { ! return (date.getTime() + 499L) / 1000L; } *************** *** 190,193 **** --- 214,225 ---- } + static boolean parseBoolean(String valueStr) { + return valueStr.equalsIgnoreCase("true") || + valueStr.equalsIgnoreCase("on") || + valueStr.equalsIgnoreCase("yes") || + valueStr.equalsIgnoreCase("y") || + valueStr.equalsIgnoreCase("1"); + } + private static final File homeDirFile; private static final String homeDirPath; *************** *** 256,260 **** --- 288,299 ---- } + /** + * Various DOM utility functions + */ static class Xml { + static Node[] getChildNodes(Node parentNode) { + return getChildNodes(parentNode, null); + } + static Node[] getChildNodes(Node parentNode, String childName) { ArrayList nodes = new ArrayList(); *************** *** 262,266 **** for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); ! if (node.getNodeName().equals(childName)) { nodes.add(node); } --- 301,305 ---- for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); ! if (childName == null || node.getNodeName().equals(childName)) { nodes.add(node); } *************** *** 277,280 **** --- 316,324 ---- } + static boolean hasChildNode(Node parentNode, String childName) { + Node[] childs = getChildNodes(parentNode, childName); + return childs.length > 0; + } + static String getChildValue(Node parentNode, String childName) throws RrdException { NodeList children = parentNode.getChildNodes(); *************** *** 282,286 **** Node child = children.item(i); if (child.getNodeName().equals(childName)) { ! return child.getFirstChild().getNodeValue().trim(); } } --- 326,330 ---- Node child = children.item(i); if (child.getNodeName().equals(childName)) { ! return getValue(child); } } *************** *** 288,291 **** --- 332,339 ---- } + static String getValue(Node node) { + return node.getFirstChild().getNodeValue().trim(); + } + static int getChildValueAsInt(Node parentNode, String childName) throws RrdException { String valueStr = getChildValue(parentNode, childName); *************** *** 293,296 **** --- 341,349 ---- } + static int getValueAsInt(Node node) { + String valueStr = getValue(node); + return Integer.parseInt(valueStr); + } + static long getChildValueAsLong(Node parentNode, String childName) throws RrdException { String valueStr = getChildValue(parentNode, childName); *************** *** 298,301 **** --- 351,359 ---- } + static long getValueAsLong(Node node) { + String valueStr = getValue(node); + return Long.parseLong(valueStr); + } + static double getChildValueAsDouble(Node parentNode, String childName) throws RrdException { String valueStr = getChildValue(parentNode, childName); *************** *** 303,306 **** --- 361,379 ---- } + static double getValueAsDouble(Node node) { + String valueStr = getValue(node); + return Util.parseDouble(valueStr); + } + + static boolean getChildValueAsBoolean(Node parentNode, String childName) throws RrdException { + String valueStr = getChildValue(parentNode, childName); + return Util.parseBoolean(valueStr); + } + + static boolean getValueAsBoolean(Node node) { + String valueStr = getValue(node); + return Util.parseBoolean(valueStr); + } + static Element getRootElement(InputSource inputSource) throws RrdException, IOException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); Index: XmlTemplate.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/core/XmlTemplate.java,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** XmlTemplate.java 23 Feb 2004 15:49:47 -0000 1.1 --- XmlTemplate.java 25 Feb 2004 15:28:05 -0000 1.2 *************** *** 32,80 **** import java.io.File; import java.util.HashMap; /** * Class used as a base class for various XML template related classes. Class provides * methods for XML source parsing and XML tree traversing. XML source may have unlimited ! * number of placeholders in the format <code>${placeholder_name}</code>. Methods are provided ! * to specify values of placeholders at runtime. Note that this class has limited functionality: ! * XML source gets parsed, and placeholder values are collected. You have to extend this class ! * to do anything more useful.<p> */ public abstract class XmlTemplate { - /** - * root element of the DOM hierarchy representing XML source - */ protected Element root; private HashMap valueMap = new HashMap(); - /** - * Creates XmlTemplate object from any parsable XML input source - * @param xmlSource Any parsable XML input source - * @throws IOException thrown in case of I/O error - * @throws RrdException thrown (in most cases) when the source has invalid XML syntax - * (cannot be parsed at all) - */ protected XmlTemplate(InputSource xmlSource) throws IOException, RrdException { root = Util.Xml.getRootElement(xmlSource); } - /** - * Creates XmlTemplate object from a string containing properly formatted XML - * @param xmlString parsable XML string - * @throws IOException thrown in case of I/O error - * @throws RrdException thrown (in most cases) when the source has invalid XML syntax - * (cannot be parsed at all) - */ protected XmlTemplate(String xmlString) throws IOException, RrdException { root = Util.Xml.getRootElement(xmlString); } - /** - * Creates XmlTemplate object from a file containing properly formatted XML - * @param xmlFile File object representing file containing parsable XML source - * @throws IOException thrown in case of I/O error - * @throws RrdException thrown (in most cases) when the source has invalid XML syntax - * (cannot be parsed at all) - */ protected XmlTemplate(File xmlFile) throws IOException, RrdException { root = Util.Xml.getRootElement(xmlFile); --- 32,61 ---- import java.io.File; import java.util.HashMap; + import java.util.HashSet; + import java.util.Date; + import java.util.GregorianCalendar; + import java.awt.*; /** * Class used as a base class for various XML template related classes. Class provides * methods for XML source parsing and XML tree traversing. XML source may have unlimited ! * number of placeholders (variables) in the format <code>${variable_name}</code>. ! * Methods are provided to specify variable values at runtime. ! * Note that this class has limited functionality: XML source gets parsed, and variable ! * values are collected. You have to extend this class to do something more useful.<p> */ public abstract class XmlTemplate { protected Element root; private HashMap valueMap = new HashMap(); + private HashSet validatedNodes = new HashSet(); protected XmlTemplate(InputSource xmlSource) throws IOException, RrdException { root = Util.Xml.getRootElement(xmlSource); } protected XmlTemplate(String xmlString) throws IOException, RrdException { root = Util.Xml.getRootElement(xmlString); } protected XmlTemplate(File xmlFile) throws IOException, RrdException { root = Util.Xml.getRootElement(xmlFile); *************** *** 89,97 **** /** ! * Sets value for the given placeholder. Placeholder should be supplied by its name. ! * For example, for a placeholder <code>${param}</code> specify just <code>param</code> ! * for its name. ! * @param name Name of the placeholder (placeholder without leading '${' and ending '}'). ! * @param value Value to replace placeholder with. */ public void setMapping(String name, String value) { --- 70,78 ---- /** ! * Sets value for a single XML template variable. Variable name should be specified ! * without leading '${' and ending '}' placeholder markers. For example, for a placeholder ! * <code>${start}</code>, specify <code>start</start> for the <code>name</code> parameter. ! * @param name variable name ! * @param value value to be set in the XML template */ public void setMapping(String name, String value) { *************** *** 100,108 **** /** ! * Sets value for the given placeholder. Placeholder should be supplied by its name. ! * For example, for a placeholder <code>${param}</code> specify just <code>param</code> ! * for its name. ! * @param name Name of the placeholder (placeholder without leading '${' and ending '}'). ! * @param value Value to replace placeholder with. */ public void setMapping(String name, int value) { --- 81,89 ---- /** ! * Sets value for a single XML template variable. Variable name should be specified ! * without leading '${' and ending '}' placeholder markers. For example, for a placeholder ! * <code>${start}</code>, specify <code>start</start> for the <code>name</code> parameter. ! * @param name variable name ! * @param value value to be set in the XML template */ public void setMapping(String name, int value) { *************** *** 111,119 **** /** ! * Sets value for the given placeholder. Placeholder should be supplied by its name. ! * For example, for a placeholder <code>${param}</code> specify just <code>param</code> ! * for its name. ! * @param name Name of the placeholder (placeholder without leading '${' and ending '}'). ! * @param value Value to replace placeholder with. */ public void setMapping(String name, long value) { --- 92,100 ---- /** ! * Sets value for a single XML template variable. Variable name should be specified ! * without leading '${' and ending '}' placeholder markers. For example, for a placeholder ! * <code>${start}</code>, specify <code>start</start> for the <code>name</code> parameter. ! * @param name variable name ! * @param value value to be set in the XML template */ public void setMapping(String name, long value) { *************** *** 122,130 **** /** ! * Sets value for the given placeholder. Placeholder should be supplied by its name. ! * For example, for a placeholder <code>${param}</code> specify just <code>param</code> ! * for its name. ! * @param name Name of the placeholder (placeholder without leading '${' and ending '}'). ! * @param value Value to replace placeholder with. */ public void setMapping(String name, double value) { --- 103,111 ---- /** ! * Sets value for a single XML template variable. Variable name should be specified ! * without leading '${' and ending '}' placeholder markers. For example, for a placeholder ! * <code>${start}</code>, specify <code>start</start> for the <code>name</code> parameter. ! * @param name variable name ! * @param value value to be set in the XML template */ public void setMapping(String name, double value) { *************** *** 133,178 **** /** ! * Returns all child nodes with the given tag ! * belonging to the specified parent Node ! * @param parentNode Parent node ! * @param childName Child node tag ! * @return Array of child nodes with the specified parent and with the given tag name */ ! protected static Node[] getChildNodes(Node parentNode, String childName) { ! return Util.Xml.getChildNodes(parentNode, childName); } /** ! * Returns the first child node with the given parent and the given tag. ! * @param parentNode Parent node ! * @param childName Child node tag ! * @return First child node with the given parent node and the given tag. ! * @throws RrdException Thrown if no such child can be found */ ! protected static Node getFirstChildNode(Node parentNode, String childName) throws RrdException { ! return Util.Xml.getFirstChildNode(parentNode, childName); } /** ! * Returns the 'value' of the child node with the given parent and the given tag name. ! * For example, in a DOM-tree created from the following XML source:<p> ! * <pre> ! * ...<root><branch>abc</branch></root>... ! * </pre> ! * and assuming that <code>parentNode</code> points to the <code><root></code> element, ! * the following call:<p> ! * <pre> ! * getChildValue(parentNode, "branch"); ! * </pre> ! * returns:<p> ! * <code>abc</code><p> ! * @param parentNode Parent DOM node ! * @param childName Child node tag ! * @return XML 'value' of the child node (trimmed content between <childName> and </childName> ! * tags) ! * @throws RrdException Thrown if no such child node exists. */ protected String getChildValue(Node parentNode, String childName) throws RrdException { String value = Util.Xml.getChildValue(parentNode, childName); if(value.startsWith("${") && value.endsWith("}")) { // template variable found, remove leading "${" and trailing "}" --- 114,187 ---- /** ! * Sets value for a single XML template variable. Variable name should be specified ! * without leading '${' and ending '}' placeholder markers. For example, for a placeholder ! * <code>${start}</code>, specify <code>start</start> for the <code>name</code> parameter. ! * @param name variable name ! * @param value value to be set in the XML template */ ! public void setMapping(String name, Color value) { ! valueMap.put(name, "#" + Integer.toHexString(value.getRGB() & 0xFFFFFF)); } /** ! * Sets value for a single XML template variable. Variable name should be specified ! * without leading '${' and ending '}' placeholder markers. For example, for a placeholder ! * <code>${start}</code>, specify <code>start</start> for the <code>name</code> parameter. ! * @param name variable name ! * @param value value to be set in the XML template */ ! public void setMapping(String name, Date value) { ! setMapping(name, Util.getTimestamp(value)); } /** ! * Sets value for a single XML template variable. Variable name should be specified ! * without leading '${' and ending '}' placeholder markers. For example, for a placeholder ! * <code>${start}</code>, specify <code>start</start> for the <code>name</code> parameter. ! * @param name variable name ! * @param value value to be set in the XML template */ + public void setMapping(String name, GregorianCalendar value) { + setMapping(name, Util.getTimestamp(value)); + } + + /** + * Sets value for a single XML template variable. Variable name should be specified + * without leading '${' and ending '}' placeholder markers. For example, for a placeholder + * <code>${start}</code>, specify <code>start</start> for the <code>name</code> parameter. + * @param name variable name + * @param value value to be set in the XML template + */ + public void setMapping(String name, boolean value) { + valueMap.put(name, "" + value); + } + + protected static Node[] getChildNodes(Node parentNode, String childName) { + return Util.Xml.getChildNodes(parentNode, childName); + } + + protected static Node[] getChildNodes(Node parentNode) { + return Util.Xml.getChildNodes(parentNode, null); + } + + protected static Node getFirstChildNode(Node parentNode, String childName) throws RrdException { + return Util.Xml.getFirstChildNode(parentNode, childName); + } + + protected boolean hasChildNode(Node parentNode, String childName) { + return Util.Xml.hasChildNode(parentNode, childName); + } + protected String getChildValue(Node parentNode, String childName) throws RrdException { String value = Util.Xml.getChildValue(parentNode, childName); + return resolveMappings(value); + } + + protected String getValue(Node parentNode) { + String value = Util.Xml.getValue(parentNode); + return resolveMappings(value); + } + + private String resolveMappings(String value) { if(value.startsWith("${") && value.endsWith("}")) { // template variable found, remove leading "${" and trailing "}" *************** *** 184,188 **** else { // no mapping found - this is illegal ! throw new RrdException("No mapping found for template variable " + value); } } --- 193,197 ---- else { // no mapping found - this is illegal ! throw new IllegalArgumentException("No mapping found for template variable " + value); } } *************** *** 190,265 **** } ! /** ! * Returns the 'value' of the child node with the given parent and the given tag name. ! * For example, in a DOM-tree created from the following XML source:<p> ! * <pre> ! * ...<root><branch>123</branch></root>... ! * </pre> ! * and assuming that <code>parentNode</code> points to the <code><root></code> element, ! * the following call:<p> ! * <pre> ! * getChildValue(parentNode, "branch"); ! * </pre> ! * returns:<p> ! * <code>123</code><p> ! * @param parentNode Parent DOM node ! * @param childName Child node tag ! * @return XML 'value' of the child node (trimmed content between <childName> and </childName> ! * tags) ! * @throws RrdException Thrown if no such child node exists. ! */ ! protected int getChildValueAsInt(Node parentNode, String childName) ! throws RrdException, NumberFormatException { String valueStr = getChildValue(parentNode, childName); return Integer.parseInt(valueStr); } ! /** ! * Returns the 'value' of the child node with the given parent and the given tag name. ! * For example, in a DOM-tree created from the following XML source:<p> ! * <pre> ! * ...<root><branch>123</branch></root>... ! * </pre> ! * and assuming that <code>parentNode</code> points to the <code><root></code> element, ! * the following call:<p> ! * <pre> ! * getChildValue(parentNode, "branch"); ! * </pre> ! * returns:<p> ! * <code>123</code><p> ! * @param parentNode Parent DOM node ! * @param childName Child node tag ! * @return XML 'value' of the child node (trimmed content between <childName> and </childName> ! * tags) ! * @throws RrdException Thrown if no such child node exists. ! */ ! protected long getChildValueAsLong(Node parentNode, String childName) ! throws RrdException, NumberFormatException { String valueStr = getChildValue(parentNode, childName); return Long.parseLong(valueStr); } ! /** ! * Returns the 'value' of the child node with the given parent and the given tag name. ! * For example, in a DOM-tree created from the following XML source:<p> ! * <pre> ! * ...<root><branch>123.45</branch></root>... ! * </pre> ! * and assuming that <code>parentNode</code> points to the <code><root></code> element, ! * the following call:<p> ! * <pre> ! * getChildValue(parentNode, "branch"); ! * </pre> ! * returns:<p> ! * <code>123.45</code><p> ! * @param parentNode Parent DOM node ! * @param childName Child node tag ! * @return XML 'value' of the child node (trimmed content between <childName> and </childName> ! * tags) ! * @throws RrdException Thrown if no such child node exists. ! */ protected double getChildValueAsDouble(Node parentNode, String childName) throws RrdException { String valueStr = getChildValue(parentNode, childName); return Util.parseDouble(valueStr); } } --- 199,268 ---- } ! protected int getChildValueAsInt(Node parentNode, String childName) throws RrdException { String valueStr = getChildValue(parentNode, childName); return Integer.parseInt(valueStr); } ! protected int getValueAsInt(Node parentNode) { ! String valueStr = getValue(parentNode); ! return Integer.parseInt(valueStr); ! } ! ! protected long getChildValueAsLong(Node parentNode, String childName) throws RrdException { String valueStr = getChildValue(parentNode, childName); return Long.parseLong(valueStr); } ! protected long getValueAsLong(Node parentNode) { ! String valueStr = getValue(parentNode); ! return Long.parseLong(valueStr); ! } ! protected double getChildValueAsDouble(Node parentNode, String childName) throws RrdException { String valueStr = getChildValue(parentNode, childName); return Util.parseDouble(valueStr); } + + protected double getValueAsDouble(Node parentNode) { + String valueStr = getValue(parentNode); + return Util.parseDouble(valueStr); + } + + protected boolean getChildValueAsBoolean(Node parentNode, String childName) throws RrdException { + String valueStr = getChildValue(parentNode, childName); + return Util.parseBoolean(valueStr); + } + + protected boolean getValueAsBoolean(Node parentNode) { + String valueStr = getValue(parentNode); + return Util.parseBoolean(valueStr); + } + + protected boolean isEmptyNode(Node node) { + // comment node or empty text node + return node.getNodeName().equals("#comment") || + (node.getNodeName().equals("#text") && node.getNodeValue().trim().length() == 0); + } + + protected void validateOnce(Node parentNode, String[] allowedChildNames) throws RrdException { + // validate node only once + if(validatedNodes.contains(parentNode)) { + //System.out.println("Already validated"); + return; + } + Node[] childs = getChildNodes(parentNode); + main: + for(int i = 0; i < childs.length; i++) { + String childName = childs[i].getNodeName(); + for(int j = 0; j < allowedChildNames.length; j++) { + if(childName.equals(allowedChildNames[j])) { + continue main; + } + } + if(!isEmptyNode(childs[i])) { + throw new RrdException("Unexpected tag encountered: <" + childName + ">"); + } + } + validatedNodes.add(parentNode); + } } |