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-06-09 09:44:57
|
Update of /cvsroot/jrobin/src/org/jrobin/graph In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv1817/org/jrobin/graph Modified Files: LinearInterpolator.java Log Message: added javadoc Index: LinearInterpolator.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/graph/LinearInterpolator.java,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** LinearInterpolator.java 9 Jun 2004 08:59:23 -0000 1.2 --- LinearInterpolator.java 9 Jun 2004 09:44:48 -0000 1.3 *************** *** 148,152 **** * <code>INTERPOLATE_RIGHT</code>, <code>INTERPOLATE_LINEAR</code> or * <code>INTERPOLATE_REGRESSION</code>. Any other value will be interpreted as ! * INTERPOLATE_LINEAR. */ public void setInterpolationMethod(int interpolationMethod) { --- 148,152 ---- * <code>INTERPOLATE_RIGHT</code>, <code>INTERPOLATE_LINEAR</code> or * <code>INTERPOLATE_REGRESSION</code>. Any other value will be interpreted as ! * INTERPOLATE_LINEAR (default). */ public void setInterpolationMethod(int interpolationMethod) { |
From: Sasa M. <sa...@us...> - 2004-06-09 08:59:32
|
Update of /cvsroot/jrobin/src/org/jrobin/graph In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv3796/org/jrobin/graph Modified Files: LinearInterpolator.java Log Message: New interpolation method (INTERPOLATE_BESTFIT - best fit straight line). More PlottableDemo graphs Index: LinearInterpolator.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/graph/LinearInterpolator.java,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** LinearInterpolator.java 20 Jan 2004 09:09:33 -0000 1.1 --- LinearInterpolator.java 9 Jun 2004 08:59:23 -0000 1.2 *************** *** 36,40 **** * Interpolation algorithm returns different values based on the value passed to * {@link #setInterpolationMethod(int) setInterpolationMethod()}. If not set, interpolation ! * method defaults to standard linear interpolation. Interpolation method handles NaN datasource * values gracefully.<p> * --- 36,41 ---- * Interpolation algorithm returns different values based on the value passed to * {@link #setInterpolationMethod(int) setInterpolationMethod()}. If not set, interpolation ! * method defaults to standard linear interpolation ({@link #INTERPOLATE_LINEAR}). ! * Interpolation method handles NaN datasource * values gracefully.<p> * *************** *** 52,58 **** * See {@link #setInterpolationMethod(int) setInterpolationMethod()} for explanation. */ public static final int INTERPOLATE_LINEAR = 2; private int lastIndexUsed = 0; - private int interpolationMethod = INTERPOLATE_LINEAR; --- 53,61 ---- * See {@link #setInterpolationMethod(int) setInterpolationMethod()} for explanation. */ public static final int INTERPOLATE_LINEAR = 2; + /** constant used to specify LINEAR REGRESSION as interpolation method. + * See {@link #setInterpolationMethod(int) setInterpolationMethod()} for explanation. */ + public static final int INTERPOLATE_REGRESSION = 3; private int lastIndexUsed = 0; private int interpolationMethod = INTERPOLATE_LINEAR; *************** *** 60,63 **** --- 63,69 ---- private double[] values; + // used only if INTERPOLATE_BESTFIT is specified + double b0 = Double.NaN, b1 = Double.NaN; + /** * Creates LinearInterpolator from arrays of timestamps and corresponding datasource values. *************** *** 129,138 **** * <li><code>INTERPOLATE_LINEAR: 200</code> * </ul> ! * If not set, interpolation method defaults to <code>INTERPOLATE_LINEAR</code>. * @param interpolationMethod Should be <code>INTERPOLATE_LEFT</code>, ! * <code>INTERPOLATE_RIGHT</code> or <code>INTERPOLATE_LINEAR</code>. */ public void setInterpolationMethod(int interpolationMethod) { ! this.interpolationMethod = interpolationMethod; } --- 135,195 ---- * <li><code>INTERPOLATE_LINEAR: 200</code> * </ul> ! * If not set, interpolation method defaults to <code>INTERPOLATE_LINEAR</code>.<p> ! * ! * The fourth available interpolation method is INTERPOLATE_REGRESSION. This method uses ! * simple linear regression to interpolate supplied data with a simple straight line which does not ! * necessarily pass through all data points. The slope of the best-fit line will be chosen so that the ! * total square distance of real data points from from the best-fit line is at minimum.<p> ! * ! * The full explanation of this inteprolation method can be found ! * <a href="http://www.tufts.edu/~gdallal/slr.htm">here</a>.<p> ! * * @param interpolationMethod Should be <code>INTERPOLATE_LEFT</code>, ! * <code>INTERPOLATE_RIGHT</code>, <code>INTERPOLATE_LINEAR</code> or ! * <code>INTERPOLATE_REGRESSION</code>. Any other value will be interpreted as ! * INTERPOLATE_LINEAR. */ public void setInterpolationMethod(int interpolationMethod) { ! switch(interpolationMethod) { ! case INTERPOLATE_REGRESSION: ! calculateBestFitLine(); ! case INTERPOLATE_LEFT: ! case INTERPOLATE_RIGHT: ! case INTERPOLATE_LINEAR: ! this.interpolationMethod = interpolationMethod; ! break; ! default: ! this.interpolationMethod = INTERPOLATE_LINEAR; ! } ! } ! ! private void calculateBestFitLine() { ! int count = timestamps.length, validCount = 0; ! double ts = 0.0, vs = 0.0; ! for(int i = 0; i < count; i++) { ! if(!Double.isNaN(values[i])) { ! ts += timestamps[i]; ! vs += values[i]; ! validCount++; ! } ! } ! if(validCount <= 1) { ! // just one not-NaN point ! b0 = b1 = Double.NaN; ! return; ! } ! ts /= validCount; ! vs /= validCount; ! double s1 = 0, s2 = 0; ! for(int i = 0; i < count; i++) { ! if(!Double.isNaN(values[i])) { ! double dt = timestamps[i] - ts; ! double dv = values[i] - vs; ! s1 += dt * dv; ! s2 += dt * dt; ! } ! } ! b1 = s1 / s2; ! b0 = vs - b1 * ts; } *************** *** 144,147 **** --- 201,207 ---- */ public double getValue(long timestamp) { + if(interpolationMethod == INTERPOLATE_REGRESSION) { + return b0 + b1 * timestamp; + } int count = timestamps.length; // check if out of range |
From: Sasa M. <sa...@us...> - 2004-06-09 08:59:31
|
Update of /cvsroot/jrobin/src In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv3796 Modified Files: PlottableDemo.java Log Message: New interpolation method (INTERPOLATE_BESTFIT - best fit straight line). More PlottableDemo graphs Index: PlottableDemo.java =================================================================== RCS file: /cvsroot/jrobin/src/PlottableDemo.java,v retrieving revision 1.7 retrieving revision 1.8 diff -C2 -d -r1.7 -r1.8 *** PlottableDemo.java 6 Jun 2004 14:40:35 -0000 1.7 --- PlottableDemo.java 9 Jun 2004 08:59:22 -0000 1.8 *************** *** 69,72 **** --- 69,75 ---- createGraph12(); createGraph13(); + createGraph14(); + createGraph15(); + createGraph16(); } *************** *** 401,404 **** --- 404,483 ---- } + private void createGraph14() throws RrdException, IOException { + final int STEPS = 20; + final Color color1 = Color.BLACK, color2 = Color.RED; + CubicSplineInterpolator hitsInterpolator = + new CubicSplineInterpolator(SF_TIMESTAMPS, SF_PAGE_HITS); + RrdGraphDef gDef = new RrdGraphDef(SF_TIMESTAMPS[0], SF_TIMESTAMPS[SF_TIMESTAMPS.length - 1]); + gDef.setTitle("Trick graph 9"); + gDef.setTimeAxisLabel("month"); + gDef.setVerticalLabel("hits"); + gDef.datasource("hits", hitsInterpolator); + gDef.datasource("maxhits", "hits", "MAX"); + for(int i = 1; i <= STEPS; i++) { + gDef.datasource("hits" + i, "maxhits," + i + ",*," + STEPS + ",/,hits,GE,hits,0,IF"); + } + for(int i = STEPS; i >= 1; i--) { + gDef.area("hits" + i, interpolateColor(color1, color2, i / (double) STEPS), null); + } + gDef.line("hits", Color.BLUE, "page hits", 2); + gDef.setTimeAxis(TimeAxisUnit.MONTH, 1, TimeAxisUnit.MONTH, 1, "MMM", false); + RrdGraph graph = new RrdGraph(gDef); + String filename = Util.getJRobinDemoPath("plottable14.png"); + graph.saveAsPNG(filename, 400, 200); + System.out.println("Graph14 saved to " + filename); + } + + private void createGraph15() throws RrdException, IOException { + final int STEPS = 20; + final Color color1 = Color.BLACK, color2 = Color.RED; + LinearInterpolator hitsInterpolator = + new LinearInterpolator(SF_TIMESTAMPS, SF_PAGE_HITS); + hitsInterpolator.setInterpolationMethod(LinearInterpolator.INTERPOLATE_LEFT); + RrdGraphDef gDef = new RrdGraphDef(SF_TIMESTAMPS[0], SF_TIMESTAMPS[SF_TIMESTAMPS.length - 1]); + gDef.setTitle("Trick graph 10"); + gDef.setTimeAxisLabel("month"); + gDef.setVerticalLabel("hits"); + gDef.datasource("hits", hitsInterpolator); + gDef.datasource("maxhits", "hits", "MAX"); + for(int i = 1; i <= STEPS; i++) { + gDef.datasource("hits" + i, "maxhits," + i + ",*," + STEPS + ",/,hits,GE,hits,0,IF"); + } + for(int i = STEPS; i >= 1; i--) { + gDef.area("hits" + i, interpolateColor(color1, color2, i / (double) STEPS), null); + } + gDef.line("hits", Color.BLUE, "page hits", 2); + gDef.setTimeAxis(TimeAxisUnit.MONTH, 1, TimeAxisUnit.MONTH, 1, "MMM", false); + RrdGraph graph = new RrdGraph(gDef); + String filename = Util.getJRobinDemoPath("plottable15.png"); + graph.saveAsPNG(filename, 400, 200); + System.out.println("Graph15 saved to " + filename); + } + + private void createGraph16() throws RrdException, IOException { + LinearInterpolator hitsInterpolator = + new LinearInterpolator(SF_TIMESTAMPS, SF_PAGE_HITS); + LinearInterpolator trendInterpolator = new LinearInterpolator(SF_TIMESTAMPS, SF_PAGE_HITS); + trendInterpolator.setInterpolationMethod(LinearInterpolator.INTERPOLATE_REGRESSION); + RrdGraphDef gDef = new RrdGraphDef(SF_TIMESTAMPS[0], SF_TIMESTAMPS[SF_TIMESTAMPS.length - 1]); + gDef.setTitle("Trend report"); + gDef.setTimeAxisLabel("month"); + gDef.setVerticalLabel("hits"); + gDef.datasource("hits", hitsInterpolator); + gDef.datasource("trend", trendInterpolator); + gDef.datasource("diff", "hits,trend,-"); + gDef.datasource("absdiff", "diff,ABS"); + gDef.area("trend", null, null); + gDef.stack("diff", Color.YELLOW, "difference"); + gDef.line("hits", Color.RED, "real page hits"); + gDef.line("trend", Color.BLUE, "trend@L"); + gDef.gprint("absdiff", "AVERAGE", "Average difference: @0@r"); + gDef.setTimeAxis(TimeAxisUnit.MONTH, 1, TimeAxisUnit.MONTH, 1, "MMM", false); + RrdGraph graph = new RrdGraph(gDef); + String filename = Util.getJRobinDemoPath("plottable16.png"); + graph.saveAsPNG(filename, 400, 200); + System.out.println("Graph16 saved to " + filename); + } + private Color interpolateColor(Color c1, Color c2, double factor) { int r = c1.getRed() + (int)((c2.getRed() - c1.getRed()) * factor); |
From: Arne V. <cob...@us...> - 2004-06-09 07:43:25
|
Update of /cvsroot/jrobin/src/org/jrobin/graph In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv11018/org/jrobin/graph Added Files: FetchSourceList.java RrdOpener.java Log Message: JRobin 1.4.0 - Added setLazy() option for lazy graph regeneration - Added setDatasources() option for GraphDef def management - Fxed 0 as end timestamp option - Fixed GraphDef reuse issue with gprint() --- NEW FILE: FetchSourceList.java --- /* ============================================================ * JRobin : Pure java implementation of RRDTool's functionality * ============================================================ * * Project Info: http://www.jrobin.org * Project Lead: Sasa Markovic (sa...@jr...) * * Developers: Sasa Markovic (sa...@jr...) * Arne Vandamme (cob...@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. * * 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 java.util.HashMap; import java.util.ArrayList; import java.io.IOException; import org.jrobin.core.RrdException; import org.jrobin.core.RrdDb; /** * <p>A FetchSourceList represents a number of RRD datasources, * to be used with RrdGraphDef for Graph generation.</p> * * @author Arne Vandamme (cob...@jr...) */ public class FetchSourceList { // ================================================================ // -- Members // ================================================================ private HashMap map; private ArrayList list; private int defCount; private boolean persistent; private boolean opened; private RrdOpener rrdOpener; // ================================================================ // -- Constructors // ================================================================ /** * Creates a new FetchSourceList with the specified default size. * The size of the actual list is not limited to this number, and * the list will expand automatically if necessary. The default size * should be a ballpark figure for the number of different RrdDb * that will be used (usually a RrdDb corresponds with a single RRD file). * * @param defaultSize Default size of the FetchSourceList. */ public FetchSourceList( int defaultSize ) { this( defaultSize, false ); } /** * Creates a new FetchSourceList with the specified default size. * The size of the actual list is not limited to this number, and * the list will expand automatically if necessary. The default size * should be a ballpark figure for the number of different RrdDb * that will be used (usually a RrdDb corresponds with a single RRD file). * * @param defaultSize Default size of the FetchSourceList. * @param persistent True if the list is persistent, false if not. */ public FetchSourceList( int defaultSize, boolean persistent ) { map = new HashMap( defaultSize ); list = new ArrayList( defaultSize ); opened = false; this.persistent = persistent; } /** * Creates a new FetchSourceList with the specified default size. * The size of the actual list is not limited to this number, and * the list will expand automatically if necessary. The default size * should be a ballpark figure for the number of different RrdDb * that will be used (usually a RrdDb corresponds with a single RRD file). * * @param defaultSize Default size of the FetchSourceList. * @param persistent True if the list is persistent, false if not. * @param rrdOpener Reference to the RrdOpener object that will be used * for RrdDb retrieval. */ public FetchSourceList( int defaultSize, boolean persistent, RrdOpener rrdOpener ) { this( defaultSize, persistent ); this.rrdOpener = rrdOpener; } // ================================================================ // -- Public methods // ================================================================ /** * Sets the internal RrdOpener object to use for RrdDb retrieval. * * @param rrdOpener Reference to the corresponding RrdOpener instance. */ public void setRrdOpener( RrdOpener rrdOpener ) { // Only allow RrdOpener change if not persistent if ( !persistent ) this.rrdOpener = rrdOpener; } public RrdOpener getRrdOpener() { return rrdOpener; } /** * Sets the persistency state of the FetchSourceList. * If the list is set as persistent, RrdDb's can be opened * and retrieved, but not released, and the RrdOpener reference * can not be changed. This is useful to avoid premature closing * and reopening of datasources for performance reasons. * * Setting a FetchSourceList as persistent requires you to manually * control releasing all datasources (all calls to openAll() will * still succeed). * * @param persistent True if the list should behave as persistent. */ public void setPersistent( boolean persistent ) { this.persistent = persistent; } /** * Returns the number of FetchSources hold in the list. * @return Number of different FetchSources. */ public int size() { return list.size(); } /** * Returns the number of Defs represented by the * different FetchSources. * @return Number of Def definitions. */ public int defCount() { return defCount; } /** * Retrieves (opens) all RrdDb instances related to the * different FetchSources. * It is safe to call this method multiple times in a row. * * @throws IOException Thrown in case of fetching I/O error. * @throws RrdException Thrown in case of a JRobin specific error. */ public void openAll() throws RrdException, IOException { if ( opened ) return; for ( int i = 0; i < size(); i++ ) get(i).openRrd(); opened = true; } /** * Releases all RrdDb instances for the FetchSources. * It is safe to call this method multiple times in a row. * In case of a persistent list, this method does nothing * until persistency is removed. * * @throws IOException Thrown in case of fetching I/O error. * @throws RrdException Thrown in case of a JRobin specific error. */ public void releaseAll() throws RrdException, IOException { if ( persistent ) return; // Do not allow release if this FSList is persistent for ( int i = 0; i < size(); i++ ) get(i).release(); opened = false; } /** * Clears up the FetchSourceList for new use. * This removes persistency, releases all RrdDb instances, and * clears the internal list of FetchSources. After clear() * the list is empty. * * @throws IOException Thrown in case of fetching I/O error. * @throws RrdException Thrown in case of a JRobin specific error. */ public void clear() throws RrdException, IOException { persistent = false; releaseAll(); map.clear(); list.clear(); } /** * Returns the highest last update time in seconds of the datasources * represented by the list. If the update time differs for different * datasources, the highest overall timestamp will be returned. * * @return Last update time in seconds. * @throws IOException Thrown in case of fetching I/O error. * @throws RrdException Thrown in case of a JRobin specific error. */ public long getLastUpdateTime() throws RrdException, IOException { RrdDb rrd; long maxUpdateTime = 0; long lastUpdateTime = 0; for ( int i = 0; i < size(); i++ ) { rrd = get(i).getRrd(); lastUpdateTime = rrd.getLastUpdateTime(); if ( lastUpdateTime > maxUpdateTime ) maxUpdateTime = lastUpdateTime; } return maxUpdateTime; } /** * Adds a datasource for graphing purposes to the list, * {@see RrdGraphDef#datasource( java.lang.String, java.lang.String, * java.lang.String, java.lang.String, java.lang.String )}. * @param name Internal datasource name, to be used in GraphDefs. * @param file Path to RRD file. * @param dsName Data source name defined in the RRD file. * @param consolFunc Consolidation function that will be used to extract data from the RRD * file ("AVERAGE", "MIN", "MAX" or "LAST"). * @param backend Name of the RrdBackendFactory that should be used for this RrdDb. * @throws RrdException Thrown in case of a JRobin specific error. */ public void add( String name, String file, String dsName, String consolFunc, String backend ) throws RrdException { if ( map.containsKey(file) ) { FetchSource rf = (FetchSource) map.get(file); rf.addSource( consolFunc, dsName, name ); } else { FetchSource fs = new FetchSource( file, consolFunc, dsName, name, backend, this ); map.put( file, fs ); list.add( fs ); } defCount++; } /** * Adds a datasource for graphing purposes to the list, * {@see RrdGraphDef#datasource( java.lang.String, java.lang.String, * java.lang.String, java.lang.String )}. * * @param name Internal datasource name, to be used in GraphDefs. * @param file Path to RRD file. * @param dsName Data source name defined in the RRD file. * @param consolFunc Consolidation function that will be used to extract data from the RRD * file ("AVERAGE", "MIN", "MAX" or "LAST"). * @throws RrdException Thrown in case of a JRobin specific error. */ public void add( String name, String file, String dsName, String consolFunc ) throws RrdException { if ( map.containsKey(file) ) { FetchSource rf = (FetchSource) map.get(file); rf.addSource( consolFunc, dsName, name ); } else { FetchSource fs = new FetchSource( file, consolFunc, dsName, name, this ); map.put( file, fs ); list.add( fs ); } defCount++; } // ================================================================ // -- Protected (package) methods // ================================================================ /** * Returns the FetchSource for the given index. * * @param index Index of the FetchSource in the list. * @return FetchSource instance. */ protected FetchSource get( int index ) { return (FetchSource) list.get(index); } } --- NEW FILE: RrdOpener.java --- /* ============================================================ * JRobin : Pure java implementation of RRDTool's functionality * ============================================================ * * Project Info: http://www.jrobin.org * Project Lead: Sasa Markovic (sa...@jr...) * * Developers: Sasa Markovic (sa...@jr...) * Arne Vandamme (cob...@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. * * 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 java.io.IOException; import org.jrobin.core.RrdDb; import org.jrobin.core.RrdBackendFactory; import org.jrobin.core.RrdException; import org.jrobin.core.RrdDbPool; /** * <p>Class that represents an object that can be used to perform the actual * opening and closing of RRD files, using different methods. Other objects * like the FetchSourceList representing the Graph datasources * {@see FetchSourceLink} use a RrdOpener to retrieve the RrdDb instances of * RRD datasources.</p> * <p>Overriding the RrdOpener class allows finetuned access on the level * of RrdDb retrieval and release. An child class could for example add * log or debug statements, gather statistics on RRD access, or provide * a transparent way to to access RRD datasources in an alternative way * like through a DBMS. </p> * * @author Arne Vandamme (cob...@jr...) */ public class RrdOpener { // ================================================================ // -- Members // ================================================================ protected RrdDbPool pool; protected boolean readOnly = false; protected boolean usePool = false; // ================================================================ // -- Constructors // ================================================================ /** * Creates a new RrdOpener that will open RrdDb objects with read/write * access. If the usePool flag is set, the RrdOpener will use the RrdDbPool * to retrieve RrdDb instances. * @param usePool True if the RrdOpener should use the RrdDbPool. */ public RrdOpener( boolean usePool ) { this.usePool = usePool; if ( usePool ) pool = RrdDbPool.getInstance(); } /** * Creates a new RrdOpener that will open RrdDb objects with read/write * or read-only access, depending on the readOnly flag.. If the usePool * flag is set, the RrdOpener will use the RrdDbPool to retrieve RrdDb * instances. * @param usePool True if the RrdOpener should use the RrdDbPool. * @param readOnly True if the RrdOpener should open RrdDb objects as read-only. */ public RrdOpener( boolean usePool, boolean readOnly ) { this( usePool ); this.readOnly = readOnly; } // ================================================================ // -- Public methods // ================================================================ /** * Retrieves the RrdDb instance matching a specific RRD datasource name * (usually a file name) and using a specified RrdBackendFactory. * * @param rrdFile Name of the RRD datasource. * @param backendFactory BackendFactory to use for retrieval. * @return RrdDb instance of the datasource. * @throws IOException Thrown in case of I/O error. * @throws RrdException Thrown in case of a JRobin specific error. */ public RrdDb getRrd( String rrdFile, RrdBackendFactory backendFactory ) throws IOException, RrdException { if ( pool != null ) return pool.requestRrdDb( rrdFile ); else return new RrdDb( rrdFile, readOnly, backendFactory ); } /** * Releases an RrdDb instance. Depending on the settings of the RrdOpener, * this either closes the RrdDb, or releases it back into the RrdDbPool. * @param rrdDb RrdDb object that should be released. * @throws IOException Thrown in case of I/O error. * @throws RrdException Thrown in case of a JRobin specific error. */ public void releaseRrd(RrdDb rrdDb) throws IOException, RrdException { if ( pool != null ) pool.release(rrdDb); else rrdDb.close(); } } |
From: Arne V. <cob...@us...> - 2004-06-09 07:35:46
|
Update of /cvsroot/jrobin/src/org/jrobin/graph In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv4540/org/jrobin/graph Modified Files: Comment.java FetchSource.java Gprint.java Grapher.java RrdGraph.java RrdGraphDef.java Log Message: JRobin 1.4.0 - Added setLazy() option for lazy graph regeneration - Added setDatasources() option for GraphDef def management - Fxed 0 as end timestamp option - Fixed GraphDef reuse issue with gprint() Index: Grapher.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/graph/Grapher.java,v retrieving revision 1.12 retrieving revision 1.13 diff -C2 -d -r1.12 -r1.13 *** Grapher.java 31 May 2004 17:13:21 -0000 1.12 --- Grapher.java 9 Jun 2004 07:35:36 -0000 1.13 *************** *** 27,34 **** import java.io.File; import java.io.IOException; ! import java.util.Vector; ! import java.util.HashMap; ! import java.util.Iterator; ! import java.util.LinkedList; import javax.imageio.ImageIO; import java.awt.Font; --- 27,31 ---- import java.io.File; import java.io.IOException; ! import java.util.*; import javax.imageio.ImageIO; import java.awt.Font; *************** *** 90,98 **** private RrdGraphDef graphDef; ! private RrdGraph rrdGraph; ! private Source[] sources; private HashMap sourceIndex; ! private long[] timestamps; private ValueFormatter valueFormat; --- 87,95 ---- private RrdGraphDef graphDef; ! ! private long[] timestamps; private Source[] sources; private HashMap sourceIndex; ! private FetchSourceList fetchSources; private ValueFormatter valueFormat; *************** *** 116,120 **** { this.graphDef = graphDef; - this.rrdGraph = rrdGraph; // Set font dimension specifics --- 113,116 ---- *************** *** 137,140 **** --- 133,140 ---- // Set default graph stroke defaultStroke = new BasicStroke(); + + // Get the fetch sources list + fetchSources = graphDef.getFetchSources(); + fetchSources.setRrdOpener( rrdGraph ); // Set the RrdOpener } *************** *** 281,284 **** --- 281,311 ---- /** + * If the lazy flag of the GraphDef has been set, this method will + * check the most recent update stamp of the FetchSources, and return + * true if the update timestamp is larger than the timestamp of the + * previous graph generation (passed on as a parameter). + * + * @param prevGenTime Timestamp of the previous graph generation. + * @return True if the graph should be generated, false if not. + */ + protected boolean shouldGenerate( long prevGenTime ) throws RrdException, IOException + { + fetchSources.openAll(); + + if ( graphDef.isLazy() && fetchSources.getLastUpdateTime() * 1000 < prevGenTime ) + { + // Should not generate, release immediately + fetchSources.releaseAll(); + + return false; + } + + return true; + } + + // ================================================================ + // -- Private methods + // ================================================================ + /** * Renders the actual graph onto the specified Graphics2D object * @param graphics The handle to the Graphics2D object to render the graph on. *************** *** 305,311 **** } - // ================================================================ - // -- Private methods - // ================================================================ /** * Fetches and calculates all datasources used in the graph. --- 332,335 ---- *************** *** 322,330 **** long finalEndTime = 0; boolean changingEndTime = false; ! long startTime = graphDef.getStartTime(); long endTime = graphDef.getEndTime(); changingEndTime = (endTime == 0); ! int numDefs = graphDef.getNumDefs(); int numSdefs = graphDef.getNumSdefs(); --- 346,354 ---- long finalEndTime = 0; boolean changingEndTime = false; ! long startTime = graphDef.getStartTime(); long endTime = graphDef.getEndTime(); changingEndTime = (endTime == 0); ! int numDefs = graphDef.getNumDefs(); int numSdefs = graphDef.getNumSdefs(); *************** *** 332,336 **** Cdef[] cdefList = graphDef.getCdefs(); int numCdefs = cdefList.length; ! Pdef[] pdefList = graphDef.getPdefs(); int numPdefs = pdefList.length; --- 356,360 ---- Cdef[] cdefList = graphDef.getCdefs(); int numCdefs = cdefList.length; ! Pdef[] pdefList = graphDef.getPdefs(); int numPdefs = pdefList.length; *************** *** 341,385 **** int tblPos = 0; int vePos = 0; ! ! ValueExtractor[] veList = new ValueExtractor[ graphDef.getFetchSources().size() ]; ! Iterator fetchSources = graphDef.getFetchSources().values().iterator(); ! ! while ( fetchSources.hasNext() ) { ! // Get the rrdDb ! src = (FetchSource) fetchSources.next(); ! String rrdFile = src.getRrdFile(); ! rrd = rrdGraph.getRrd( rrdFile, src.getRrdBackendFactory() ); ! ! // If the endtime is 0, use the last time a database was updated ! if ( changingEndTime ) { ! long step = rrd.getRrdDef().getStep(); ! endTime = rrd.getLastUpdateTime() - (endTime % step) - step; ! if ( endTime > finalEndTime ) ! finalEndTime = endTime; ! } ! ! // Fetch all required datasources ! ve = src.fetch( rrd, startTime, endTime, graphDef.getResolution() ); ! 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); ! sourceIndex.put( varList[i], new Integer(tblPos++) ); } - - veList[ vePos++ ] = ve; } ! // Add all Pdefs to the source table for ( int i = 0; i < pdefList.length; i++ ) { pdefList[i].prepare( numPoints ); ! sources[tblPos] = pdefList[i]; sourceIndex.put( pdefList[i].getName(), new Integer(tblPos++) ); --- 365,411 ---- int tblPos = 0; int vePos = 0; ! ! ValueExtractor[] veList = new ValueExtractor[ fetchSources.size() ]; ! ! // Open all datasources ! try { ! fetchSources.openAll(); ! ! for ( int i = 0; i < fetchSources.size(); i++ ) { ! src = fetchSources.get( i ); ! if ( changingEndTime ) ! { ! endTime = src.getLastSampleTime( endTime ); ! if ( endTime > finalEndTime ) ! finalEndTime = endTime; ! } ! // Fetch all required datasources ! ve = src.fetch( startTime, endTime, graphDef.getResolution() ); ! varList = ve.getNames(); ! ! for (int j= 0; j < varList.length; j++) { ! sources[tblPos] = new Def(varList[j], numPoints); ! sourceIndex.put( varList[j], new Integer(tblPos++) ); ! } ! ! veList[ vePos++ ] = ve; } } ! finally ! { ! // Release all datasources again ! fetchSources.releaseAll(); ! } ! // Add all Pdefs to the source table for ( int i = 0; i < pdefList.length; i++ ) { pdefList[i].prepare( numPoints ); ! sources[tblPos] = pdefList[i]; sourceIndex.put( pdefList[i].getName(), new Integer(tblPos++) ); *************** *** 393,399 **** { cdefList[i].prepare( sourceIndex, numPoints ); ! sources[tblPos] = cdefList[i]; ! sourceIndex.put( cdefList[i].getName(), new Integer(tblPos++) ); } --- 419,425 ---- { cdefList[i].prepare( sourceIndex, numPoints ); ! sources[tblPos] = cdefList[i]; ! sourceIndex.put( cdefList[i].getName(), new Integer(tblPos++) ); } *************** *** 874,883 **** ((Gprint) clist[i]).setValue( sources, sourceIndex, valueFormat ); ! Vector tknpairs = clist[i].getTokens(); for (int j = 0; j < tknpairs.size(); j++) { ! String str = (String) tknpairs.elementAt(j++); ! Byte tkn = (Byte) tknpairs.elementAt(j); if ( clist[i].trimString() ) --- 900,909 ---- ((Gprint) clist[i]).setValue( sources, sourceIndex, valueFormat ); ! ArrayList tknpairs = clist[i].getTokens(); for (int j = 0; j < tknpairs.size(); j++) { ! String str = (String) tknpairs.get(j++); ! Byte tkn = (Byte) tknpairs.get(j); if ( clist[i].trimString() ) *************** *** 1019,1027 **** boolean newLine = false; ! Vector tknpairs = graphTitle.getTokens(); for (int j = 0; j < tknpairs.size(); j++) { ! String str = (String) tknpairs.elementAt(j++); ! Byte tkn = (Byte) tknpairs.elementAt(j); tmpStr.append( str ); --- 1045,1053 ---- boolean newLine = false; ! ArrayList tknpairs = graphTitle.getTokens(); for (int j = 0; j < tknpairs.size(); j++) { ! String str = (String) tknpairs.get(j++); ! Byte tkn = (Byte) tknpairs.get(j); tmpStr.append( str ); Index: Gprint.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/graph/Gprint.java,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** Gprint.java 26 Apr 2004 22:28:33 -0000 1.5 --- Gprint.java 9 Jun 2004 07:35:36 -0000 1.6 *************** *** 26,29 **** --- 26,30 ---- import java.util.HashMap; + import java.util.ArrayList; import java.util.regex.Matcher; import java.util.regex.Pattern; *************** *** 55,60 **** private boolean normalScale = false; private boolean uniformScale = false; ! ! // ================================================================ // -- Constructors --- 56,63 ---- private boolean normalScale = false; private boolean uniformScale = false; ! ! protected ArrayList parsedList; ! ! // ================================================================ // -- Constructors *************** *** 75,79 **** checkValuePlacement(); // First see if this GPRINT is valid super.parseComment(); ! this.commentType = Comment.CMT_GPRINT; this.sourceName = sourceName; --- 78,82 ---- checkValuePlacement(); // First see if this GPRINT is valid super.parseComment(); ! this.commentType = Comment.CMT_GPRINT; this.sourceName = sourceName; *************** *** 143,151 **** String valueStr = vFormat.getFormattedValue(); String prefix = vFormat.getPrefix(); ! // Replace all values for (int i = 0; i < oList.size(); i += 2 ) { ! String str = (String) oList.elementAt(i); str = str.replaceAll(VALUE_MARKER, valueStr); --- 146,157 ---- String valueStr = vFormat.getFormattedValue(); String prefix = vFormat.getPrefix(); ! ! // Create a copy of the token/pair list ! parsedList = new ArrayList( oList ); ! // Replace all values for (int i = 0; i < oList.size(); i += 2 ) { ! String str = (String) oList.get(i); str = str.replaceAll(VALUE_MARKER, valueStr); *************** *** 153,157 **** if ( uniformScale ) str = str.replaceAll(UNIFORM_SCALE_MARKER, prefix); ! oList.set( i, str ); } --- 159,163 ---- if ( uniformScale ) str = str.replaceAll(UNIFORM_SCALE_MARKER, prefix); ! parsedList.set( i, str ); } *************** *** 164,169 **** } } ! ! // ================================================================ // -- Private methods --- 170,184 ---- } } ! ! /** ! * Retrieves a <code>ArrayList</code> containing all string/token pairs in order of <code>String</code> - <code>Byte</code>. ! * @return ArrayList containing all string/token pairs of this Comment. ! */ ! ArrayList getTokens() ! { ! return parsedList; ! } ! ! // ================================================================ // -- Private methods Index: RrdGraph.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/graph/RrdGraph.java,v retrieving revision 1.8 retrieving revision 1.9 diff -C2 -d -r1.8 -r1.9 *** RrdGraph.java 30 May 2004 19:49:56 -0000 1.8 --- RrdGraph.java 9 Jun 2004 07:35:36 -0000 1.9 *************** *** 52,66 **** * @author Sasa Markovic (sa...@jr...) */ ! public class RrdGraph implements Serializable { // ================================================================ // -- Members // ================================================================ - private Grapher grapher; private BufferedImage img; - private RrdDbPool pool; - private boolean useImageSize = false; --- 52,63 ---- * @author Sasa Markovic (sa...@jr...) */ ! public class RrdGraph extends RrdOpener implements Serializable { // ================================================================ // -- Members // ================================================================ private Grapher grapher; private BufferedImage img; private boolean useImageSize = false; *************** *** 73,77 **** */ public RrdGraph() ! { } --- 70,75 ---- */ public RrdGraph() ! { ! super( false, true ); } *************** *** 82,87 **** public RrdGraph( boolean usePool ) { ! if ( usePool ) ! this.pool = RrdDbPool.getInstance(); } --- 80,84 ---- public RrdGraph( boolean usePool ) { ! super( usePool, true ); } *************** *** 102,107 **** public RrdGraph( RrdGraphDef graphDef, boolean usePool ) { ! if ( usePool ) ! this.pool = RrdDbPool.getInstance(); grapher = new Grapher( graphDef, this ); } --- 99,103 ---- public RrdGraph( RrdGraphDef graphDef, boolean usePool ) { ! super( usePool, true ); grapher = new Grapher( graphDef, this ); } *************** *** 156,162 **** 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) ); } ! /** * Creates and saves a graph image with default dimensions as a GIF file. --- 152,161 ---- public void saveAsPNG( String path, int width, int height ) throws RrdException, IOException { ! File imgFile = new File( path ); ! ! if ( shouldGenerate(imgFile) ) ! ImageIO.write( getBufferedImage(width, height, BufferedImage.TYPE_INT_RGB), "png", imgFile ); } ! /** * Creates and saves a graph image with default dimensions as a GIF file. *************** *** 183,192 **** public void saveAsGIF(String path, int width, int height) throws RrdException, IOException { ! GifEncoder gifEncoder = new GifEncoder( getBufferedImage(width, height, BufferedImage.TYPE_BYTE_INDEXED) ); ! FileOutputStream stream = new FileOutputStream( path, false ); ! ! gifEncoder.encode(stream); ! ! stream.close(); } --- 182,196 ---- public void saveAsGIF(String path, int width, int height) throws RrdException, IOException { ! File imgFile = new File( path ); ! ! if ( shouldGenerate(imgFile) ) ! { ! GifEncoder gifEncoder = new GifEncoder( getBufferedImage(width, height, BufferedImage.TYPE_BYTE_INDEXED) ); ! FileOutputStream stream = new FileOutputStream( path, false ); ! ! gifEncoder.encode(stream); ! ! stream.close(); ! } } *************** *** 215,218 **** --- 219,227 ---- public void saveAsJPEG( String path, int width, int height, float quality ) throws RrdException, IOException { + File imgFile = new File( path ); + + if ( !shouldGenerate(imgFile) ) + return; + // Based on http://javaalmanac.com/egs/javax.imageio/JpegWrite.html?l=rel // Retrieve jpg image to be compressed *************** *** 265,270 **** ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ! ImageIO.write(getBufferedImage(width, height, BufferedImage.TYPE_INT_RGB), ! "png", outputStream ); return outputStream.toByteArray(); --- 274,278 ---- ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ! ImageIO.write(getBufferedImage(width, height, BufferedImage.TYPE_INT_RGB), "png", outputStream ); return outputStream.toByteArray(); *************** *** 396,420 **** // ================================================================ ! // -- Protected (package) methods // ================================================================ ! RrdDb getRrd( String rrdFile, RrdBackendFactory backendFactory ) throws IOException, RrdException { ! if ( pool != null ) ! return pool.requestRrdDb( rrdFile ); ! else ! return new RrdDb( rrdFile, true, backendFactory ); ! } ! void releaseRrd(RrdDb rrdDb) throws RrdException, IOException ! { ! if ( pool != null ) ! pool.release(rrdDb); ! else ! rrdDb.close(); } - // ================================================================ - // -- Private methods - // ================================================================ private BufferedImage getBufferedImage(int width, int height, int colorType) throws RrdException, IOException { --- 404,426 ---- // ================================================================ ! // -- Private methods // ================================================================ ! /** ! * This method checks if the graph should be generated. This would be the case if the requested ! * image file does not yet exist, or (in case the generation is set to be lazy) the last modified ! * timestamp of the image file is before the last updated timestamp of the used datasources. ! * @param imgFile Image file to check against. ! * @return True if graph generation should be done, false if not. ! * @throws IOException Thrown in case of I/O error. ! * @throws RrdException Thrown in case of JRobin specific error. ! */ ! private boolean shouldGenerate( File imgFile ) throws RrdException, IOException { ! if ( !imgFile.exists() ) ! return true; ! return grapher.shouldGenerate( imgFile.lastModified() ); } private BufferedImage getBufferedImage(int width, int height, int colorType) throws RrdException, IOException { Index: FetchSource.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/graph/FetchSource.java,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** FetchSource.java 31 May 2004 17:13:21 -0000 1.5 --- FetchSource.java 9 Jun 2004 07:35:36 -0000 1.6 *************** *** 25,29 **** package org.jrobin.graph; - import java.util.Vector; import java.util.ArrayList; import java.io.IOException; --- 25,28 ---- *************** *** 52,56 **** protected static final String[] cfNames = new String[] { "AVERAGE", "MAX", "MIN", "LAST" }; ! private String rrdFile; // Holds the name of the RRD file private String backendName; --- 51,57 ---- protected static final String[] cfNames = new String[] { "AVERAGE", "MAX", "MIN", "LAST" }; ! ! private RrdDb rrd; ! private String rrdFile; // Holds the name of the RRD file private String backendName; *************** *** 58,63 **** private int numSources = 0; private ArrayList[] datasources = new ArrayList[MAX_CF]; ! ! // ================================================================ // -- Constructors --- 59,66 ---- private int numSources = 0; private ArrayList[] datasources = new ArrayList[MAX_CF]; ! ! private FetchSourceList listReference = null; ! ! // ================================================================ // -- Constructors *************** *** 65,74 **** /** * Constructs a FetchSource object based on a RRD file name. * @param rrdFile Name of the RRD file holding all datasources. */ ! protected FetchSource( String rrdFile ) { ! this.rrdFile = rrdFile; ! // Initialization of datasource lists per CF for (int i = 0; i < datasources.length; i++) --- 68,80 ---- /** * Constructs a FetchSource object based on a RRD file name. + * * @param rrdFile Name of the RRD file holding all datasources. + * @param listRef Reference to the FetchSourceList this FetchSource belongs to. */ ! protected FetchSource( String rrdFile, FetchSourceList listRef ) { ! this.rrdFile = rrdFile; ! listReference = listRef; ! // Initialization of datasource lists per CF for (int i = 0; i < datasources.length; i++) *************** *** 79,91 **** * Constructs a FetchSource object based on a RRD file name, and * adds a given datasource to the datasources list. * @param rrdFile Name of the RRD file holding all datasources. * @param consolFunc Consolidation function of the datasource to fetch. * @param dsName Internal name of the datasource in the RRD file. * @param name Variable name of the datasource in the graph definition. * @throws RrdException Thrown in case of a JRobin specific error. */ ! FetchSource( String rrdFile, String consolFunc, String dsName, String name ) throws RrdException { ! this( rrdFile ); addSource( consolFunc, dsName, name ); } --- 85,99 ---- * Constructs a FetchSource object based on a RRD file name, and * adds a given datasource to the datasources list. + * * @param rrdFile Name of the RRD file holding all datasources. * @param consolFunc Consolidation function of the datasource to fetch. * @param dsName Internal name of the datasource in the RRD file. * @param name Variable name of the datasource in the graph definition. + * @param listRef Reference to the FetchSourceList this FetchSource belongs to. * @throws RrdException Thrown in case of a JRobin specific error. */ ! protected FetchSource( String rrdFile, String consolFunc, String dsName, String name, FetchSourceList listRef ) throws RrdException { ! this( rrdFile, listRef ); addSource( consolFunc, dsName, name ); } *************** *** 94,97 **** --- 102,106 ---- * Constructs a FetchSource object based on a RRD file name, and * adds a given datasource to the datasources list. + * * @param rrdFile Name of the RRD file holding all datasources. * @param consolFunc Consolidation function of the datasource to fetch. *************** *** 99,107 **** * @param name Variable name of the datasource in the graph definition. * @param backendName Name of the RrdBackendFactory to use for this RrdDb. * @throws RrdException Thrown in case of a JRobin specific error. */ ! FetchSource( String rrdFile, String consolFunc, String dsName, String name, String backendName ) throws RrdException { ! this( rrdFile, consolFunc, dsName, name ); setBackendFactory( backendName ); } --- 108,117 ---- * @param name Variable name of the datasource in the graph definition. * @param backendName Name of the RrdBackendFactory to use for this RrdDb. + * @param listRef Reference to the FetchSourceList this FetchSource belongs to. * @throws RrdException Thrown in case of a JRobin specific error. */ ! protected FetchSource( String rrdFile, String consolFunc, String dsName, String name, String backendName, FetchSourceList listRef ) throws RrdException { ! this( rrdFile, consolFunc, dsName, name, listRef ); setBackendFactory( backendName ); } *************** *** 112,115 **** --- 122,126 ---- /** * Adds a given datasource to the datasources list for this FetchSource. + * * @param consolFunc Consolidation function of the datasource to fetch. * @param dsName Internal name of the datasource in the RRD file. *************** *** 136,139 **** --- 147,151 ---- * Sets the name of the RrdBackendFactory that should be used for this FetchSource. * The factory should be registered with RrdBackendFactory static. + * * @param backendName Name of the RrdBackendFactory to use for this RrdDb. */ *************** *** 144,148 **** /** * Fetches all datavalues for a given timespan out of the provided RRD file. ! * @param rrd An open <code>RrdDb</code> object holding the necessary datasources. * @param startTime Start time of the given timespan. * @param endTime End time of the given timespan. --- 156,160 ---- /** * Fetches all datavalues for a given timespan out of the provided RRD file. ! * * @param startTime Start time of the given timespan. * @param endTime End time of the given timespan. *************** *** 152,157 **** * @throws RrdException Thrown in case of a JRobin specific error. */ ! protected ValueExtractor fetch ( RrdDb rrd, long startTime, long endTime, long resolution ) throws IOException, RrdException { int dsSize = 0; String[] dsNames, vNames; --- 164,172 ---- * @throws RrdException Thrown in case of a JRobin specific error. */ ! protected ValueExtractor fetch ( long startTime, long endTime, long resolution ) throws IOException, RrdException { + if ( rrd == null ) + openRrd(); + int dsSize = 0; String[] dsNames, vNames; *************** *** 195,198 **** --- 210,298 ---- } + /** + * Retrieves the RrdDb connected to this FetchSource. + * The RrdDb instance is retrieved through the use of the + * RrdOpener that is referred internally in the FetchSourceList. + * It is okay to call this method multiple times in a row. + * + * @throws IOException Thrown in case of fetching I/O error. + * @throws RrdException Thrown in case of a JRobin specific error. + */ + protected void openRrd() throws RrdException, IOException + { + if ( rrd == null ) + { + RrdOpener opener = listReference.getRrdOpener(); + + if ( opener == null ) + throw new RrdException( "No RrdOpener specified for RRD management." ); + + // Only open if not open yet + if ( rrd == null ) + rrd = opener.getRrd( rrdFile, getRrdBackendFactory() ); + } + } + + /** + * Gets the RrdDb instance for this FetchSource. If the + * RrdDb has not been retrieved yet, it is before this + * method returns. It is okay to call this method multiple + * times in a row. + * + * @return Reference to the RrdDb instance. + * @throws IOException Thrown in case of fetching I/O error. + * @throws RrdException Thrown in case of a JRobin specific error. + */ + protected RrdDb getRrd() throws RrdException, IOException + { + if ( rrd == null ) + openRrd(); + + return rrd; + } + + /** + * Releases the internal RrdDb reference for this FetchSource. + * It is okay to call this method multiple times in a row. + * + * @throws IOException Thrown in case of fetching I/O error. + * @throws RrdException Thrown in case of a JRobin specific error. + */ + protected void release() throws RrdException, IOException + { + if ( rrd != null ) + { + RrdOpener opener = listReference.getRrdOpener(); + + if ( opener == null ) + throw new RrdException( "No RrdOpener specified for RRD management." ); + + opener.releaseRrd( rrd ); + rrd = null; + } + } + + /** + * Returns the timestamp of the last completed sample before or on the given time. + * This method is useful to find out the actual last timestamp for graphing, if the + * current time is after the last update time. This sample can contain bad (Unknown) + * values, as long as the interval for it has been completed. This is not the + * timestamp of the last non-unknown sample! + * + * @param endTime Timestamp for which the last sample time should be calculated. + * @return Last sample timestamp in seconds. + * @throws IOException Thrown in case of fetching I/O error. + * @throws RrdException Thrown in case of a JRobin specific error. + */ + protected long getLastSampleTime( long endTime ) throws RrdException, IOException + { + if ( rrd == null ) + openRrd(); + + long step = rrd.getRrdDef().getStep(); + + return endTime = rrd.getLastUpdateTime() - (endTime % step) - step; + } + protected String getRrdFile() { return rrdFile; Index: RrdGraphDef.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/graph/RrdGraphDef.java,v retrieving revision 1.14 retrieving revision 1.15 diff -C2 -d -r1.14 -r1.15 *** RrdGraphDef.java 31 May 2004 17:13:21 -0000 1.14 --- RrdGraphDef.java 9 Jun 2004 07:35:36 -0000 1.15 *************** *** 61,123 **** // -- Members // ================================================================ ! private long endTime = Util.getTime(); // default time span of the last 24 hours ! private long startTime = Util.getTime() - 86400L; ! private long resolution = 1; // resolution to fetch from the RRD databases ! private Title title = null; // no title ! private String valueAxisLabel = null; // no vertical label ! private TimeAxisLabel timeAxisLabel = null; // no horizontal label ! ! private boolean gridX = true; // hide entire X axis grid (default: no) ! private boolean gridY = true; // hide entire Y axis grid (default: no) ! private boolean minorGridX = true; // hide minor X axis grid (default: no) ! private boolean minorGridY = true; // hide minor Y axis grid (default: no) ! private boolean majorGridX = true; // hide major X axis grid with labels (default: no) ! private boolean majorGridY = true; // hide major Y axis grid with labels (default: no) ! private boolean frontGrid = true; // show grid in front of the chart (default: yes) ! private boolean antiAliasing = true; // use anti-aliasing for the chart (default: yes) ! private boolean showLegend = true; // show legend and comments (default: yes) ! private boolean drawSignature = true; // show JRobin url signature (default: yes) ! private Color backColor = new Color( 245, 245, 245 ); // variation of light gray ! private Color canvasColor = Color.WHITE; // white ! private Color borderColor = Color.LIGHT_GRAY; // light gray, only applicable with a borderStroke ! private Color normalFontColor = Color.BLACK; // black ! private Color titleFontColor = Color.BLACK; // black ! private Color majorGridColor = new Color(130,30,30); // variation of dark red ! private Color minorGridColor = new Color(140,140,140); // variation of gray ! private Color axisColor = new Color(130,30,30); // variation of dark red ! private Color arrowColor = Color.RED; // red ! private Color frameColor = Color.LIGHT_GRAY; // light gray ! private Font titleFont = null; // use default 'grapher' font ! private Font normalFont = null; // use default 'grapher' font ! private File background = null; // no background image by default ! private File overlay = null; // no overlay image by default ! private int chart_lpadding = Grapher.CHART_LPADDING; // padding space on the left of the chart area ! private int firstDayOfWeek = TimeAxisUnit.MONDAY; // first day of a calendar week, default: monday ! private double baseValue = ValueFormatter.DEFAULT_BASE; // unit base value to use (default: 1000) ! private int scaleIndex = ValueFormatter.NO_SCALE; // fixed units exponent value to use ! private BasicStroke borderStroke = null; // defaults to standard beveled border ! private TimeAxisUnit tAxis = null; // custom time axis grid, defaults to no custom ! private ValueAxisUnit vAxis = null; // custom value axis grid, defaults to no custom ! private GridRange gridRange = null; // custom value range definition, defaults to auto-scale // -- Non-settable members ! private int numSdefs = 0; ! private int numDefs = 0; // number of Def datasources added ! private int commentLines = 0; // number of complete lines in the list of comment items ! private int commentLineShift = 0; // modifier to add to get minimum one complete line of comments ! private HashMap fetchSources = new HashMap( 10 ); // holds the list of FetchSources ! private ArrayList cdefList = new ArrayList( 10 ); // holds the list of Cdef datasources ! private ArrayList pdefList = new ArrayList( 10 ); // holds the list of Plottable datasources ! private ArrayList plotDefs = new ArrayList( 10 ); // holds the list of PlotDefs ! private ArrayList comments = new ArrayList( 10 ); // holds the list of comment items --- 61,124 ---- // -- Members // ================================================================ ! private long endTime = Util.getTime(); // default time span of the last 24 hours ! private long startTime = Util.getTime() - 86400L; ! private long resolution = 1; // resolution to fetch from the RRD databases ! private Title title = null; // no title ! private String valueAxisLabel = null; // no vertical label ! private TimeAxisLabel timeAxisLabel = null; // no horizontal label ! ! private boolean lazyGeneration = false; // generate only if the file is outdated ! private boolean gridX = true; // hide entire X axis grid (default: no) ! private boolean gridY = true; // hide entire Y axis grid (default: no) ! private boolean minorGridX = true; // hide minor X axis grid (default: no) ! private boolean minorGridY = true; // hide minor Y axis grid (default: no) ! private boolean majorGridX = true; // hide major X axis grid with labels (default: no) ! private boolean majorGridY = true; // hide major Y axis grid with labels (default: no) ! private boolean frontGrid = true; // show grid in front of the chart (default: yes) ! private boolean antiAliasing = true; // use anti-aliasing for the chart (default: yes) ! private boolean showLegend = true; // show legend and comments (default: yes) ! private boolean drawSignature = true; // show JRobin url signature (default: yes) ! private Color backColor = new Color( 245, 245, 245 ); // variation of light gray ! private Color canvasColor = Color.WHITE; // white ! private Color borderColor = Color.LIGHT_GRAY; // light gray, only applicable with a borderStroke ! private Color normalFontColor = Color.BLACK; // black ! private Color titleFontColor = Color.BLACK; // black ! private Color majorGridColor = new Color(130,30,30); // variation of dark red ! private Color minorGridColor = new Color(140,140,140); // variation of gray ! private Color axisColor = new Color(130,30,30); // variation of dark red ! private Color arrowColor = Color.RED; // red ! private Color frameColor = Color.LIGHT_GRAY; // light gray ! private Font titleFont = null; // use default 'grapher' font ! private Font normalFont = null; // use default 'grapher' font ! private File background = null; // no background image by default ! private File overlay = null; // no overlay image by default ! private int chart_lpadding = Grapher.CHART_LPADDING; // padding space on the left of the chart area ! private int firstDayOfWeek = TimeAxisUnit.MONDAY; // first day of a calendar week, default: monday ! private double baseValue = ValueFormatter.DEFAULT_BASE; // unit base value to use (default: 1000) ! private int scaleIndex = ValueFormatter.NO_SCALE; // fixed units exponent value to use ! private BasicStroke borderStroke = null; // defaults to standard beveled border ! private TimeAxisUnit tAxis = null; // custom time axis grid, defaults to no custom ! private ValueAxisUnit vAxis = null; // custom value axis grid, defaults to no custom ! private GridRange gridRange = null; // custom value range definition, defaults to auto-scale // -- Non-settable members ! private int numSdefs = 0; ! private int numDefs = 0; // number of Def datasources added ! private int commentLines = 0; // number of complete lines in the list of comment items ! private int commentLineShift = 0; // modifier to add to get minimum one complete line of comments ! private FetchSourceList fetchSources = new FetchSourceList( 10 ); // holds the list of FetchSources ! private ArrayList cdefList = new ArrayList( 10 ); // holds the list of Cdef datasources ! private ArrayList pdefList = new ArrayList( 10 ); // holds the list of Plottable datasources ! private ArrayList plotDefs = new ArrayList( 10 ); // holds the list of PlotDefs ! private ArrayList comments = new ArrayList( 10 ); // holds the list of comment items *************** *** 210,213 **** --- 211,227 ---- /** + * Sets the 'lazy' flag for this GraphDef. This means that upon graph generation and saving to a file, + * JRobin will first check that if that file already exists, the 'last modified' timestamp + * of the file is smaller than 'last update' timestamp of the used datasources. Only if that is indeed + * the case and the image file is outdated, will the graph be generated. + * + * @param lazyGeneration True if the script should only generate. + */ + public void setLazy( boolean lazyGeneration ) + { + this.lazyGeneration = lazyGeneration; + } + + /** * Sets the resolution with which data will be fetched from the RRD sources. * JRobin will try to match the requested resolution as closely as possible. *************** *** 656,665 **** public void datasource( String name, String file, String dsName, String consolFunc ) throws RrdException { ! if ( fetchSources.containsKey(file) ) { ! FetchSource rf = (FetchSource) fetchSources.get(file); ! rf.addSource( consolFunc, dsName, name ); ! } ! else ! fetchSources.put( file, new FetchSource(file, consolFunc, dsName, name) ); numDefs++; --- 670,674 ---- public void datasource( String name, String file, String dsName, String consolFunc ) throws RrdException { ! fetchSources.add( name, file, dsName, consolFunc ); numDefs++; *************** *** 687,698 **** public void datasource( String name, String file, String dsName, String consolFunc, String backend ) throws RrdException { ! if ( fetchSources.containsKey(file) ) ! { ! FetchSource rf = (FetchSource) fetchSources.get(file); ! rf.setBackendFactory( backend ); ! rf.addSource( consolFunc, dsName, name ); ! } ! else ! fetchSources.put( file, new FetchSource(file, consolFunc, dsName, name, backend ) ); numDefs++; --- 696,700 ---- public void datasource( String name, String file, String dsName, String consolFunc, String backend ) throws RrdException { ! fetchSources.add( name, file, dsName, consolFunc, backend ); numDefs++; *************** *** 700,703 **** --- 702,718 ---- /** + * <p>Clears the list of RRD datasources for this GraphDef and sets it to the FetchSourceList + * passed as aparameter. This does not alter any Cdef, Sdef or Pdef definitions. The datasources + * should be passed on as a FetchSourceList {@see FetchSourceList}.</p> + * @param datasourceList FetchSourceList of the datasources to use. + */ + public void setDatasources( FetchSourceList datasourceList ) + { + fetchSources = datasourceList; + + numDefs = fetchSources.defCount(); + } + + /** * <p>Adds complex graph source with the given name to the graph definition. * Complex graph sources are evaluated using the supplied <code>rpn</code> expression. *************** *** 1086,1094 **** xml.startTag("datasources"); // defs ! Iterator fsIterator = fetchSources.values().iterator(); ! while (fsIterator.hasNext()) { ! FetchSource fs = (FetchSource) fsIterator.next(); ! fs.exportXml(xml); ! } // cdefs and sdefs for (int i = 0; i < cdefList.size(); i++ ) { --- 1101,1106 ---- xml.startTag("datasources"); // defs ! for ( int i = 0; i < fetchSources.size(); i++ ) ! fetchSources.get( i ).exportXml(xml); // cdefs and sdefs for (int i = 0; i < cdefList.size(); i++ ) { *************** *** 1167,1170 **** --- 1179,1186 ---- } + protected boolean isLazy() { + return lazyGeneration; + } + protected Title getTitle() { return title; *************** *** 1350,1354 **** } ! protected HashMap getFetchSources() { return fetchSources; --- 1366,1370 ---- } ! protected FetchSourceList getFetchSources() { return fetchSources; Index: Comment.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/graph/Comment.java,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** Comment.java 1 Mar 2004 08:50:25 -0000 1.3 --- Comment.java 9 Jun 2004 07:35:35 -0000 1.4 *************** *** 26,29 **** --- 26,30 ---- import java.util.Vector; + import java.util.ArrayList; import org.jrobin.core.RrdException; *************** *** 61,65 **** protected String text; ! protected Vector oList = new Vector(); --- 62,66 ---- protected String text; ! protected ArrayList oList = new ArrayList(3); *************** *** 226,233 **** /** ! * Retrieves a <code>Vector</code> containing all string/token pairs in order of <code>String</code> - <code>Byte</code>. ! * @return Vector containing all string/token pairs of this Comment. */ ! Vector getTokens() { return oList; --- 227,234 ---- /** ! * Retrieves a <code>ArrayList</code> containing all string/token pairs in order of <code>String</code> - <code>Byte</code>. ! * @return ArrayList containing all string/token pairs of this Comment. */ ! ArrayList getTokens() { return oList; |
From: Sasa M. <sa...@us...> - 2004-06-06 14:40:47
|
Update of /cvsroot/jrobin/src In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv11626 Modified Files: PlottableDemo.java Log Message: nice plottable demos Index: PlottableDemo.java =================================================================== RCS file: /cvsroot/jrobin/src/PlottableDemo.java,v retrieving revision 1.6 retrieving revision 1.7 diff -C2 -d -r1.6 -r1.7 *** PlottableDemo.java 2 Jun 2004 07:19:57 -0000 1.6 --- PlottableDemo.java 6 Jun 2004 14:40:35 -0000 1.7 *************** *** 61,64 **** --- 61,72 ---- createGraph4(); createGraph5(); + createGraph6(); + createGraph7(); + createGraph8(); + createGraph9(); + createGraph10(); + createGraph11(); + createGraph12(); + createGraph13(); } *************** *** 193,196 **** --- 201,411 ---- } + private void createGraph6() throws RrdException, IOException { + CubicSplineInterpolator hitsInterpolator = + new CubicSplineInterpolator(SF_TIMESTAMPS, SF_PAGE_HITS); + RrdGraphDef gDef = new RrdGraphDef(SF_TIMESTAMPS[0], + SF_TIMESTAMPS[SF_TIMESTAMPS.length - 1]); + gDef.setTitle("Trick graph 1"); + gDef.setTimeAxisLabel("month"); + gDef.setVerticalLabel("hits"); + gDef.datasource("hits", hitsInterpolator); + gDef.datasource("hits2", "hits,1000,-"); + gDef.datasource("invisible", "hits2,0,GE,hits2,0,IF"); + gDef.datasource("margin", "hits,invisible,-"); + gDef.area("invisible", null, null); + gDef.stack("margin", Color.YELLOW, "yellow margin"); + gDef.line("hits", Color.RED, "page hits", 3); + gDef.line("hits", Color.WHITE, null, 1); + gDef.setTimeAxis(TimeAxisUnit.MONTH, 1, TimeAxisUnit.MONTH, 1, "MMM", false); + RrdGraph graph = new RrdGraph(gDef); + String filename = Util.getJRobinDemoPath("plottable6.png"); + graph.saveAsPNG(filename, 400, 200); + System.out.println("Graph6 saved to " + filename); + } + + private void createGraph7() throws RrdException, IOException { + CubicSplineInterpolator hitsInterpolator = + new CubicSplineInterpolator(SF_TIMESTAMPS, SF_PAGE_HITS); + RrdGraphDef gDef = new RrdGraphDef(SF_TIMESTAMPS[0], + SF_TIMESTAMPS[SF_TIMESTAMPS.length - 1]); + gDef.setTitle("Trick graph 2"); + gDef.setTimeAxisLabel("month"); + gDef.setVerticalLabel("hits"); + gDef.datasource("hits", hitsInterpolator); + gDef.datasource("avg", "hits", "AVERAGE"); + gDef.datasource("diff", "avg,hits,-"); + gDef.datasource("diffpos", "diff,0,GE,diff,0,IF"); + gDef.datasource("diffneg", "diff,0,LT,diff,0,IF"); + gDef.area("hits", null, null); + gDef.stack("diffpos", Color.RED, "bad"); + gDef.stack("diffneg", Color.GREEN, "good"); + gDef.line("hits", Color.BLUE, "hits", 3); + gDef.line("hits", Color.WHITE, null, 1); + gDef.line("avg", Color.MAGENTA, "average@L", 3); + gDef.line("avg", Color.WHITE, null, 1); + gDef.setTimeAxis(TimeAxisUnit.MONTH, 1, TimeAxisUnit.MONTH, 1, "MMM", false); + gDef.gprint("hits", "AVERAGE", "Average: @0@r"); + RrdGraph graph = new RrdGraph(gDef); + String filename = Util.getJRobinDemoPath("plottable7.png"); + graph.saveAsPNG(filename, 400, 200); + System.out.println("Graph7 saved to " + filename); + } + + private void createGraph8() throws RrdException, IOException { + GregorianCalendar[] times = { SF_TIMESTAMPS[0], SF_TIMESTAMPS[SF_TIMESTAMPS.length - 1] }; + double[] values = { SF_PAGE_HITS[0], SF_PAGE_HITS[SF_PAGE_HITS.length - 1] }; + LinearInterpolator trendLine = new LinearInterpolator(times, values); + CubicSplineInterpolator hitsInterpolator = + new CubicSplineInterpolator(SF_TIMESTAMPS, SF_PAGE_HITS); + RrdGraphDef gDef = new RrdGraphDef(SF_TIMESTAMPS[0], + SF_TIMESTAMPS[SF_TIMESTAMPS.length - 1]); + gDef.setTitle("Trick graph 3"); + gDef.setTimeAxisLabel("month"); + gDef.setVerticalLabel("hits"); + gDef.datasource("hits", hitsInterpolator); + gDef.datasource("trend", trendLine); + gDef.datasource("diff", "trend,hits,-"); + gDef.area("hits", null, null); + gDef.stack("diff", Color.YELLOW, "difference"); + gDef.line("hits", Color.BLUE, "hits"); + gDef.line("trend", Color.RED, "trend@L"); + gDef.setTimeAxis(TimeAxisUnit.MONTH, 1, TimeAxisUnit.MONTH, 1, "MMM", false); + RrdGraph graph = new RrdGraph(gDef); + String filename = Util.getJRobinDemoPath("plottable8.png"); + graph.saveAsPNG(filename, 400, 200); + System.out.println("Graph8 saved to " + filename); + } + + private void createGraph9() throws RrdException, IOException { + final int GRADIENT_STEPS = 30; + final Color color1 = Color.RED, color2 = Color.YELLOW; + CubicSplineInterpolator hitsInterpolator = + new CubicSplineInterpolator(SF_TIMESTAMPS, SF_PAGE_HITS); + RrdGraphDef gDef = new RrdGraphDef(SF_TIMESTAMPS[0], SF_TIMESTAMPS[SF_TIMESTAMPS.length - 1]); + gDef.setTitle("Trick graph 4"); + gDef.setTimeAxisLabel("month"); + gDef.setVerticalLabel("hits"); + gDef.datasource("hits", hitsInterpolator); + for(int i = 0; i <= GRADIENT_STEPS; i++) { + gDef.datasource("hits" + i, "hits," + i + ",*," + GRADIENT_STEPS + ",/"); + } + for(int i = GRADIENT_STEPS; i >=0 ; i--) { + Color c = interpolateColor(color1, color2, i / (double) GRADIENT_STEPS); + gDef.area("hits" + i, c, null); + } + gDef.line("hits", Color.BLACK, "Number of page hits"); + gDef.setTimeAxis(TimeAxisUnit.MONTH, 1, TimeAxisUnit.MONTH, 1, "MMM", false); + RrdGraph graph = new RrdGraph(gDef); + String filename = Util.getJRobinDemoPath("plottable9.png"); + graph.saveAsPNG(filename, 400, 200); + System.out.println("Graph9 saved to " + filename); + } + + private void createGraph10() throws RrdException, IOException { + final int GRADIENT_STEPS = 30; + final Color color1 = Color.RED, color2 = Color.YELLOW; + CubicSplineInterpolator hitsInterpolator = + new CubicSplineInterpolator(SF_TIMESTAMPS, SF_PAGE_HITS); + RrdGraphDef gDef = new RrdGraphDef(SF_TIMESTAMPS[0], SF_TIMESTAMPS[SF_TIMESTAMPS.length - 1]); + gDef.setTitle("Trick graph 5"); + gDef.setTimeAxisLabel("month"); + gDef.setVerticalLabel("hits"); + gDef.datasource("hits", hitsInterpolator); + for(int i = 0; i <= GRADIENT_STEPS; i++) { + gDef.datasource("hits" + i, "hits," + i + ",*," + GRADIENT_STEPS + ",/"); + } + for(int i = GRADIENT_STEPS; i >= 0 ; i--) { + Color c = interpolateColor(color1, color2, i / (double) GRADIENT_STEPS); + gDef.area("hits" + i, c, null); + } + gDef.line("hits", color2, "Estimated number of page hits"); + gDef.setTimeAxis(TimeAxisUnit.MONTH, 1, TimeAxisUnit.MONTH, 1, "MMM", false); + gDef.setCanvasColor(color1); + RrdGraph graph = new RrdGraph(gDef); + String filename = Util.getJRobinDemoPath("plottable10.png"); + graph.saveAsPNG(filename, 400, 200); + System.out.println("Graph10 saved to " + filename); + } + + private void createGraph11() throws RrdException, IOException { + final int GRADIENT_STEPS = 30; + final Color color1 = Color.YELLOW, color2 = Color.RED; + CubicSplineInterpolator hitsInterpolator = + new CubicSplineInterpolator(SF_TIMESTAMPS, SF_PAGE_HITS); + RrdGraphDef gDef = new RrdGraphDef(SF_TIMESTAMPS[0], SF_TIMESTAMPS[SF_TIMESTAMPS.length - 1]); + gDef.setTitle("Trick graph 6"); + gDef.setTimeAxisLabel("month"); + gDef.setVerticalLabel("hits"); + gDef.datasource("hits", hitsInterpolator); + gDef.datasource("top", "hits", "MAX"); + for(int i = 1; i <= GRADIENT_STEPS; i++) { + gDef.datasource("hits" + i, "hits,top," + i + ",*," + GRADIENT_STEPS + ",/,MIN"); + } + for(int i = GRADIENT_STEPS; i >= 1 ; i--) { + Color c = i % 2 == 0? color1: color2; + gDef.area("hits" + i, c, null); + } + gDef.line("hits", color2, "Estimated number of page hits"); + gDef.setTimeAxis(TimeAxisUnit.MONTH, 1, TimeAxisUnit.MONTH, 1, "MMM", false); + RrdGraph graph = new RrdGraph(gDef); + String filename = Util.getJRobinDemoPath("plottable11.png"); + graph.saveAsPNG(filename, 400, 200); + System.out.println("Graph11 saved to " + filename); + } + + private void createGraph12() throws RrdException, IOException { + final int GRADIENT_STEPS = 15; + final Color color1 = Color.LIGHT_GRAY, color2 = Color.WHITE; + CubicSplineInterpolator hitsInterpolator = + new CubicSplineInterpolator(SF_TIMESTAMPS, SF_PAGE_HITS); + RrdGraphDef gDef = new RrdGraphDef(SF_TIMESTAMPS[0], SF_TIMESTAMPS[SF_TIMESTAMPS.length - 1]); + gDef.setTitle("Trick graph 7"); + gDef.setTimeAxisLabel("month"); + gDef.setVerticalLabel("hits"); + gDef.datasource("hits", hitsInterpolator); + for(int i = GRADIENT_STEPS; i >= 1 ; i--) { + Color c = interpolateColor(color1, color2, i / (double) GRADIENT_STEPS); + gDef.line("hits", c, null, i); + } + gDef.line("hits", color1, "Estimated number of page hits"); + gDef.setTimeAxis(TimeAxisUnit.MONTH, 1, TimeAxisUnit.MONTH, 1, "MMM", false); + RrdGraph graph = new RrdGraph(gDef); + String filename = Util.getJRobinDemoPath("plottable12.png"); + graph.saveAsPNG(filename, 400, 200); + System.out.println("Graph12 saved to " + filename); + } + + private void createGraph13() throws RrdException, IOException { + final int GRADIENT_STEPS = 20; + final double GRADIENT_WIDTH = 2000.0; + final Color color1 = Color.RED, color2 = Color.WHITE; + CubicSplineInterpolator hitsInterpolator = + new CubicSplineInterpolator(SF_TIMESTAMPS, SF_PAGE_HITS); + RrdGraphDef gDef = new RrdGraphDef(SF_TIMESTAMPS[0], SF_TIMESTAMPS[SF_TIMESTAMPS.length - 1]); + gDef.setTitle("Trick graph 8"); + gDef.setTimeAxisLabel("month"); + gDef.setVerticalLabel("hits"); + gDef.datasource("hits", hitsInterpolator); + for(int i = 0; i <= GRADIENT_STEPS; i++) { + gDef.datasource("hits" + i, + "hits," + GRADIENT_WIDTH + "," + i + ",*," + GRADIENT_STEPS + ",/,-,0,MAX"); + } + for(int i = 0; i <= GRADIENT_STEPS; i++) { + gDef.area("hits" + i, interpolateColor(color1, color2, i / (double) GRADIENT_STEPS), null); + } + gDef.setTimeAxis(TimeAxisUnit.MONTH, 1, TimeAxisUnit.MONTH, 1, "MMM", false); + RrdGraph graph = new RrdGraph(gDef); + String filename = Util.getJRobinDemoPath("plottable13.png"); + graph.saveAsPNG(filename, 400, 200); + System.out.println("Graph13 saved to " + filename); + } + + private Color interpolateColor(Color c1, Color c2, double factor) { + int r = c1.getRed() + (int)((c2.getRed() - c1.getRed()) * factor); + int g = c1.getGreen() + (int)((c2.getGreen() - c1.getGreen()) * factor); + int b = c1.getBlue() + (int)((c2.getBlue() - c1.getBlue()) * factor); + return new Color(r, g, b); + } + public static void main(String[] args) throws RrdException, IOException { new PlottableDemo(); |
From: Sasa M. <sa...@us...> - 2004-06-02 08:55:58
|
Update of /cvsroot/jrobin/src/org/jrobin/core In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv10051/org/jrobin/core Modified Files: RrdCacher.java Sample.java Log Message: Faster RRD cacher (5-10%). StressTest should be faster. Index: RrdCacher.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/core/RrdCacher.java,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** RrdCacher.java 20 May 2004 10:34:00 -0000 1.1 --- RrdCacher.java 2 Jun 2004 08:55:48 -0000 1.2 *************** *** 26,106 **** package org.jrobin.core; ! class RrdCacher { ! private Object cache = null; ! boolean setInt(int value) { ! if(isCached(value)) { return false; } else { ! cache = new Integer(value); ! return true; } } ! boolean setLong(long value) { ! if(isCached(value)) { return false; } else { ! cache = new Long(value); ! return true; } } ! boolean setDouble(double value) { ! if(isCached(value)) { return false; } else { ! cache = new Double(value); ! return true; } } ! boolean setString(String value) { ! if(isCached(value)) { return false; } else { ! cache = value; ! return true; } } ! boolean isEmpty() { ! return cache == null; ! } ! ! int getInt() { ! return ((Integer) cache).intValue(); ! } ! ! long getLong() { ! return ((Long) cache).longValue(); ! } ! ! double getDouble() { ! return ((Double) cache).doubleValue(); } ! String getString() { ! return (String) cache; } ! private boolean isCached(int value) { ! return cache != null && getInt() == value; } ! private boolean isCached(long value) { ! return cache != null && getLong() == value; } ! private boolean isCached(double value) { ! return cache != null && getDouble() == value; } - private boolean isCached(String value) { - return cache != null && getString().equals(value); - } } --- 26,95 ---- package org.jrobin.core; ! final class RrdCacher { ! private boolean cached = false; ! private int i; ! private long l; ! private double d; ! private String s; ! final boolean setInt(int value) { ! if (cached && value == i) { return false; } else { ! i = value; ! return cached = true; } } ! final boolean setLong(long value) { ! if(cached && value == l) { return false; } else { ! l = value; ! return cached = true; } } ! final boolean setDouble(double value) { ! if(cached && value == d) { return false; } else { ! d = value; ! return cached = true; } } ! final boolean setString(String value) { ! if(cached && value.equals(s)) { return false; } else { ! s = value; ! return cached = true; } } ! final boolean isEmpty() { ! return !cached; } ! final int getInt() { ! return i; } ! final long getLong() { ! return l; } ! final double getDouble() { ! return d; } ! final String getString() { ! return s; } } Index: Sample.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/core/Sample.java,v retrieving revision 1.8 retrieving revision 1.9 diff -C2 -d -r1.8 -r1.9 *** Sample.java 28 May 2004 10:22:47 -0000 1.8 --- Sample.java 2 Jun 2004 08:55:48 -0000 1.9 *************** *** 99,103 **** return; } ! throw new RrdException("Sample index " + i + " out of bounds"); } --- 99,103 ---- return; } ! throw new RrdException("Sample datasource index " + i + " out of bounds"); } *************** *** 164,190 **** * * @param timeAndValues String made by concatenating sample timestamp with corresponding ! * data source values delmited with colons. For example: ! * <code>1005234132:12.2:35.6:U:24.5</code> * @throws RrdException Thrown if too many datasource values are supplied */ public void set(String timeAndValues) throws RrdException { ! StringTokenizer st = new StringTokenizer(timeAndValues, ":", false); ! int numTokens = st.countTokens(); ! String[] tokens = new String[numTokens]; ! for(int i = 0; i < numTokens; i++) { ! tokens[i] = st.nextToken(); } ! long time = Long.parseLong(tokens[0]); ! double[] values = new double[numTokens - 1]; ! for(int i = 0; i < numTokens - 1; i++) { try { ! values[i] = Double.parseDouble(tokens[i + 1]); } ! catch(NumberFormatException nfe) { ! values[i] = Double.NaN; } } - setTime(time); - setValues(values); } --- 164,204 ---- * * @param timeAndValues String made by concatenating sample timestamp with corresponding ! * data source values delmited with colons. For example:<p> ! * <pre> ! * 1005234132:12.2:35.6:U:24.5 ! * NOW:12.2:35.6:U:24.5 ! * </pre> ! * 'N' stands for the current timestamp (can be replaced with 'NOW')<p> ! * Method will throw an exception if timestamp is invalid (cannot be parsed as Long, and is not 'N' ! * or 'NOW'). Datasource value which cannot be parsed as 'double' will be silently set to NaN.<p> * @throws RrdException Thrown if too many datasource values are supplied */ public void set(String timeAndValues) throws RrdException { ! StringTokenizer tokenizer = new StringTokenizer(timeAndValues, ":", false); ! int n = tokenizer.countTokens(); ! if(n > values.length + 1) { ! throw new RrdException("Invalid number of values specified (found " + ! values.length + ", " + dsNames.length + " allowed)"); } ! String timeToken = tokenizer.nextToken(); ! try { ! time = Long.parseLong(timeToken); ! } ! catch(NumberFormatException nfe) { ! if(timeToken.equalsIgnoreCase("N") || timeToken.equalsIgnoreCase("NOW")) { ! time = Util.getTime(); ! } ! else { ! throw new RrdException("Invalid sample timestamp: " + timeToken); ! } ! } ! for(int i = 0; tokenizer.hasMoreTokens(); i++) { try { ! values[i] = Double.parseDouble(tokenizer.nextToken()); } ! catch (NumberFormatException nfe) { ! // NOP, value is already set to NaN } } } *************** *** 210,215 **** * </pre> * @param timeAndValues String made by concatenating sample timestamp with corresponding ! * data source values delmited with colons. For example: ! * <code>1005234132:12.2:35.6:U:24.5</code> * * @throws IOException Thrown in case of I/O error. --- 224,230 ---- * </pre> * @param timeAndValues String made by concatenating sample timestamp with corresponding ! * data source values delmited with colons. For example:<br> ! * <code>1005234132:12.2:35.6:U:24.5</code><br> ! * <code>NOW:12.2:35.6:U:24.5</code> * * @throws IOException Thrown in case of I/O error. |
From: Sasa M. <sa...@us...> - 2004-06-02 07:20:26
|
Update of /cvsroot/jrobin/src/org/jrobin/core In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv25254/org/jrobin/core Modified Files: RrdBackend.java RrdNioBackend.java Log Message: Nice plottable demo, with five cute graphs. Minor javadoc changes. Index: RrdBackend.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/core/RrdBackend.java,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** RrdBackend.java 1 Jun 2004 14:41:01 -0000 1.5 --- RrdBackend.java 2 Jun 2004 07:20:12 -0000 1.6 *************** *** 137,141 **** /** ! * Closes the storage. Calls sync() implicitly. * @throws IOException Thrown in case of I/O error */ --- 137,143 ---- /** ! * Closes the underlying storage. Calls sync() implicitly. ! * In other words, you don't have to call sync() before close() in order to preserve ! * data cached in memory. * @throws IOException Thrown in case of I/O error */ Index: RrdNioBackend.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/core/RrdNioBackend.java,v retrieving revision 1.6 retrieving revision 1.7 diff -C2 -d -r1.6 -r1.7 *** RrdNioBackend.java 1 Jun 2004 14:41:01 -0000 1.6 --- RrdNioBackend.java 2 Jun 2004 07:20:13 -0000 1.7 *************** *** 34,38 **** /** * JRobin backend which is used to store RRD data to ordinary files on the disk ! * by using java.nio.* package. */ public class RrdNioBackend extends RrdFileBackend { --- 34,38 ---- /** * JRobin backend which is used to store RRD data to ordinary files on the disk ! * by using java.nio.* package. This is the default backend engine since JRobin 1.4.0. */ public class RrdNioBackend extends RrdFileBackend { *************** *** 123,126 **** --- 123,131 ---- } + /** + * Method called by the framework immediatelly before RRD update operation starts. This method + * will synchronize in-memory cache with the disk content if synchronization mode is set to + * {@link RrdNioBackendFactory#SYNC_BEFOREUPDATE}. Otherwise it does nothing. + */ protected void beforeUpdate() { if(syncMode == RrdNioBackendFactory.SYNC_BEFOREUPDATE) { *************** *** 129,132 **** --- 134,142 ---- } + /** + * Method called by the framework immediatelly after RRD update operation finishes. This method + * will synchronize in-memory cache with the disk content if synchronization mode is set to + * {@link RrdNioBackendFactory#SYNC_AFTERUPDATE}. Otherwise it does nothing. + */ protected void afterUpdate() { if(syncMode == RrdNioBackendFactory.SYNC_AFTERUPDATE) { *************** *** 135,138 **** --- 145,153 ---- } + /** + * Method called by the framework immediatelly before RRD fetch operation starts. This method + * will synchronize in-memory cache with the disk content if synchronization mode is set to + * {@link RrdNioBackendFactory#SYNC_BEFOREFETCH}. Otherwise it does nothing. + */ protected void beforeFetch() { if(syncMode == RrdNioBackendFactory.SYNC_BEFOREFETCH) { *************** *** 141,144 **** --- 156,164 ---- } + /** + * Method called by the framework immediatelly after RRD fetch operation finishes. This method + * will synchronize in-memory cache with the disk content if synchronization mode is set to + * {@link RrdNioBackendFactory#SYNC_AFTERFETCH}. Otherwise it does nothing. + */ protected void afterFetch() { if(syncMode == RrdNioBackendFactory.SYNC_AFTERFETCH) { |
From: Sasa M. <sa...@us...> - 2004-06-02 07:20:22
|
Update of /cvsroot/jrobin/src In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv25254 Modified Files: PlottableDemo.java Log Message: Nice plottable demo, with five cute graphs. Minor javadoc changes. Index: PlottableDemo.java =================================================================== RCS file: /cvsroot/jrobin/src/PlottableDemo.java,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** PlottableDemo.java 31 May 2004 09:04:50 -0000 1.5 --- PlottableDemo.java 2 Jun 2004 07:19:57 -0000 1.6 *************** *** 1,3 **** ! import org.jrobin.graph.*; import org.jrobin.core.RrdException; --- 1,27 ---- ! /* ============================================================ ! * 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.graph.*; import org.jrobin.core.RrdException; *************** *** 11,22 **** class PlottableDemo { ! static double[] SF_DOWNLOAD_COUNT = { ! 0, 0, 13, 34, 76, 72, 255, 144, 135, 194, 358, 304, 247 }; ! static double[] SF_PAGE_HITS = { ! 0, 1072, 517, 979, 2132, 2532, 5515, 3519, 3500, 4942, 7858, 7797, 5509 }; ! static GregorianCalendar[] SF_TIMESTAMPS = new GregorianCalendar[SF_DOWNLOAD_COUNT.length]; ! static Date SF_START_DATE = new GregorianCalendar(2003, 4, 1).getTime(); // May 1st 2004. static { --- 35,48 ---- class PlottableDemo { ! static final double[] SF_DOWNLOAD_COUNT = { ! 0, 0, 13, 34, 76, 72, 255, 144, 135, 194, 358, 304, 293 }; ! static final double[] SF_PAGE_HITS = { ! 0, 1072, 517, 979, 2132, 2532, 5515, 3519, 3500, 4942, 7858, 7797, 6570 }; ! static final GregorianCalendar[] SF_TIMESTAMPS = ! new GregorianCalendar[SF_DOWNLOAD_COUNT.length]; ! static final Date SF_START_DATE = ! new GregorianCalendar(2003, 4, 1).getTime(); // May 1st 2004. static { *************** *** 146,150 **** LinearInterpolator downloadsInterpolator = new LinearInterpolator(SF_TIMESTAMPS, SF_DOWNLOAD_COUNT); ! RrdGraphDef gDef = new RrdGraphDef(SF_TIMESTAMPS[0], SF_TIMESTAMPS[SF_TIMESTAMPS.length - 1]); gDef.setTitle("JRobin statistics at SourceForge"); gDef.setTimeAxisLabel("month"); --- 172,177 ---- LinearInterpolator downloadsInterpolator = new LinearInterpolator(SF_TIMESTAMPS, SF_DOWNLOAD_COUNT); ! RrdGraphDef gDef = new RrdGraphDef(SF_TIMESTAMPS[0], ! SF_TIMESTAMPS[SF_TIMESTAMPS.length - 1]); gDef.setTitle("JRobin statistics at SourceForge"); gDef.setTimeAxisLabel("month"); |
Update of /cvsroot/jrobin/src/org/jrobin/core In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv2815/org/jrobin/core Modified Files: RrdBackend.java RrdBackendFactory.java RrdDb.java RrdFileBackend.java RrdFileBackendFactory.java RrdNioBackend.java RrdNioBackendFactory.java Log Message: Default factory switched to NIO. Minor code changes Index: RrdBackend.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/core/RrdBackend.java,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** RrdBackend.java 30 May 2004 10:06:47 -0000 1.4 --- RrdBackend.java 1 Jun 2004 14:41:01 -0000 1.5 *************** *** 35,41 **** * <ul> * <li>{@link RrdFileBackend}: objects of this class are created from the ! * {@link RrdFileBackendFactory} class. This is the default backend used in all ! * JRobin releases. It uses java.io.* package and RandomAccessFile class to store ! * RRD data in files on the disk. * * <li>{@link RrdNioBackend}: objects of this class are created from the --- 35,41 ---- * <ul> * <li>{@link RrdFileBackend}: objects of this class are created from the ! * {@link RrdFileBackendFactory} class. This was the default backend used in all ! * JRobin releases prior to 1.4.0. It uses java.io.* package and ! * RandomAccessFile class to store RRD data in files on the disk. * * <li>{@link RrdNioBackend}: objects of this class are created from the *************** *** 43,47 **** * classes (mapped ByteBuffer) to store RRD data in files on the disk. This backend is fast, very fast, * but consumes a lot of memory (borrowed not from the JVM but from the underlying operating system ! * directly). * * <li>{@link RrdMemoryBackend}: objects of this class are created from the --- 43,47 ---- * classes (mapped ByteBuffer) to store RRD data in files on the disk. This backend is fast, very fast, * but consumes a lot of memory (borrowed not from the JVM but from the underlying operating system ! * directly). <b>This is the default backend used in JRobin since 1.4.0 release.</b> * * <li>{@link RrdMemoryBackend}: objects of this class are created from the *************** *** 137,144 **** /** ! * Closes the storage. * @throws IOException Thrown in case of I/O error */ ! public abstract void close() throws IOException; /** --- 137,146 ---- /** ! * Closes the storage. Calls sync() implicitly. * @throws IOException Thrown in case of I/O error */ ! public void close() throws IOException { ! sync(); ! } /** Index: RrdNioBackend.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/core/RrdNioBackend.java,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** RrdNioBackend.java 31 May 2004 09:04:50 -0000 1.5 --- RrdNioBackend.java 1 Jun 2004 14:41:01 -0000 1.6 *************** *** 117,126 **** */ protected void sync() { - //long t1 = System.currentTimeMillis(); synchronized(byteBuffer) { byteBuffer.force(); } - //long t2 = System.currentTimeMillis(); - //System.out.println("** SYNC ** " + (t2 - t1) + " millis"); } --- 117,124 ---- */ protected void sync() { synchronized(byteBuffer) { + // System.out.println("** SYNC **"); byteBuffer.force(); } } Index: RrdBackendFactory.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/core/RrdBackendFactory.java,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** RrdBackendFactory.java 25 May 2004 11:35:58 -0000 1.5 --- RrdBackendFactory.java 1 Jun 2004 14:41:01 -0000 1.6 *************** *** 40,50 **** * <ul> * <li>{@link RrdFileBackend}: objects of this class are created from the ! * {@link RrdFileBackendFactory} class. This is the default backend used in all ! * JRobin releases. It uses java.io.* package and RandomAccessFile class to store * RRD data in files on the disk. * * <li>{@link RrdNioBackend}: objects of this class are created from the * {@link RrdNioBackendFactory} class. The backend uses java.io.* and java.nio.* ! * classes (mapped ByteBuffer) to store RRD data in files on the disk. * * <li>{@link RrdMemoryBackend}: objects of this class are created from the --- 40,51 ---- * <ul> * <li>{@link RrdFileBackend}: objects of this class are created from the ! * {@link RrdFileBackendFactory} class. This was the default backend used in all ! * JRobin releases before 1.4.0 release. It uses java.io.* package and RandomAccessFile class to store * RRD data in files on the disk. * * <li>{@link RrdNioBackend}: objects of this class are created from the * {@link RrdNioBackendFactory} class. The backend uses java.io.* and java.nio.* ! * classes (mapped ByteBuffer) to store RRD data in files on the disk. This is the default backend ! * since 1.4.0 release. * * <li>{@link RrdMemoryBackend}: objects of this class are created from the *************** *** 73,77 **** // Here is the default backend factory ! defaultFactory = fileFactory; } catch (RrdException e) { --- 74,78 ---- // Here is the default backend factory ! defaultFactory = nioFactory; } catch (RrdException e) { *************** *** 124,127 **** --- 125,141 ---- /** + * Registers new (custom) backend factory within the JRobin framework and sets this + * factory as the default. + * @param factory Factory to be registered and set as default + * @throws RrdException Thrown if the name of the specified factory is already + * used. + */ + public static synchronized void registerAndSetAsDefaultFactory(RrdBackendFactory factory) + throws RrdException { + registerFactory(factory); + setDefaultFactory(factory.getFactoryName()); + } + + /** * Returns the defaul backend factory. This factory is used to construct * {@link RrdDb} objects if no factory is specified in the RrdDb constructor. Index: RrdFileBackend.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/core/RrdFileBackend.java,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** RrdFileBackend.java 28 May 2004 10:22:47 -0000 1.3 --- RrdFileBackend.java 1 Jun 2004 14:41:01 -0000 1.4 *************** *** 33,37 **** /** ! * Default JRobin backend which is used to store RRD data to ordinary files on the disk.<p> * * This backend is based on the RandomAccessFile class (java.io.* package). --- 33,38 ---- /** ! * JRobin backend which is used to store RRD data to ordinary files on the disk. This was the ! * default factory before 1.4.0 version<p> * * This backend is based on the RandomAccessFile class (java.io.* package). *************** *** 82,86 **** */ public void close() throws IOException { ! sync(); unlockFile(); file.close(); --- 83,87 ---- */ public void close() throws IOException { ! super.close(); // calls sync() unlockFile(); file.close(); Index: RrdFileBackendFactory.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/core/RrdFileBackendFactory.java,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** RrdFileBackendFactory.java 25 May 2004 11:35:58 -0000 1.3 --- RrdFileBackendFactory.java 1 Jun 2004 14:41:01 -0000 1.4 *************** *** 30,35 **** /** ! * Factory class which creates actual {@link RrdFileBackend} objects. This is the default ! * backend factory in JRobin. */ public class RrdFileBackendFactory extends RrdBackendFactory { --- 30,35 ---- /** ! * Factory class which creates actual {@link RrdFileBackend} objects. This was the default ! * backend factory in JRobin before 1.4.0 release. */ public class RrdFileBackendFactory extends RrdBackendFactory { Index: RrdNioBackendFactory.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/core/RrdNioBackendFactory.java,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** RrdNioBackendFactory.java 31 May 2004 09:04:51 -0000 1.5 --- RrdNioBackendFactory.java 1 Jun 2004 14:41:01 -0000 1.6 *************** *** 29,33 **** /** ! * Factory class which creates actual {@link RrdNioBackend} objects. */ public class RrdNioBackendFactory extends RrdFileBackendFactory{ --- 29,34 ---- /** ! * Factory class which creates actual {@link RrdNioBackend} objects. This is the default factory since ! * 1.4.0 version */ public class RrdNioBackendFactory extends RrdFileBackendFactory{ Index: RrdDb.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/core/RrdDb.java,v retrieving revision 1.18 retrieving revision 1.19 diff -C2 -d -r1.18 -r1.19 *** RrdDb.java 30 May 2004 10:06:47 -0000 1.18 --- RrdDb.java 1 Jun 2004 14:41:01 -0000 1.19 *************** *** 89,93 **** /** * <p>Constructor used to create new RRD object from the definition. This RRD object will be backed ! * with a storage (backend) of the default type. Initially, storage type defaults to "FILE" * (RRD bytes will be put in a file on the disk). Default storage type can be changed with a static * {@link RrdBackendFactory#setDefaultFactory(String)} method call.</p> --- 89,93 ---- /** * <p>Constructor used to create new RRD object from the definition. This RRD object will be backed ! * with a storage (backend) of the default type. Initially, storage type defaults to "NIO" * (RRD bytes will be put in a file on the disk). Default storage type can be changed with a static * {@link RrdBackendFactory#setDefaultFactory(String)} method call.</p> |
From: Sasa M. <sa...@us...> - 2004-06-01 14:41:09
|
Update of /cvsroot/jrobin/src In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv2815 Modified Files: Demo.java Log Message: Default factory switched to NIO. Minor code changes Index: Demo.java =================================================================== RCS file: /cvsroot/jrobin/src/Demo.java,v retrieving revision 1.18 retrieving revision 1.19 diff -C2 -d -r1.18 -r1.19 *** Demo.java 30 May 2004 10:06:46 -0000 1.18 --- Demo.java 1 Jun 2004 14:41:01 -0000 1.19 *************** *** 36,40 **** class Demo { ! static final String FACTORY_NAME = "FILE"; static final long SEED = 1909752002L; --- 36,40 ---- class Demo { ! // static final String FACTORY_NAME = "NIO"; static final long SEED = 1909752002L; *************** *** 47,51 **** public static void main(String[] args) throws RrdException, IOException { ! RrdDb.setDefaultFactory(FACTORY_NAME); // setup println("== Starting demo"); --- 47,51 ---- public static void main(String[] args) throws RrdException, IOException { ! // RrdDb.setDefaultFactory(FACTORY_NAME); // setup println("== Starting demo"); |
From: Arne V. <cob...@us...> - 2004-05-31 17:13:30
|
Update of /cvsroot/jrobin/src/org/jrobin/graph In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv12212/org/jrobin/graph Modified Files: FetchSource.java Grapher.java RrdGraphDef.java Log Message: JRobin 1.4.0 - Added setResolution() option - Added setLowerLimit() option Index: Grapher.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/graph/Grapher.java,v retrieving revision 1.11 retrieving revision 1.12 diff -C2 -d -r1.11 -r1.12 *** Grapher.java 30 May 2004 19:49:56 -0000 1.11 --- Grapher.java 31 May 2004 17:13:21 -0000 1.12 *************** *** 363,367 **** // Fetch all required datasources ! ve = src.fetch( rrd, startTime, endTime ); varList = ve.getNames(); --- 363,367 ---- // Fetch all required datasources ! ve = src.fetch( rrd, startTime, endTime, graphDef.getResolution() ); varList = ve.getNames(); *************** *** 587,596 **** double val; double[] tmpSeries = new double[numPoints]; ! GridRange range = graphDef.getGridRange(); ! boolean rigid = ( range != null ? range.isRigid() : false ); ! double lowerValue = ( range != null ? range.getLowerValue() : Double.MAX_VALUE ); ! double upperValue = ( range != null ? range.getUpperValue() : Double.MIN_VALUE ); ! // For autoscale, detect lower and upper limit of values PlotDef[] plotDefs = graphDef.getPlotDefs(); --- 587,606 ---- double val; double[] tmpSeries = new double[numPoints]; ! ! boolean rigid = false; ! double lowerValue = Double.MAX_VALUE; ! double upperValue = Double.MIN_VALUE; ! GridRange range = graphDef.getGridRange(); ! if ( range != null ) ! { ! rigid = range.isRigid(); ! lowerValue = range.getLowerValue(); ! upperValue = range.getUpperValue(); ! ! if ( Double.isNaN(lowerValue) ) lowerValue = Double.MAX_VALUE; ! if ( Double.isNaN(upperValue) ) upperValue = Double.MIN_VALUE; ! } ! // For autoscale, detect lower and upper limit of values PlotDef[] plotDefs = graphDef.getPlotDefs(); Index: FetchSource.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/graph/FetchSource.java,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** FetchSource.java 30 May 2004 19:49:56 -0000 1.4 --- FetchSource.java 31 May 2004 17:13:21 -0000 1.5 *************** *** 147,155 **** * @param startTime Start time of the given timespan. * @param endTime End time of the given timespan. * @return A <code>ValueExtractor</code> object holding all fetched data. * @throws IOException Thrown in case of fetching I/O error. * @throws RrdException Thrown in case of a JRobin specific error. */ ! protected ValueExtractor fetch ( RrdDb rrd, long startTime, long endTime ) throws IOException, RrdException { int dsSize = 0; --- 147,156 ---- * @param startTime Start time of the given timespan. * @param endTime End time of the given timespan. + * @param resolution Resolution for the fetch request. * @return A <code>ValueExtractor</code> object holding all fetched data. * @throws IOException Thrown in case of fetching I/O error. * @throws RrdException Thrown in case of a JRobin specific error. */ ! protected ValueExtractor fetch ( RrdDb rrd, long startTime, long endTime, long resolution ) throws IOException, RrdException { int dsSize = 0; *************** *** 178,182 **** // Fetch datasources ! FetchRequest request = rrd.createFetchRequest( cfNames[i], startTime, endTime + rrdStep); request.setFilter( dsNames ); --- 179,183 ---- // Fetch datasources ! FetchRequest request = rrd.createFetchRequest( cfNames[i], startTime, endTime + rrdStep, resolution ); request.setFilter( dsNames ); Index: RrdGraphDef.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/graph/RrdGraphDef.java,v retrieving revision 1.13 retrieving revision 1.14 diff -C2 -d -r1.13 -r1.14 *** RrdGraphDef.java 31 May 2004 08:01:47 -0000 1.13 --- RrdGraphDef.java 31 May 2004 17:13:21 -0000 1.14 *************** *** 63,67 **** private long endTime = Util.getTime(); // default time span of the last 24 hours private long startTime = Util.getTime() - 86400L; ! private Title title = null; // no title private String valueAxisLabel = null; // no vertical label --- 63,68 ---- private long endTime = Util.getTime(); // default time span of the last 24 hours private long startTime = Util.getTime() - 86400L; ! private long resolution = 1; // resolution to fetch from the RRD databases ! private Title title = null; // no title private String valueAxisLabel = null; // no vertical label *************** *** 207,211 **** setTimePeriod( start.getTime(), end.getTime() ); } ! /** * Sets graph title. --- 208,222 ---- setTimePeriod( start.getTime(), end.getTime() ); } ! ! /** ! * Sets the resolution with which data will be fetched from the RRD sources. ! * JRobin will try to match the requested resolution as closely as possible. ! * @param resolution Resolution (data step) in seconds. ! */ ! public void setResolution( long resolution ) ! { ! this.resolution = resolution; ! } ! /** * Sets graph title. *************** *** 548,551 **** --- 559,564 ---- /** * Sets value range that will be presented in the graph. If not set, graph limits will be autoscaled. + * If you wish to specify one limit but leave the other auto-scaled, specify the value as Double.NaN + * fot the limit that should be auto-scaled. * @param lower Lower limit. * @param upper Upper limit. *************** *** 553,557 **** */ ! public void setGridRange(double lower, double upper, boolean rigid) { gridRange = new GridRange( lower, upper, rigid ); --- 566,570 ---- */ ! public void setGridRange( double lower, double upper, boolean rigid ) { gridRange = new GridRange( lower, upper, rigid ); *************** *** 559,562 **** --- 572,585 ---- /** + * This sets the lower limit of the grid to the specified value {@see setGridRange}. + * This is the equivalent of: <code>setGridRange( lower, Double.NaN, false );</code> + * @param lower Lower limit. + */ + public void setLowerLimit( double lower ) + { + gridRange = new GridRange( lower, Double.NaN, false ); + } + + /** * This sets the grid and labels on the Y axis. * Minor grid lines appear at <code>gridStep</code>, major grid lines accompanied by a label *************** *** 1139,1143 **** return endTime; } ! protected Title getTitle() { return title; --- 1162,1170 ---- return endTime; } ! ! protected long getResolution() { ! return resolution; ! } ! protected Title getTitle() { return title; |
From: Sasa M. <sa...@us...> - 2004-05-31 09:05:30
|
Update of /cvsroot/jrobin/src/org/jrobin/core In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv21037/org/jrobin/core Modified Files: RrdNioBackend.java RrdNioBackendFactory.java Log Message: Final changes in NIO Index: RrdNioBackend.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/core/RrdNioBackend.java,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** RrdNioBackend.java 31 May 2004 08:01:46 -0000 1.4 --- RrdNioBackend.java 31 May 2004 09:04:50 -0000 1.5 *************** *** 117,123 **** --- 117,126 ---- */ protected void sync() { + //long t1 = System.currentTimeMillis(); synchronized(byteBuffer) { byteBuffer.force(); } + //long t2 = System.currentTimeMillis(); + //System.out.println("** SYNC ** " + (t2 - t1) + " millis"); } Index: RrdNioBackendFactory.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/core/RrdNioBackendFactory.java,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** RrdNioBackendFactory.java 30 May 2004 10:16:00 -0000 1.4 --- RrdNioBackendFactory.java 31 May 2004 09:04:51 -0000 1.5 *************** *** 47,52 **** /** See {@link #setSyncMode(int) for explanation } */ public static final int SYNC_BACKGROUND = 5; ! /** See {@link #setSyncPeriod(int)} for explanation */ ! public static final int DEFAULT_SYNC_PERIOD = 60; // seconds private static int syncMode = SYNC_BACKGROUND; --- 47,57 ---- /** See {@link #setSyncMode(int) for explanation } */ public static final int SYNC_BACKGROUND = 5; ! /** ! * Period in seconds between consecutive synchronizations when ! * sync-mode is set to SYNC_BACKGROUND. By default in-memory cache will be ! * transferred to the disc every 300 seconds (5 minutes). Default value can be ! * changed via {@link #setSyncPeriod(int)} method. ! */ ! public static final int DEFAULT_SYNC_PERIOD = 300; // seconds private static int syncMode = SYNC_BACKGROUND; *************** *** 92,96 **** /** * Returns time between two consecutive background synchronizations. If not changed via ! * {@link #setSyncPeriod(int)} method call, defaults to DEFAULT_SYNC_PERIOD (60 seconds). * See {@link #setSyncPeriod(int)} for more information. * @return Time in seconds between consecutive background synchronizations. --- 97,101 ---- /** * Returns time between two consecutive background synchronizations. If not changed via ! * {@link #setSyncPeriod(int)} method call, defaults to {@link #DEFAULT_SYNC_PERIOD}. * See {@link #setSyncPeriod(int)} for more information. * @return Time in seconds between consecutive background synchronizations. |
From: Sasa M. <sa...@us...> - 2004-05-31 09:05:30
|
Update of /cvsroot/jrobin/src In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv21037 Modified Files: PlottableDemo.java Log Message: Final changes in NIO Index: PlottableDemo.java =================================================================== RCS file: /cvsroot/jrobin/src/PlottableDemo.java,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** PlottableDemo.java 26 Feb 2004 12:24:45 -0000 1.4 --- PlottableDemo.java 31 May 2004 09:04:50 -0000 1.5 *************** *** 8,16 **** --- 8,38 ---- import java.util.Date; import java.util.GregorianCalendar; + import java.util.Calendar; class PlottableDemo { + static double[] SF_DOWNLOAD_COUNT = { + 0, 0, 13, 34, 76, 72, 255, 144, 135, 194, 358, 304, 247 + }; + static double[] SF_PAGE_HITS = { + 0, 1072, 517, 979, 2132, 2532, 5515, 3519, 3500, 4942, 7858, 7797, 5509 + }; + static GregorianCalendar[] SF_TIMESTAMPS = new GregorianCalendar[SF_DOWNLOAD_COUNT.length]; + static Date SF_START_DATE = new GregorianCalendar(2003, 4, 1).getTime(); // May 1st 2004. + + static { + for(int i = 0; i < SF_TIMESTAMPS.length; i++) { + GregorianCalendar gc = new GregorianCalendar(); + gc.setTime(SF_START_DATE); + gc.add(Calendar.MONTH, i); + SF_TIMESTAMPS[i] = gc; + } + } + private PlottableDemo() throws RrdException, IOException { createGraph1(); createGraph2(); + createGraph3(); + createGraph4(); + createGraph5(); } *************** *** 83,86 **** --- 105,169 ---- } + private void createGraph3() throws RrdException, IOException { + LinearInterpolator linear = new LinearInterpolator(SF_TIMESTAMPS, SF_PAGE_HITS); + RrdGraphDef gDef = new RrdGraphDef(SF_TIMESTAMPS[0], SF_TIMESTAMPS[SF_TIMESTAMPS.length - 1]); + gDef.setTitle("JRobin page hits per month"); + gDef.setTimeAxisLabel("month"); + gDef.setVerticalLabel("page hits"); + gDef.datasource("linear", linear); + gDef.area("linear", Color.GREEN, null); + gDef.line("linear", Color.RED, "page hits@L", 2); + gDef.vrule(new GregorianCalendar(2004, 0, 1), Color.BLUE, null, 3); + gDef.setTimeAxis(TimeAxisUnit.MONTH, 1, TimeAxisUnit.MONTH, 1, "MMM", false); + gDef.comment("Data provided by SourceForge.net@r"); + RrdGraph graph = new RrdGraph(gDef); + String filename = Util.getJRobinDemoPath("plottable3.png"); + graph.saveAsPNG(filename, 400, 200); + System.out.println("Graph3 saved to " + filename); + } + + private void createGraph4() throws RrdException, IOException { + LinearInterpolator linear = new LinearInterpolator(SF_TIMESTAMPS, SF_DOWNLOAD_COUNT); + RrdGraphDef gDef = new RrdGraphDef(SF_TIMESTAMPS[0], SF_TIMESTAMPS[SF_TIMESTAMPS.length - 1]); + gDef.setTitle("JRobin download count per month"); + gDef.setTimeAxisLabel("month"); + gDef.setVerticalLabel("download count"); + gDef.datasource("linear", linear); + gDef.area("linear", Color.GREEN, null); + gDef.line("linear", Color.RED, "download count@L", 2); + gDef.vrule(new GregorianCalendar(2004, 0, 1), Color.BLUE, null, 3); + gDef.setTimeAxis(TimeAxisUnit.MONTH, 1, TimeAxisUnit.MONTH, 1, "MMM", false); + gDef.comment("Data provided by SourceForge.net@r"); + RrdGraph graph = new RrdGraph(gDef); + String filename = Util.getJRobinDemoPath("plottable4.png"); + graph.saveAsPNG(filename, 400, 200); + System.out.println("Graph4 saved to " + filename); + } + + private void createGraph5() throws RrdException, IOException { + LinearInterpolator hitsInterpolator = + new LinearInterpolator(SF_TIMESTAMPS, SF_PAGE_HITS); + LinearInterpolator downloadsInterpolator = + new LinearInterpolator(SF_TIMESTAMPS, SF_DOWNLOAD_COUNT); + RrdGraphDef gDef = new RrdGraphDef(SF_TIMESTAMPS[0], SF_TIMESTAMPS[SF_TIMESTAMPS.length - 1]); + gDef.setTitle("JRobin statistics at SourceForge"); + gDef.setTimeAxisLabel("month"); + gDef.setVerticalLabel("hits/downloads"); + gDef.datasource("hits", hitsInterpolator); + gDef.datasource("downloads", downloadsInterpolator); + gDef.datasource("ratio", "downloads,0,EQ,UNKN,hits,downloads,/,IF"); + gDef.area("hits", Color.GREEN, null); + gDef.line("hits", Color.RED, "page hits", 2); + gDef.area("downloads", Color.MAGENTA, "downloads@L"); + gDef.vrule(new GregorianCalendar(2004, 0, 1), Color.BLUE, null, 3); + gDef.setTimeAxis(TimeAxisUnit.MONTH, 1, TimeAxisUnit.MONTH, 1, "MMM", false); + gDef.gprint("ratio", "AVERAGE", "Average number of page hits per download: @0@r"); + gDef.comment("Data provided by SourceForge.net@r"); + RrdGraph graph = new RrdGraph(gDef); + String filename = Util.getJRobinDemoPath("plottable5.png"); + graph.saveAsPNG(filename, 400, 200); + System.out.println("Graph5 saved to " + filename); + } + public static void main(String[] args) throws RrdException, IOException { new PlottableDemo(); |
From: Sasa M. <sa...@us...> - 2004-05-31 09:05:07
|
Update of /cvsroot/jrobin/src/org/jrobin/mrtg/server In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv21037/org/jrobin/mrtg/server Modified Files: Server.java Log Message: Final changes in NIO Index: Server.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/mrtg/server/Server.java,v retrieving revision 1.12 retrieving revision 1.13 diff -C2 -d -r1.12 -r1.13 *** Server.java 10 Apr 2004 10:31:30 -0000 1.12 --- Server.java 31 May 2004 09:04:54 -0000 1.13 *************** *** 27,30 **** --- 27,31 ---- import org.jrobin.core.RrdDb; import org.jrobin.core.RrdDbPool; + import org.jrobin.core.RrdException; import org.jrobin.mrtg.MrtgException; import org.jrobin.mrtg.MrtgConstants; *************** *** 76,79 **** --- 77,86 ---- throw new MrtgException("Cannot start Server, already started"); } + // set default backend factory + try { + RrdDb.setDefaultFactory(BACKEND_FACTORY_NAME); + } catch (RrdException e) { + throw new MrtgException("Inavlide backend factory (" + BACKEND_FACTORY_NAME + ")"); + } // create template files try { |
From: Sasa M. <sa...@us...> - 2004-05-31 09:05:07
|
Update of /cvsroot/jrobin/src/org/jrobin/mrtg In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv21037/org/jrobin/mrtg Modified Files: MrtgConstants.java Log Message: Final changes in NIO Index: MrtgConstants.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/mrtg/MrtgConstants.java,v retrieving revision 1.8 retrieving revision 1.9 diff -C2 -d -r1.8 -r1.9 *** MrtgConstants.java 25 May 2004 07:49:26 -0000 1.8 --- MrtgConstants.java 31 May 2004 09:04:51 -0000 1.9 *************** *** 27,30 **** --- 27,36 ---- public interface MrtgConstants { + // backend factory to be used + // WARNING: Change this to "FILE" if you run the Server app + // on a machine with less RAM. "NIO" consumes a lot of memory + // but it's fast, very fast. + String BACKEND_FACTORY_NAME = "NIO"; + // turn debugging on/off boolean DEBUG = false; |
From: Sasa M. <sa...@us...> - 2004-05-31 08:01:58
|
Update of /cvsroot/jrobin/src/org/jrobin/core In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv8988/org/jrobin/core Modified Files: RrdNioBackend.java Log Message: Minor changes in NIO, fixed single javadoc error in RrdGraphDef class Index: RrdNioBackend.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/core/RrdNioBackend.java,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** RrdNioBackend.java 30 May 2004 10:06:48 -0000 1.3 --- RrdNioBackend.java 31 May 2004 08:01:46 -0000 1.4 *************** *** 37,44 **** */ public class RrdNioBackend extends RrdFileBackend { private int syncMode; MappedByteBuffer byteBuffer; ! ! private Timer syncTimer; RrdNioBackend(String path, boolean readOnly, int lockMode, int syncMode, int syncPeriod) --- 37,45 ---- */ public class RrdNioBackend extends RrdFileBackend { + private static final Timer syncTimer = new Timer(true); + private int syncMode; MappedByteBuffer byteBuffer; ! private TimerTask syncTask; RrdNioBackend(String path, boolean readOnly, int lockMode, int syncMode, int syncPeriod) *************** *** 55,64 **** private void createSyncTask(int syncPeriod) { ! TimerTask syncTask = new TimerTask() { public void run() { sync(); } }; - syncTimer = new Timer(true); syncTimer.schedule(syncTask, syncPeriod * 1000L, syncPeriod * 1000L); } --- 56,64 ---- private void createSyncTask(int syncPeriod) { ! syncTask = new TimerTask() { public void run() { sync(); } }; syncTimer.schedule(syncTask, syncPeriod * 1000L, syncPeriod * 1000L); } *************** *** 104,109 **** */ public void close() throws IOException { ! if(syncTimer != null) { ! syncTimer.cancel(); } super.close(); // calls sync() --- 104,109 ---- */ public void close() throws IOException { ! if(syncTask != null) { ! syncTask.cancel(); } super.close(); // calls sync() |
From: Sasa M. <sa...@us...> - 2004-05-31 08:01:58
|
Update of /cvsroot/jrobin/src/org/jrobin/graph In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv8988/org/jrobin/graph Modified Files: RrdGraphDef.java Log Message: Minor changes in NIO, fixed single javadoc error in RrdGraphDef class Index: RrdGraphDef.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/graph/RrdGraphDef.java,v retrieving revision 1.12 retrieving revision 1.13 diff -C2 -d -r1.12 -r1.13 *** RrdGraphDef.java 30 May 2004 19:49:56 -0000 1.12 --- RrdGraphDef.java 31 May 2004 08:01:47 -0000 1.13 *************** *** 1098,1102 **** * Exports RrdGraphDef (graph definition) object in XML format to string. * Generated code can be parsed with {@link RrdGraphDefTemplate} class ! * {@see exportXmlTemplate). * * @return String representing graph definition in XML format --- 1098,1102 ---- * Exports RrdGraphDef (graph definition) object in XML format to string. * Generated code can be parsed with {@link RrdGraphDefTemplate} class ! * {@see exportXmlTemplate}. * * @return String representing graph definition in XML format |
From: Arne V. <cob...@us...> - 2004-05-30 19:50:08
|
Update of /cvsroot/jrobin/src/org/jrobin/graph In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv27850/org/jrobin/graph Modified Files: Cdef.java ChartPanel.java FetchSource.java Grapher.java Pdef.java RpnCalculator.java RrdGraph.java RrdGraphDef.java RrdGraphDefTemplate.java ValueExtractor.java ValueGrid.java Added Files: RrdtoolGraph.java Sdef.java Log Message: JRobin 1.4.0 - Added new datasource (Sdef) - Added backend specification to datasource - Added option to pass Graphics2D object for drawing - Minor changes to RrdGraph/Grapher/ChartPanel Index: Cdef.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/graph/Cdef.java,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** Cdef.java 30 Mar 2004 22:57:45 -0000 1.5 --- Cdef.java 30 May 2004 19:49:55 -0000 1.6 *************** *** 51,55 **** // ================================================================ // -- Constructors ! // ================================================================ /** * Constructs a new Cdef object holding a number of datapoints for a graph. --- 51,67 ---- // ================================================================ // -- Constructors ! // ================================================================ ! /** ! * Constructs a new simple Cdef object based on an empty RPN expression,. ! * ! * @param name Name of the datasource in the graph definition. ! */ ! Cdef( String name ) ! { ! super( name ); ! ! strTokens = new String[0]; ! } ! /** * Constructs a new Cdef object holding a number of datapoints for a graph. *************** *** 185,189 **** tokens[i] = RpnCalculator.TKN_STEP; else ! throw new RrdException("Unknown token enocuntered: " + tkn); } --- 197,201 ---- tokens[i] = RpnCalculator.TKN_STEP; else ! throw new RrdException("Unknown token encountered: " + tkn); } *************** *** 191,194 **** --- 203,225 ---- /** + * Returns the level this Cdef would have in the calculation tree. The level defines when + * the Cdef can be calculated. The level depends on the number of Sdefs this Cdef is depending + * on, and their corresponding calculation levels. + * + * @param levels Array containing the previously calculated calculation levels. + * @return Level of this Sdef in the calculation tree. + */ + int calculateLevel( int[] levels ) + { + int level = 0; + + for ( int i = 0; i < dsIndices.length; i++ ) + if ( levels[ dsIndices[i] ] > level ) + level = levels[ dsIndices[i] ]; + + return level; + } + + /** * Sets the value of a specific datapoint for this Cdef. * @param pos Position (index in the value table) of the new datapoint. Index: ValueExtractor.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/graph/ValueExtractor.java,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** ValueExtractor.java 7 Nov 2003 08:23:19 -0000 1.1 --- ValueExtractor.java 30 May 2004 19:49:56 -0000 1.2 *************** *** 103,107 **** for (int j = 0; j < dsValues[i].length; j++) sources[tblPos++].set( row, timestamp, dsValues[i][j][ tIndex + 1 ] ); ! break; } else { --- 103,107 ---- for (int j = 0; j < dsValues[i].length; j++) sources[tblPos++].set( row, timestamp, dsValues[i][j][ tIndex + 1 ] ); ! break; } else { --- NEW FILE: Sdef.java --- package org.jrobin.graph; import java.util.HashMap; import org.jrobin.core.RrdException; import org.jrobin.core.XmlWriter; /** * <p>Represents a 'static' datasource for a graph. A static datasource is a single value (constant), * but can only be the result of applying a consolidation function (AVG, MIN, MAX, LAST, FIRST or TOTAL) * to one of the other, already defined, datasources.</p> * * @author Arne Vandamme (cob...@jr...) */ class Sdef extends Cdef { // ================================================================ // -- Members // ================================================================ private int defIndex = -1; private String defName = ""; private String consolFunc = "AVERAGE"; private int aggregate = Source.AGG_AVERAGE; private boolean calculated = false; private double[] value = null; // ================================================================ // -- Constructors // ================================================================ /** * Constructs a new Sdef object based on an existing datasource (Def, Cdef or Pdef) * and the consolidation function to apply to that datasource. * * @param name Name of the datasource in the graph definition. * @param defName Name of the datasource this Sdef is derived from. * @param consolFunc Consolidation function to apply to the referring datasource (defName). * @throws RrdException Thrown in case of invalid consolidation function specified. */ Sdef( String name, String defName, String consolFunc ) throws RrdException { super( name ); this.defName = defName; this.consolFunc = consolFunc; // -- Parse the consolidation function to be used if ( consolFunc.equalsIgnoreCase("AVERAGE") || consolFunc.equalsIgnoreCase("AVG") ) aggregate = Source.AGG_AVERAGE; else if ( consolFunc.equalsIgnoreCase("MAX") || consolFunc.equalsIgnoreCase("MAXIMUM") ) aggregate = Source.AGG_MAXIMUM; else if ( consolFunc.equalsIgnoreCase("MIN") || consolFunc.equalsIgnoreCase("MINIMUM") ) aggregate = Source.AGG_MINIMUM; else if ( consolFunc.equalsIgnoreCase("LAST") ) aggregate = Source.AGG_LAST; else if ( consolFunc.equalsIgnoreCase("FIRST") ) aggregate = Source.AGG_FIRST; else if ( consolFunc.equalsIgnoreCase("TOTAL") ) aggregate = Source.AGG_TOTAL; else throw new RrdException( "Invalid consolidation function specified." ); } // ================================================================ // -- Protected methods // ================================================================ /** * Prepares the Sef for faster value calculation by setting the internal * array and references. Override from Cdef parent class. * * @param sourceIndex Lookup table holding the name - index pairs for all datasources. * @param numPoints Number of points used as graph resolution (size of the value table). * @throws RrdException Thrown in case of the requested datasource is not available in the sourceIndex */ void prepare( HashMap sourceIndex, int numPoints ) throws RrdException { if ( sourceIndex.containsKey( defName ) ) defIndex = ( (Integer) sourceIndex.get( defName ) ).intValue(); else throw new RrdException( "Datasource not found: " + defName ); values = new double[ numPoints ]; } /** * Returns the level this Sdef would have in the calculation tree. The level defines when * the Sdef can be calculated. The level of the Sdef will always be one higher than that of * its referring datasource, since it can only be calculated after that datasource has already * been calculated. * * @param levels Array containing the previously calculated calculation levels. * @return Level of this Sdef in the calculation tree. */ int calculateLevel( int[] levels ) { // An Sdef is always one lower in the tree than its source return levels[defIndex] + 1; } /** * Gets the value of the datapoint at a particular position in the datapoint array. * In case of an Sdef, the value will be the same for every different position. * * @param pos Inherited from Cdef * @return The consolidated value of the referring datasource as double */ double get( int pos ) { return values[0]; } /** * Calculates the internal value of this Sdef. * * @param sources Array of the calculated datasources. */ void set( Source[] sources ) { if ( calculated ) return; double value = sources[ defIndex ].getAggregate( aggregate ); for ( int i = 0; i < values.length; i++ ) values[i] = value; calculated = true; } /** * Override from the corresponding method in the Source parent class, * overridden for faster implementation. * * Five of the possible aggregation methods return the actual value * of the Sdef: * <code>AGG_MINIMUM, AGG_MAXIMUM, AGG_AVERAGE, AGG_FIRST and AGG_LAST</code> * * Only <code>AGG_TOTAL</code> will return value summed over the number of * samples in the graph. * * @param aggType Type of the aggregate requested. * @return The double value of the requested aggregate. */ double getAggregate( int aggType ) { switch ( aggType ) { case AGG_MINIMUM: case AGG_MAXIMUM: case AGG_AVERAGE: case AGG_FIRST: case AGG_LAST: return values[0]; case AGG_TOTAL: return (values[0] * values.length) ; } return Double.NaN; } void exportXml(XmlWriter xml) { xml.startTag( "def" ); xml.writeTag( "name", getName() ); xml.writeTag( "datasource", defName ); xml.writeTag( "cf", consolFunc ); xml.closeTag(); // def } } Index: ChartPanel.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/graph/ChartPanel.java,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** ChartPanel.java 7 Nov 2003 09:53:35 -0000 1.2 --- ChartPanel.java 30 May 2004 19:49:56 -0000 1.3 *************** *** 25,29 **** package org.jrobin.graph; ! import java.awt.Graphics; import java.awt.image.BufferedImage; import javax.swing.JPanel; --- 25,29 ---- package org.jrobin.graph; ! import java.awt.*; import java.awt.image.BufferedImage; import javax.swing.JPanel; *************** *** 38,42 **** private BufferedImage chart; ! void setChart( BufferedImage chart ) { this.chart = chart; } --- 38,42 ---- private BufferedImage chart; ! public void setChart( BufferedImage chart ) { this.chart = chart; } Index: RrdGraphDefTemplate.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/graph/RrdGraphDefTemplate.java,v retrieving revision 1.6 retrieving revision 1.7 diff -C2 -d -r1.6 -r1.7 *** RrdGraphDefTemplate.java 28 Apr 2004 12:05:01 -0000 1.6 --- RrdGraphDefTemplate.java 30 May 2004 19:49:56 -0000 1.7 *************** *** 495,501 **** validateTagsOnlyOnce(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"); --- 495,509 ---- validateTagsOnlyOnce(nodes[i], new String[] {"name", "rpn"}); String name = getChildValue(nodes[i], "name"); ! String rpn = getChildValue(nodes[i], "rpn"); rrdGraphDef.datasource(name, rpn); } + else if ( hasChildNode( nodes[i], "cf" ) || hasChildNode( nodes[i], "datasource" ) ) { + // STATIC AGGREGATED DATASOURCE + validateTagsOnlyOnce( nodes[i], new String[] {"name", "datasource", "cf"} ); + String name = getChildValue(nodes[i], "name"); + String ds = getChildValue(nodes[i], "datasource"); + String cf = getChildValue(nodes[i], "cf"); + rrdGraphDef.datasource( name, ds, cf ); + } else { throw new RrdException("Unrecognized <def> format"); Index: Pdef.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/graph/Pdef.java,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** Pdef.java 16 Jan 2004 16:36:54 -0000 1.2 --- Pdef.java 30 May 2004 19:49:56 -0000 1.3 *************** *** 36,39 **** --- 36,42 ---- class Pdef extends Source { + // ================================================================ + // -- Members + // ================================================================ private Plottable plottable; *************** *** 42,46 **** private boolean indexed = false; private boolean named = false; ! /** * Constructs a new Plottable Def: a custom external datasource --- 45,53 ---- private boolean indexed = false; private boolean named = false; ! ! ! // ================================================================ ! // -- Constructors ! // ================================================================ /** * Constructs a new Plottable Def: a custom external datasource *************** *** 85,88 **** --- 92,99 ---- } + + // ================================================================ + // -- Protected methods + // ================================================================ /** * Prepares the array that will hold the values. Index: FetchSource.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/graph/FetchSource.java,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** FetchSource.java 1 Mar 2004 08:50:25 -0000 1.3 --- FetchSource.java 30 May 2004 19:49:56 -0000 1.4 *************** *** 26,29 **** --- 26,30 ---- import java.util.Vector; + import java.util.ArrayList; import java.io.IOException; *************** *** 53,59 **** private String rrdFile; // Holds the name of the RRD file ! private int numSources = 0; ! private Vector[] datasources = new Vector[MAX_CF]; --- 54,61 ---- private String rrdFile; // Holds the name of the RRD file ! private String backendName; ! private int numSources = 0; ! private ArrayList[] datasources = new ArrayList[MAX_CF]; *************** *** 71,75 **** // Initialization of datasource lists per CF for (int i = 0; i < datasources.length; i++) ! datasources[i] = new Vector(); } --- 73,77 ---- // Initialization of datasource lists per CF for (int i = 0; i < datasources.length; i++) ! datasources[i] = new ArrayList( 10 ); } *************** *** 86,92 **** { this( rrdFile ); ! addSource( consolFunc, dsName, name ); } ! // ================================================================ // -- Protected methods --- 88,110 ---- { this( rrdFile ); ! addSource( consolFunc, dsName, name ); } ! ! /** ! * Constructs a FetchSource object based on a RRD file name, and ! * adds a given datasource to the datasources list. ! * @param rrdFile Name of the RRD file holding all datasources. ! * @param consolFunc Consolidation function of the datasource to fetch. ! * @param dsName Internal name of the datasource in the RRD file. ! * @param name Variable name of the datasource in the graph definition. ! * @param backendName Name of the RrdBackendFactory to use for this RrdDb. ! * @throws RrdException Thrown in case of a JRobin specific error. ! */ ! FetchSource( String rrdFile, String consolFunc, String dsName, String name, String backendName ) throws RrdException ! { ! this( rrdFile, consolFunc, dsName, name ); ! setBackendFactory( backendName ); ! } ! // ================================================================ // -- Protected methods *************** *** 114,118 **** numSources++; } ! /** * Fetches all datavalues for a given timespan out of the provided RRD file. --- 132,145 ---- numSources++; } ! ! /** ! * Sets the name of the RrdBackendFactory that should be used for this FetchSource. ! * The factory should be registered with RrdBackendFactory static. ! * @param backendName Name of the RrdBackendFactory to use for this RrdDb. ! */ ! protected void setBackendFactory( String backendName ) { ! this.backendName = backendName; ! } ! /** * Fetches all datavalues for a given timespan out of the provided RRD file. *************** *** 126,129 **** --- 153,159 ---- protected ValueExtractor fetch ( RrdDb rrd, long startTime, long endTime ) throws IOException, RrdException { + int dsSize = 0; + String[] dsNames, vNames; + long rrdStep = rrd.getRrdDef().getStep(); FetchData[] result = new FetchData[datasources.length]; *************** *** 134,144 **** for (int i = 0; i < datasources.length; i++) { ! if ( datasources[i].size() > 0 ) { // Set the list of ds names ! String[] dsNames = new String[ datasources[i].size() ]; ! String[] vNames = new String[ datasources[i].size() ]; ! for (int j = 0; j < dsNames.length; j++ ) { ! String[] spair = (String[]) datasources[i].elementAt(j); dsNames[j] = spair[0]; vNames[j] = spair[1]; --- 164,176 ---- for (int i = 0; i < datasources.length; i++) { ! dsSize = datasources[i].size(); ! ! if ( dsSize > 0 ) { // Set the list of ds names ! dsNames = new String[ dsSize ]; ! vNames = new String[ dsSize ]; ! for (int j = 0; j < dsSize; j++ ) { ! String[] spair = (String[]) datasources[i].get(j); dsNames[j] = spair[0]; vNames[j] = spair[1]; *************** *** 151,157 **** FetchData data = request.fetchData(); ! for (int j = 0; j < vNames.length; j++) names[ data.getDsIndex(dsNames[j]) + tblPos ] = vNames[j]; ! tblPos += dsNames.length; result[i] = data; --- 183,189 ---- FetchData data = request.fetchData(); ! for (int j = 0; j < dsSize; j++) names[ data.getDsIndex(dsNames[j]) + tblPos ] = vNames[j]; ! tblPos += dsSize; result[i] = data; *************** *** 166,173 **** } 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]); --- 198,213 ---- } + protected RrdBackendFactory getRrdBackendFactory() throws RrdException + { + if ( backendName != null ) + return RrdBackendFactory.getFactory( backendName ); + + return RrdBackendFactory.getDefaultFactory(); + } + 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].get(j); xml.startTag("def"); xml.writeTag("name", pair[1]); --- NEW FILE: RrdtoolGraph.java --- package org.jrobin.graph; import org.jrobin.core.RrdException; import java.awt.*; /** * Created by IntelliJ IDEA. * User: cbld * Date: 25-mei-2004 * Time: 21:02:56 * To change this template use File | Settings | File Templates. */ public class RrdtoolGraph { // ================================================================ // -- Constants // ================================================================ private static final int SAVE_PNG = 0; private static final int SAVE_GIF = 1; private static final int DS_DEF = 0; private static final int DS_CDEF = 1; private static final int TXT_COMMENT = 0; private static final int TXT_GPRINT = 1; private static final int GRAPH_LINE = 0; private static final int GRAPH_AREA = 1; private static final int GRAPH_STACK = 2; private static final int TKN_IGNORE = -2; private static final int TKN_UNKNOWN = -1; private static final int TKN_RRDTOOL = 0; private static final int TKN_GRAPH = 1; private static final int TKN_START = 2; private static final int TKN_END = 3; private static final int TKN_COMMENT = 4; private static final int TKN_LINE = 5; private static final int TKN_AREA = 6; private static final int TKN_STACK = 7; private static final int TKN_CDEF = 8; private static final int TKN_DEF = 9; private static final int TKN_GPRINT = 11; private static final int TKN_HRULE = 12; private static final int TKN_VRULE = 13; private static final int TKN_STEP = 14; private static final int TKN_TITLE = 15; private static final int TKN_NOLEGEND = 16; private static final int TKN_COLOR = 17; private static final int TKN_RIGID = 18; private static final int TKN_LOWERLIMIT = 19; private static final int TKN_UPPERLIMIT = 20; private static final int TKN_LAZY = 21; private static final int TKN_OVERLAY = 23; private static final int TKN_BACKGROUND = 24; private static final int TKN_IMGFORMAT = 25; private static final int TKN_WIDTH = 26; private static final int TKN_HEIGHT = 27; private static final int TKN_VERT_LABEL = 28; private static final int TKN_UNITS_EXP = 29; private static final int TKN_NOMINOR = 30; private static final int TKN_XGRID = 31; private static final int TKN_YGRID = 32; private static final int TKN_BASE = 33; // ================================================================ // -- Members // ================================================================ private String token = ""; private String script = null; private RrdGraphDef graphDef = null; private int tokenPos = 0; private char[] parseCmd = new char[0]; private boolean gridRigid = false; private double gridLower = Double.MAX_VALUE; private double gridUpper = Double.MIN_VALUE; private int width = 0; private int height = 0; private int fileType = SAVE_PNG; private String fileName = ""; // ================================================================ // -- Constructors // ================================================================ public RrdtoolGraph( String script ) { this.script = script; } // ================================================================ // -- Public methods // ================================================================ public RrdGraphDef getRrdGraphDef() throws RrdException { parseRrdtoolScript(); return graphDef; } // ================================================================ // -- Private methods // ================================================================ /** * * @return * @throws RrdException */ private boolean parseRrdtoolScript() throws RrdException { long startTime = 0, stopTime = 0; graphDef = new RrdGraphDef(); // First replace all special whitespace chars by a space parseCmd = script.replace( '\n', ' ' ).replace( '\r', ' ' ).replace( '\t', ' ' ).toCharArray(); while ( nextToken() > 0 ) { System.err.println( token ); switch ( parseToken( token ) ) { case TKN_RRDTOOL: // We don't care about this token break; case TKN_GRAPH: // Next token is the filename nextToken(); break; case TKN_START: // Next token is the start time nextToken(); startTime = Long.parseLong( token ); break; case TKN_END: // Next token is the end time nextToken(); stopTime = Long.parseLong( token ); break; case TKN_NOMINOR: // Hide the entire minor grid graphDef.setMinorGridX( false ); graphDef.setMinorGridY( false ); break; case TKN_WIDTH: // Next token is graph pixel width nextToken(); width = Integer.parseInt( token ); break; case TKN_HEIGHT: // Next token is graph pixel height nextToken(); height = Integer.parseInt( token ); break; case TKN_UNITS_EXP: // Next token is the units exponent value nextToken(); graphDef.setUnitsExponent( Integer.parseInt( token ) ); break; case TKN_VERT_LABEL: // Next token is the actual vertical label text nextToken(); graphDef.setVerticalLabel( unescape(token) ); break; case TKN_TITLE: // Next token is the actual title text nextToken(); graphDef.setTitle( unescape(token) ); break; case TKN_IMGFORMAT: // Next token is the file type nextToken(); if ( token.equalsIgnoreCase("gif") ) fileType = SAVE_GIF; break; case TKN_BACKGROUND: // Next token is the filename of background image nextToken(); graphDef.setBackground( unescape(token) ); break; case TKN_OVERLAY: // Next token is the filename of background image nextToken(); graphDef.setOverlay( unescape(token) ); break; case TKN_NOLEGEND: // Hide the legend graphDef.setShowLegend( false ); break; case TKN_LOWERLIMIT: // Next token is the lower limit value nextToken(); gridLower = Double.parseDouble(token); break; case TKN_UPPERLIMIT: // Next token is the upper limit value nextToken(); gridUpper = Double.parseDouble(token); break; case TKN_RIGID: // Set rigid grid gridRigid = true; break; case TKN_BASE: // Set base value nextToken(); graphDef.setBaseValue( Double.parseDouble(token) ); break; case TKN_COMMENT: parseTextCommand( TXT_COMMENT ); break; case TKN_GPRINT: parseTextCommand( TXT_GPRINT ); break; case TKN_LINE: parseGraphCommand( GRAPH_LINE ); break; case TKN_AREA: parseGraphCommand( GRAPH_AREA ); break; case TKN_STACK: parseGraphCommand( GRAPH_STACK ); break; case TKN_DEF: parseDatasource( DS_DEF ); break; case TKN_CDEF: parseDatasource( DS_CDEF ); break; case TKN_IGNORE: // Do nothing break; case TKN_UNKNOWN: throw new RrdException( "Unknown token: " + token ); } } // Set grid range if necessary if ( gridRigid || ( gridLower == Double.MAX_VALUE ) || ( gridUpper == Double.MIN_VALUE ) ) graphDef.setGridRange( gridLower, gridUpper, gridRigid ); return true; } /** * * @param type * @throws RrdException */ private void parseGraphCommand( int type ) throws RrdException { if ( type == GRAPH_LINE ) { int w = Integer.parseInt( "" + token.charAt( 4 ) ); // Get the datasource int pos = token.indexOf( '#', 6 ); int npos = token.indexOf( ':', 6 ); if ( pos < 0 ) pos = npos; String ds = ( pos > 0 ? token.substring( 6, pos ) : token.substring( 6 ) ); Color color = null; String legend = null; // Get the color if ( pos > 0 && token.charAt(pos) == '#' ) color = Color.decode( npos > 0 ? token.substring( pos, npos ) : token.substring( pos ) ); // Get the legend (if there is one) if ( npos > 0 ) legend = unescape( token.substring( npos + 1 ) ); graphDef.line( ds, color, legend, w ); } else { if ( type == GRAPH_STACK ) token = token.substring( 6 ); else token = token.substring( 5 ); int pos = token.indexOf( '#' ); int npos = token.indexOf( ':' ); String ds = ( pos > 0 ? token.substring( 0, pos ) : token.substring( 0 ) ); Color color = null; String legend = null; // Get the color if ( pos > 0 && token.charAt(pos) == '#' ) color = Color.decode( npos > 0 ? token.substring( pos, npos ) : token.substring( pos ) ); // Get the legend (if there is one) if ( npos > 0 ) legend = unescape( token.substring( npos + 1 ) ); if ( type == GRAPH_AREA ) graphDef.area( ds, color, legend ); else if ( type == GRAPH_STACK ) graphDef.stack( ds, color, legend ); } } /** * * @param text * @return */ private String unescape( String text ) { if ( text.startsWith( "'" ) || text.startsWith( "\"" ) ) return text.substring( 1, text.length() - 1 ); return text; } /** * * @param type * @throws RrdException */ private void parseTextCommand( int type ) throws RrdException { int pos = token.indexOf( ':' ); if ( type == TXT_COMMENT ) { String text = unescape( token.substring( pos + 1 ) ); graphDef.comment( text ); } else if ( type == TXT_GPRINT ) { // GPRINT:vname:CF:format int npos = token.indexOf( ':', ++pos ); String ds = token.substring( pos, npos ); pos = token.indexOf( ':', ++npos ); String cf = token.substring( npos, pos ); String text = unescape( token.substring( pos + 1 ) ); // Change the placeholder to JRobin //graphDef.gprint( ds, cf, text ); } } /** * * @param type * @throws RrdException */ private void parseDatasource( int type ) throws RrdException { // Fetch the name of the datasource int pos = token.indexOf( ':' ); int npos = token.indexOf( '=', ++pos ); String name = token.substring( pos, npos ); if ( type == DS_DEF ) { // DEF:vname=rrd:ds-name:CF token = token.substring( npos + 1 ); // Fetch reverse pos = token.lastIndexOf( ':' ); String cf = token.substring( pos + 1 ); npos = token.lastIndexOf( ':', pos - 1 ); String dsName = token.substring( npos + 1, pos ); String rrdFile = token.substring( 0, npos ); graphDef.datasource( name, rrdFile, dsName, cf ); } else { // CDEF:vname=rpn-expression graphDef.datasource( name, token.substring( npos + 1 ) ); } } /** * Reads the next token in the rrdtool script. * * @return */ private int nextToken() { char[] tknChars = new char[512]; int charPos = 0; int cmdPos = tokenPos; boolean found = false; boolean stringComplete = true; char findChar = ' '; /* * This will read from the current position, till the next whitespace. * However, if it encounters a " or a ' that is not escaped, it will read until the next matching character. */ while ( charPos < 512 && (cmdPos < parseCmd.length) && !found ) { if ( parseCmd[cmdPos] == '"' ) { if ( stringComplete ) { stringComplete = false; findChar = '"'; } else if ( findChar == '"' && !(parseCmd[cmdPos - 1] == '\\') ) stringComplete = true; } else if ( parseCmd[cmdPos] == '\'' ) { if ( stringComplete ) { stringComplete = false; findChar = '\''; } else if ( findChar == '\'' && !(parseCmd[cmdPos - 1] == '\\') ) stringComplete = true; } if ( stringComplete && parseCmd[cmdPos] == ' ' ) found = true; else tknChars[charPos++] = parseCmd[cmdPos++]; } token = new String( tknChars, 0, charPos ).trim(); tokenPos = cmdPos + 1; return charPos; } /** * * @param token * @return */ private int parseToken( String token ) { if ( token.equalsIgnoreCase("rrdtool") ) return TKN_RRDTOOL; if ( token.equalsIgnoreCase("graph") ) return TKN_GRAPH; if ( token.equalsIgnoreCase("--start") || token.equals("-s") ) return TKN_START; if ( token.equalsIgnoreCase("--end") || token.equals("-e") ) return TKN_END; if ( token.equalsIgnoreCase("--width") || token.equals("-w") ) return TKN_WIDTH; if ( token.equalsIgnoreCase("--height") || token.equals("-h") ) return TKN_HEIGHT; if ( token.equalsIgnoreCase("--no-minor") ) return TKN_NOMINOR; if ( token.equalsIgnoreCase("--units-exponent") || token.equals("-X") ) return TKN_UNITS_EXP; if ( token.equalsIgnoreCase("--vertical-label") || token.equals("-v") ) return TKN_VERT_LABEL; if ( token.equalsIgnoreCase("--imgformat") || token.equals("-a") ) return TKN_IMGFORMAT; if ( token.equalsIgnoreCase("--background") || token.equals("-B") ) return TKN_BACKGROUND; if ( token.equalsIgnoreCase("--overlay") || token.equals("-O") ) return TKN_OVERLAY; if ( token.equalsIgnoreCase("--title") || token.equals("-t") ) return TKN_TITLE; if ( token.equalsIgnoreCase("--step") || token.equals("-S") ) return TKN_STEP; if ( token.equalsIgnoreCase("--no-legend") || token.equals("-g") ) return TKN_NOLEGEND; if ( token.equalsIgnoreCase("--base") || token.equals("-b") ) return TKN_BASE; if ( token.equalsIgnoreCase("--lower-limit") || token.equals("-l") ) return TKN_LOWERLIMIT; if ( token.equalsIgnoreCase("--upper-limit") || token.equals("-u") ) return TKN_UPPERLIMIT; if ( token.equalsIgnoreCase("--rigid") || token.equals("-r") ) return TKN_RIGID; if ( token.startsWith("COMMENT") ) return TKN_COMMENT; if ( token.startsWith("GPRINT") ) return TKN_GPRINT; if ( token.startsWith("LINE") ) return TKN_LINE; if ( token.startsWith("AREA") ) return TKN_AREA; if ( token.startsWith("STACK") ) return TKN_STACK; if ( token.startsWith("HRULE") ) return TKN_HRULE; if ( token.startsWith("VRULE") ) return TKN_VRULE; if ( token.startsWith("CDEF") ) return TKN_CDEF; if ( token.startsWith("DEF") ) return TKN_DEF; if ( token.equals("-Y") || token.equals("--alt-y-grid") || token.equals("-R") || token.equals("--alt-y-mrtg") || token.equals("-A") || token.equals("--alt-autoscale") || token.equals("-M") || token.equals("--alt-autoscale-max") || token.equals("-L") || token.equals("--units-length") || token.equals("-i") || token.equals("--interlaced") || token.equals("-f") || token.equals("--imginfo") || token.equals("-o") || token.equals("--logarithmic") || token.equals("-j") || token.equals("--only-graph") || token.equals("-F") || token.equals("--force-rules-legend") || token.startsWith("PRINT") || token.equals("-U") || token.startsWith("--unit") ) return TKN_IGNORE; return TKN_UNKNOWN; } public static void main( String[] args ) throws Exception { String str = "rrdtool graph FNAME --start 100 --end 700\n" + "DEF:inOctets=c:/file.rrd:test-run:AVERAGE " + "CDEF:bitIn=inOctets,8,* " + "COMMENT:'commentaar \"nr\" 1'\n" + "AREA:test#ffa9b3:'this is the legend'\n" + "COMMENT:\"commentaar 'nr' 2\"\n" + "LINE2:test2:'this is the legend two' " + "GPRINT:bitIn:AVG:'Average %2.5'"; RrdtoolGraph rg = new RrdtoolGraph( str ); rg.getRrdGraphDef(); } } Index: RpnCalculator.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/graph/RpnCalculator.java,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** RpnCalculator.java 30 Mar 2004 22:57:44 -0000 1.2 --- RpnCalculator.java 30 May 2004 19:49:56 -0000 1.3 *************** *** 333,338 **** return pop(); } ! ! // ================================================================ // -- Private methods --- 333,338 ---- return pop(); } ! ! // ================================================================ // -- Private methods Index: ValueGrid.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/graph/ValueGrid.java,v retrieving revision 1.7 retrieving revision 1.8 diff -C2 -d -r1.7 -r1.8 *** ValueGrid.java 26 Apr 2004 22:28:33 -0000 1.7 --- ValueGrid.java 30 May 2004 19:49:56 -0000 1.8 *************** *** 127,133 **** return; ! if ( upper == Double.NaN || upper == Double.MIN_VALUE || upper == Double.MAX_VALUE ) upper = 0.9; ! if ( lower == Double.NaN || lower == Double.MAX_VALUE || lower == Double.MIN_VALUE ) lower = 0; --- 127,133 ---- return; ! if ( Double.isNaN(upper) || upper == Double.MIN_VALUE || upper == Double.MAX_VALUE ) upper = 0.9; ! if ( Double.isNaN(lower) || lower == Double.MAX_VALUE || lower == Double.MIN_VALUE ) lower = 0; Index: RrdGraph.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/graph/RrdGraph.java,v retrieving revision 1.7 retrieving revision 1.8 diff -C2 -d -r1.7 -r1.8 *** RrdGraph.java 21 Apr 2004 09:48:54 -0000 1.7 --- RrdGraph.java 30 May 2004 19:49:56 -0000 1.8 *************** *** 39,46 **** --- 39,48 ---- import java.awt.image.RenderedImage; import java.awt.image.BufferedImage; + import java.awt.*; import org.jrobin.core.RrdDb; import org.jrobin.core.RrdDbPool; import org.jrobin.core.RrdException; + import org.jrobin.core.RrdBackendFactory; /** *************** *** 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) ); } --- 156,160 ---- 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) ); } *************** *** 188,192 **** stream.close(); - } --- 189,192 ---- *************** *** 270,274 **** return outputStream.toByteArray(); } ! /** * Returns graph with default chart dimensions (400 by 100) as an array of JPEG bytes. --- 270,274 ---- return outputStream.toByteArray(); } ! /** * Returns graph with default chart dimensions (400 by 100) as an array of JPEG bytes. *************** *** 351,360 **** return bStream.toByteArray(); } ! /** * Returns panel object so that graph can be easily embedded in swing applications. * @return Swing JPanel object with graph embedded in panel. */ ! public JPanel getChartPanel() throws RrdException, IOException { ChartPanel p = new ChartPanel(); --- 351,374 ---- return bStream.toByteArray(); } ! ! /** ! * Returns the underlying BufferedImage of a graph with custom dimensions. ! * Specifying 0 for both width and height will result in a auto-sized graph. ! * @param width Width of the chart area in pixels. ! * @param height Height of the chart area in pixels. ! * @return BufferedImage containing the graph. ! * @throws IOException Thrown in case of I/O error. ! * @throws RrdException Thrown in case of JRobin specific error. ! */ ! public BufferedImage getBufferedImage( int width, int height ) throws IOException, RrdException ! { ! return getBufferedImage( width, height, BufferedImage.TYPE_INT_RGB ); ! } ! /** * Returns panel object so that graph can be easily embedded in swing applications. * @return Swing JPanel object with graph embedded in panel. */ ! public ChartPanel getChartPanel() throws RrdException, IOException { ChartPanel p = new ChartPanel(); *************** *** 363,376 **** return p; } ! // ================================================================ // -- Protected (package) methods // ================================================================ ! RrdDb getRrd( String rrdFile ) throws IOException, RrdException { if ( pool != null ) return pool.requestRrdDb( rrdFile ); ! else ! return new RrdDb( rrdFile, true ); } --- 377,407 ---- return p; } ! ! /** ! * Renders the graph onto a specified Graphics2D object. ! * Specifying 0 for both width and height will result in a auto-sized graph. ! * @param graphics Handle to a Graphics2D object to render the graph on. ! * @param width Width of the chart area in pixels. ! * @param height Height of the chart area in pixels. ! * @throws RrdException Thrown in case of JRobin specific error. ! * @throws IOException Thrown in case of I/O error ! */ ! public void renderImage( Graphics2D graphics, int width, int height ) throws RrdException, IOException ! { ! if ( useImageSize ) ! grapher.renderImage( width, height, graphics, true ); ! else ! grapher.renderImage( width, height, graphics, false ); ! } ! // ================================================================ // -- Protected (package) methods // ================================================================ ! RrdDb getRrd( String rrdFile, RrdBackendFactory backendFactory ) throws IOException, RrdException { if ( pool != null ) return pool.requestRrdDb( rrdFile ); ! else ! return new RrdDb( rrdFile, true, backendFactory ); } Index: RrdGraphDef.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/graph/RrdGraphDef.java,v retrieving revision 1.11 retrieving revision 1.12 diff -C2 -d -r1.11 -r1.12 *** RrdGraphDef.java 29 Apr 2004 10:17:21 -0000 1.11 --- RrdGraphDef.java 30 May 2004 19:49:56 -0000 1.12 *************** *** 29,37 **** import java.awt.Color; import java.awt.BasicStroke; ! import java.util.Date; ! import java.util.Vector; ! import java.util.HashMap; ! import java.util.Iterator; ! import java.util.GregorianCalendar; import java.text.SimpleDateFormat; --- 29,33 ---- import java.awt.Color; import java.awt.BasicStroke; ! import java.util.*; import java.text.SimpleDateFormat; *************** *** 113,125 **** // -- Non-settable members private int numDefs = 0; // number of Def datasources added private int commentLines = 0; // number of complete lines in the list of comment items private int commentLineShift = 0; // modifier to add to get minimum one complete line of comments ! private HashMap fetchSources = new HashMap(); // holds the list of FetchSources ! private Vector cdefList = new Vector(); // holds the list of Cdef datasources ! private Vector pdefList = new Vector(); // holds the list of Plottable datasources ! private Vector plotDefs = new Vector(); // holds the list of PlotDefs ! private Vector comments = new Vector(); // holds the list of comment items --- 109,122 ---- // -- Non-settable members + private int numSdefs = 0; private int numDefs = 0; // number of Def datasources added private int commentLines = 0; // number of complete lines in the list of comment items private int commentLineShift = 0; // modifier to add to get minimum one complete line of comments ! private HashMap fetchSources = new HashMap( 10 ); // holds the list of FetchSources ! private ArrayList cdefList = new ArrayList( 10 ); // holds the list of Cdef datasources ! private ArrayList pdefList = new ArrayList( 10 ); // holds the list of Plottable datasources ! private ArrayList plotDefs = new ArrayList( 10 ); // holds the list of PlotDefs ! private ArrayList comments = new ArrayList( 10 ); // holds the list of comment items *************** *** 620,629 **** * can be used:</p> * <ul> ! * <li>To specify sources for line, area and stack plots. * <li>To define complex graph sources * (see {@link #datasource(java.lang.String, java.lang.String) complex graph ! * source definition}). * <li>To specify graph data source for the ! * {@link #gprint(java.lang.String, java.lang.String, java.lang.String) gprint()} method. * @param name Graph source name. * @param file Path to RRD file. --- 617,628 ---- * can be used:</p> * <ul> ! * <li>To specify sources for line, area and stack plots.</li> * <li>To define complex graph sources * (see {@link #datasource(java.lang.String, java.lang.String) complex graph ! * source definition}).</li> * <li>To specify graph data source for the ! * {@link #gprint(java.lang.String, java.lang.String, java.lang.String) gprint()} method.</li> ! * </ul> ! * * @param name Graph source name. * @param file Path to RRD file. *************** *** 643,647 **** numDefs++; } ! /** * <p>Adds complex graph source with the given name to the graph definition. --- 642,679 ---- numDefs++; } ! ! /** ! * <p>Adds simple graph source to graph definition. Graph source <code>name</code> ! * can be used:</p> ! * <ul> ! * <li>To specify sources for line, area and stack plots.</li> ! * <li>To define complex graph sources ! * (see {@link #datasource(java.lang.String, java.lang.String) complex graph ! * source definition}).</li> ! * <li>To specify graph data source for the ! * {@link #gprint(java.lang.String, java.lang.String, java.lang.String) gprint()} method.</li> ! * </ul> ! * ! * @param name Graph source name. ! * @param file Path to RRD file. ! * @param dsName Data source name defined in the RRD file. ! * @param consolFunc Consolidation function that will be used to extract data from the RRD ! * file ("AVERAGE", "MIN", "MAX" or "LAST"). ! * @param backend Name of the RrdBackendFactory that should be used for this RrdDb. ! */ ! public void datasource( String name, String file, String dsName, String consolFunc, String backend ) throws RrdException ! { ! if ( fetchSources.containsKey(file) ) ! { ! FetchSource rf = (FetchSource) fetchSources.get(file); ! rf.setBackendFactory( backend ); ! rf.addSource( consolFunc, dsName, name ); ! } ! else ! fetchSources.put( file, new FetchSource(file, consolFunc, dsName, name, backend ) ); ! ! numDefs++; ! } ! /** * <p>Adds complex graph source with the given name to the graph definition. *************** *** 662,665 **** --- 694,698 ---- * <p>For more details on RPN see RRDTool's * <a href="http://people.ee.ethz.ch/~oetiker/webtools/rrdtool/manual/rrdgraph.html" target="man">rrdgraph man page</a>.</p> + * * @param name Graph source name. * @param rpn RPN expression containig comma delmited simple and complex graph *************** *** 670,674 **** cdefList.add( new Cdef(name, rpn) ); } ! /** * <p>Adds a custom graph source with the given name to the graph definition. --- 703,722 ---- cdefList.add( new Cdef(name, rpn) ); } ! ! /** ! * <p>Adds static graph source with the given name to the graph definition. ! * Static graph sources are the result of a consolidation function applied ! * to *any* other graph source that has been defined previously.</p> ! * ! * @param name Graph source name. ! * @param defName Name of the datasource to calculate the value from. ! * @param consolFunc Consolidation function to use for value calculation ! */ ! public void datasource( String name, String defName, String consolFunc ) throws RrdException ! { ! cdefList.add( new Sdef(name, defName, consolFunc) ); ! numSdefs++; ! } ! /** * <p>Adds a custom graph source with the given name to the graph definition. *************** *** 1020,1026 **** fs.exportXml(xml); } ! // cdefs for (int i = 0; i < cdefList.size(); i++ ) { ! Cdef cdef = (Cdef) cdefList.elementAt(i); cdef.exportXml(xml); } --- 1068,1074 ---- fs.exportXml(xml); } ! // cdefs and sdefs for (int i = 0; i < cdefList.size(); i++ ) { ! Cdef cdef = (Cdef) cdefList.get(i); cdef.exportXml(xml); } *************** *** 1029,1036 **** 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); } --- 1077,1084 ---- for ( int i = 0; i < comments.size(); i++ ) { ! Comment cmt = (Comment) comments.get(i); if ( cmt.commentType == Comment.CMT_LEGEND || cmt.commentType == Comment.CMT_NOLEGEND) { ! PlotDef pDef = (PlotDef) plotDefs.get( ((Legend) cmt).getPlofDefIndex() ); pDef.exportXmlTemplate(xml, cmt.text); } *************** *** 1048,1053 **** --- 1096,1112 ---- /** + * Exports RrdGraphDef (graph definition) object in XML format to string. + * Generated code can be parsed with {@link RrdGraphDefTemplate} class + * {@see exportXmlTemplate). + * + * @return String representing graph definition in XML format + */ + public String getXmlTemplate() { + return exportXmlTemplate(); + } + /** * 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 */ *************** *** 1061,1064 **** --- 1120,1124 ---- * Exports RrdGraphDef (graph definition) object in XML format to file. * Generated code can be parsed with {@link RrdGraphDefTemplate} class. + * * @param filePath destination file */ *************** *** 1257,1261 **** return (Pdef[]) pdefList.toArray( new Pdef[] {} ); } ! protected HashMap getFetchSources() { --- 1317,1326 ---- return (Pdef[]) pdefList.toArray( new Pdef[] {} ); } ! ! protected int getNumSdefs() ! { ! return numSdefs; ! } ! protected HashMap getFetchSources() { Index: Grapher.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/graph/Grapher.java,v retrieving revision 1.10 retrieving revision 1.11 diff -C2 -d -r1.10 -r1.11 *** Grapher.java 21 Apr 2004 09:49:01 -0000 1.10 --- Grapher.java 30 May 2004 19:49:56 -0000 1.11 *************** *** 144,156 **** // ================================================================ /** ! * Creates the actual graph based on the GraphDef definition. ! * The graph is created as a <code>java.awt.image.BufferedImage</code>. * @param cWidth Width of the chart area in pixels. * @param cHeight Height of the chart area in pixels. - * @return The created graph as a BufferedImage. - * @throws RrdException Thrown in case of a JRobin specific error. - * @throws IOException Thrown in case of a I/O related error. */ ! protected BufferedImage createImage( int cWidth, int cHeight, int colorType ) throws RrdException, IOException { // Calculate chart dimensions --- 144,152 ---- // ================================================================ /** ! * Calculates the graph and chart dimensions. * @param cWidth Width of the chart area in pixels. * @param cHeight Height of the chart area in pixels. */ ! private void calculateDimensions( int cWidth, int cHeight ) { // Calculate chart dimensions *************** *** 163,216 **** chart_lpadding = ( graphDef.showMajorGridY() ? graphDef.getChartLeftPadding() : CHART_LPADDING_NM ); chart_bpadding = ( graphDef.showMajorGridX() ? CHART_BPADDING : CHART_BPADDING_NM ); ! // Size of all lines below chart commentBlock = 0; if ( graphDef.showLegend() ) ! commentBlock = graphDef.getCommentLineCount() * (nfont_height + LINE_PADDING) - LINE_PADDING; ! ! // x_offset and y_offset define the starting corner of the actual graph x_offset = LBORDER_SPACE; ! if ( graphDef.getVerticalLabel() != null ) x_offset += nfont_height + LINE_PADDING; imgWidth = chartWidth + x_offset + RBORDER_SPACE + chart_lpadding + CHART_RPADDING; ! y_offset = UBORDER_SPACE; ! if ( graphDef.getTitle() != null ) // Title *always* gets a extra LF automatically y_offset += ((tfont_height + LINE_PADDING) * graphDef.getTitle().getLineCount() + tfont_height) + LINE_PADDING; imgHeight = chartHeight + commentBlock + y_offset + BBORDER_SPACE + CHART_UPADDING + CHART_BPADDING; - - // Create graphics object - BufferedImage bImg = new BufferedImage( imgWidth, imgHeight, colorType ); - Graphics2D graphics = (Graphics2D) bImg.getGraphics(); - - // Do the actual graphing - calculateSeries(); // calculate all datasources - - plotImageBackground( graphics ); // draw the image background - - plotChart( graphics ); // draw the actual chart - - plotComments( graphics ); // draw all comment lines - - plotOverlay( graphics ); // draw a possible image overlay - - plotSignature( graphics ); // draw the JRobin signature - - // Dispose graphics context - graphics.dispose(); - - return bImg; } ! /** ! * Creates the actual graph based on the GraphDef definition. ! * The graph is created as a <code>java.awt.image.BufferedImage</code>. * @param cWidth Width of the entire image in pixels. * @param cHeight Height of the entire image in pixels. - * @return The created graph as a BufferedImage. - * @throws RrdException Thrown in case of a JRobin specific error. - * @throws IOException Thrown in case of a I/O related error. */ ! protected BufferedImage createImageGlobal( int cWidth, int cHeight, int colorType ) throws RrdException, IOException { imgWidth = cWidth; --- 159,186 ---- chart_lpadding = ( graphDef.showMajorGridY() ? graphDef.getChartLeftPadding() : CHART_LPADDING_NM ); chart_bpadding = ( graphDef.showMajorGridX() ? CHART_BPADDING : CHART_BPADDING_NM ); ! // Size of all lines below chart commentBlock = 0; if ( graphDef.showLegend() ) ! commentBlock = graphDef.getCommentLineCount() * (nfont_height + LINE_PADDING) - LINE_PADDING; ! ! // x_offset and y_offset define the starting corner of the actual graph x_offset = LBORDER_SPACE; ! if ( graphDef.getVerticalLabel() != null ) x_offset += nfont_height + LINE_PADDING; imgWidth = chartWidth + x_offset + RBORDER_SPACE + chart_lpadding + CHART_RPADDING; ! y_offset = UBORDER_SPACE; ! if ( graphDef.getTitle() != null ) // Title *always* gets a extra LF automatically y_offset += ((tfont_height + LINE_PADDING) * graphDef.getTitle().getLineCount() + tfont_height) + LINE_PADDING; imgHeight = chartHeight + commentBlock + y_offset + BBORDER_SPACE + CHART_UPADDING + CHART_BPADDING; } ! /** ! * Calculates the graph and chart dimensions. * @param cWidth Width of the entire image in pixels. * @param cHeight Height of the entire image in pixels. */ ! private void calculateDimensionsGlobal( int cWidth, int cHeight ) { imgWidth = cWidth; *************** *** 222,266 **** chart_lpadding = ( graphDef.showMajorGridY() ? graphDef.getChartLeftPadding() : CHART_LPADDING_NM ); chart_bpadding = ( graphDef.showMajorGridX() ? CHART_BPADDING : CHART_BPADDING_NM ); ! // Size of all lines below chart commentBlock = 0; if ( graphDef.showLegend() ) ! commentBlock = graphDef.getCommentLineCount() * (nfont_height + LINE_PADDING) - LINE_PADDING; ! // x_offset and y_offset define the starting corner of the actual graph x_offset = LBORDER_SPACE; ! if ( graphDef.getVerticalLabel() != null ) x_offset += nfont_height + LINE_PADDING; chartWidth = imgWidth - x_offset - RBORDER_SPACE - chart_lpadding - CHART_RPADDING; ! y_offset = UBORDER_SPACE; ! if ( graphDef.getTitle() != null ) // Title *always* gets a extra LF automatically y_offset += ((tfont_height + LINE_PADDING) * graphDef.getTitle().getLineCount() + tfont_height) + LINE_PADDING; chartHeight = imgHeight - commentBlock - y_offset - BBORDER_SPACE - CHART_UPADDING - CHART_BPADDING; ! // Create graphics object BufferedImage bImg = new BufferedImage( imgWidth, imgHeight, colorType ); Graphics2D graphics = (Graphics2D) bImg.getGraphics(); ! // Do the actual graphing calculateSeries(); // calculate all datasources ! plotImageBackground( graphics ); // draw the image background ! plotChart( graphics ); // draw the actual chart ! plotComments( graphics ); // draw all comment lines ! plotOverlay( graphics ); // draw a possible image overlay plotSignature( graphics ); // draw the JRobin signature ! // Dispose graphics context graphics.dispose(); - - return bImg; } ! ! // ================================================================ // -- Private methods --- 192,308 ---- chart_lpadding = ( graphDef.showMajorGridY() ? graphDef.getChartLeftPadding() : CHART_LPADDING_NM ); chart_bpadding = ( graphDef.showMajorGridX() ? CHART_BPADDING : CHART_BPADDING_NM ); ! // Size of all lines below chart commentBlock = 0; if ( graphDef.showLegend() ) ! commentBlock = graphDef.getCommentLineCount() * (nfont_height + LINE_PADDING) - LINE_PADDING; ! // x_offset and y_offset define the starting corner of the actual graph x_offset = LBORDER_SPACE; ! if ( graphDef.getVerticalLabel() != null ) x_offset += nfont_height + LINE_PADDING; chartWidth = imgWidth - x_offset - RBORDER_SPACE - chart_lpadding - CHART_RPADDING; ! y_offset = UBORDER_SPACE; ! if ( graphDef.getTitle() != null ) // Title *always* gets a extra LF automatically y_offset += ((tfont_height + LINE_PADDING) * graphDef.getTitle().getLineCount() + tfont_height) + LINE_PADDING; chartHeight = imgHeight - commentBlock - y_offset - BBORDER_SPACE - CHART_UPADDING - CHART_BPADDING; ! } ! ! /** ! * Creates the actual graph based on the GraphDef definition. ! * The graph is created as a <code>java.awt.image.BufferedImage</code>. ! * @param cWidth Width of the chart area in pixels. ! * @param cHeight Height of the chart area in pixels. ! * @return The created graph as a BufferedImage. ! * @throws RrdException Thrown in case of a JRobin specific error. ! * @throws IOException Thrown in case of a I/O related error. ! */ ! protected BufferedImage createImage( int cWidth, int cHeight, int colorType ) throws RrdException, IOException ! { ! calculateDimensions( cWidth, cHeight ); ! // Create graphics object BufferedImage bImg = new BufferedImage( imgWidth, imgHeight, colorType ); Graphics2D graphics = (Graphics2D) bImg.getGraphics(); ! ! render( graphics ); ! ! // Dispose graphics context ! graphics.dispose(); ! ! return bImg; ! } ! ! /** ! * Creates the actual graph based on the GraphDef definition. ! * The graph is created as a <code>java.awt.image.BufferedImage</code>. ! * @param cWidth Width of the entire image in pixels. ! * @param cHeight Height of the entire image in pixels. ! * @return The created graph as a BufferedImage. ! * @throws RrdException Thrown in case of a JRobin specific error. ! * @throws IOException Thrown in case of a I/O related error. ! */ ! protected BufferedImage createImageGlobal( int cWidth, int cHeight, int colorType ) throws RrdException, IOException ! { ! calculateDimensionsGlobal( cWidth, cHeight ); ! ! // Create graphics object ! BufferedImage bImg = new BufferedImage( imgWidth, imgHeight, colorType ); ! Graphics2D graphics = (Graphics2D) bImg.getGraphics(); ! ! render( graphics ); ! ! // Dispose graphics context ! graphics.dispose(); ! ! return bImg; ! } ! ! /** ! * Creates the actual graph based on the GraphDef definition. ! * The graph is rendered on the Graphics2D object passed as a parameter. ! * @param cWidth Width of the entire image in pixels. ! * @param cHeight Height of the entire image in pixels. ! * @param graphics The handle to the Graphics2D object to render the graph on. ! * @param useGlobal True if the dimensions specified are those of the entire image. ! * @throws RrdException Thrown in case of a JRobin specific error. ! * @throws IOException Thrown in case of a I/O related error. ! */ ! protected void renderImage( int cWidth, int cHeight, Graphics2D graphics, boolean useGlobal ) throws RrdException, IOException ! { ! if ( useGlobal ) ! calculateDimensionsGlobal( cWidth, cHeight ); ! else ! calculateDimensions( cWidth, cHeight ); ! ! render( graphics ); ! } ! ! /** ! * Renders the actual graph onto the specified Graphics2D object ! * @param graphics The handle to the Graphics2D object to render the graph on. ! * @throws RrdException Thrown in case of a JRobin specific error. ! * @throws IOException Thrown in case of a I/O related error. ! */ ! private void render( Graphics2D graphics ) throws RrdException, IOException ! { // Do the actual graphing calculateSeries(); // calculate all datasources ! plotImageBackground( graphics ); // draw the image background ! plotChart( graphics ); // draw the actual chart ! plotComments( graphics ); // draw all comment lines ! plotOverlay( graphics ); // draw a possible image overlay plotSignature( graphics ); // draw the JRobin signature ! // Dispose graphics context graphics.dispose(); } ! // ================================================================ // -- Private methods *************** *** 277,280 **** --- 319,323 ---- RrdDb rrd; String[] varList; + long finalEndTime = 0; boolean changingEndTime = false; *************** *** 285,289 **** int numDefs = graphDef.getNumDefs(); ! Cdef[] cdefList = graphDef.getCdefs(); int numCdefs = cdefList.length; --- 328,333 ---- int numDefs = graphDef.getNumDefs(); ! int numSdefs = graphDef.getNumSdefs(); ! Cdef[] cdefList = graphDef.getCdefs(); int numCdefs = cdefList.length; *************** *** 291,295 **** Pdef[] pdefList = graphDef.getPdefs(); int numPdefs = pdefList.length; ! // Set up the array with all datasources (both Def, Cdef and Pdef) sourc... [truncated message content] |
From: Sasa M. <sa...@us...> - 2004-05-30 10:16:09
|
Update of /cvsroot/jrobin/src/org/jrobin/core In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv24441/org/jrobin/core Modified Files: RrdNioBackendFactory.java Log Message: minor bug Index: RrdNioBackendFactory.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/core/RrdNioBackendFactory.java,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** RrdNioBackendFactory.java 30 May 2004 10:06:48 -0000 1.3 --- RrdNioBackendFactory.java 30 May 2004 10:16:00 -0000 1.4 *************** *** 36,40 **** /** See {@link #setSyncMode(int) for explanation } */ ! public static final int SYNC_DEFAULT = 0; // will sync() only on close() /** See {@link #setSyncMode(int) for explanation } */ public static final int SYNC_BEFOREUPDATE = 1; --- 36,40 ---- /** See {@link #setSyncMode(int) for explanation } */ ! public static final int SYNC_ONCLOSE = 0; // will sync() only on close() /** See {@link #setSyncMode(int) for explanation } */ public static final int SYNC_BEFOREUPDATE = 1; *************** *** 57,61 **** * in the persistent storage (disk file). * ! * @return Integer representing current synchronization mode (SYNC_DEFAULT, * SYNC_BEFOREUPDATE, SYNC_AFTERUPDATE, SYNC_BEFOREFETCH, SYNC_AFTERFETCH or * SYNC_BACKGROUND). See {@link #setSyncMode(int)} for full explanation of these return values. --- 57,61 ---- * in the persistent storage (disk file). * ! * @return Integer representing current synchronization mode (SYNC_ONCLOSE, * SYNC_BEFOREUPDATE, SYNC_AFTERUPDATE, SYNC_BEFOREFETCH, SYNC_AFTERFETCH or * SYNC_BACKGROUND). See {@link #setSyncMode(int)} for full explanation of these return values. *************** *** 70,74 **** * @param syncMode Desired synchronization mode. Possible values are:<p> * <ul> ! * <li>SYNC_DEFAULT: synchronization will be performed only when {@link RrdDb#close()} * is called (RRD file is closed) or when {@link RrdDb#sync()} method is called. * <li>SYNC_BEFOREUPDATE: synchronization will be performed before each {@link Sample#update()} --- 70,74 ---- * @param syncMode Desired synchronization mode. Possible values are:<p> * <ul> ! * <li>SYNC_ONCLOSE: synchronization will be performed only when {@link RrdDb#close()} * is called (RRD file is closed) or when {@link RrdDb#sync()} method is called. * <li>SYNC_BEFOREUPDATE: synchronization will be performed before each {@link Sample#update()} |
From: Sasa M. <sa...@us...> - 2004-05-30 10:10:45
|
Update of /cvsroot/jrobin/src In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv23637 Modified Files: StressTest.java Log Message: minor bug Index: StressTest.java =================================================================== RCS file: /cvsroot/jrobin/src/StressTest.java,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** StressTest.java 30 May 2004 10:06:47 -0000 1.5 --- StressTest.java 30 May 2004 10:10:23 -0000 1.6 *************** *** 118,122 **** } } ! rrd.close(); printLapTime("FINISHED: " + count + " samples stored"); // GRAPH --- 118,122 ---- } } ! RrdDbPool.getInstance().release(rrd); printLapTime("FINISHED: " + count + " samples stored"); // GRAPH |
From: Sasa M. <sa...@us...> - 2004-05-30 10:07:03
|
Update of /cvsroot/jrobin/src/org/jrobin/core In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv23240/org/jrobin/core Modified Files: RrdBackend.java RrdDb.java RrdNioBackend.java RrdNioBackendFactory.java Log Message: greatly improved RrdNioBackend. By default RrdNioBackend is flushed to the disc every 60 seconds from a separate thread. Index: RrdBackend.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/core/RrdBackend.java,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** RrdBackend.java 28 May 2004 10:22:47 -0000 1.3 --- RrdBackend.java 30 May 2004 10:06:47 -0000 1.4 *************** *** 41,45 **** * <li>{@link RrdNioBackend}: objects of this class are created from the * {@link RrdNioBackendFactory} class. The backend uses java.io.* and java.nio.* ! * classes (mapped ByteBuffer) to store RRD data in files on the disk. * * <li>{@link RrdMemoryBackend}: objects of this class are created from the --- 41,47 ---- * <li>{@link RrdNioBackend}: objects of this class are created from the * {@link RrdNioBackendFactory} class. The backend uses java.io.* and java.nio.* ! * classes (mapped ByteBuffer) to store RRD data in files on the disk. This backend is fast, very fast, ! * but consumes a lot of memory (borrowed not from the JVM but from the underlying operating system ! * directly). * * <li>{@link RrdMemoryBackend}: objects of this class are created from the *************** *** 141,144 **** --- 143,181 ---- /** + * Method called by the framework immediatelly before RRD update operation starts. This method + * does nothing, but can be overriden in subclasses. + */ + protected void beforeUpdate() throws IOException { + } + + /** + * Method called by the framework immediatelly after RRD update operation is completed. This method + * does nothing, but can be overriden in subclasses. + */ + protected void afterUpdate() throws IOException { + } + + /** + * Method called by the framework immediatelly before RRD fetch operation starts. This method + * does nothing, but can be overriden in subclasses. + */ + protected void beforeFetch() throws IOException { + } + + /** + * Method called by the framework immediatelly after RRD fetch operation is completed. This method + * does nothing, but can be overriden in subclasses. + */ + protected void afterFetch() throws IOException { + } + + /** + * Method called by the framework immediatelly after RrdDb obejct is created. This method + * does nothing, but can be overriden in subclasses. + */ + protected void afterCreate() throws IOException { + } + + /** * This method forces all data cached in memory but not yet stored in the persistant * storage, to be stored in it. In the base class this method does nothing but Index: RrdNioBackend.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/core/RrdNioBackend.java,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** RrdNioBackend.java 28 May 2004 10:22:47 -0000 1.2 --- RrdNioBackend.java 30 May 2004 10:06:48 -0000 1.3 *************** *** 29,32 **** --- 29,34 ---- import java.nio.channels.FileChannel; import java.nio.MappedByteBuffer; + import java.util.TimerTask; + import java.util.Timer; /** *************** *** 35,45 **** */ public class RrdNioBackend extends RrdFileBackend { ! FileChannel.MapMode mapMode; MappedByteBuffer byteBuffer; ! RrdNioBackend(String path, boolean readOnly, int lockMode) throws IOException { super(path, readOnly, lockMode); ! mapMode = readOnly? FileChannel.MapMode.READ_ONLY: FileChannel.MapMode.READ_WRITE; ! byteBuffer = file.getChannel().map(mapMode, 0, getLength()); } --- 37,65 ---- */ public class RrdNioBackend extends RrdFileBackend { ! private int syncMode; MappedByteBuffer byteBuffer; ! private Timer syncTimer; ! ! RrdNioBackend(String path, boolean readOnly, int lockMode, int syncMode, int syncPeriod) ! throws IOException { super(path, readOnly, lockMode); ! this.syncMode = syncMode; ! FileChannel.MapMode mapMode = ! readOnly? FileChannel.MapMode.READ_ONLY: FileChannel.MapMode.READ_WRITE; ! this.byteBuffer = file.getChannel().map(mapMode, 0, getLength()); ! if(syncMode == RrdNioBackendFactory.SYNC_BACKGROUND && !readOnly) { ! createSyncTask(syncPeriod); ! } ! } ! ! private void createSyncTask(int syncPeriod) { ! TimerTask syncTask = new TimerTask() { ! public void run() { ! sync(); ! } ! }; ! syncTimer = new Timer(true); ! syncTimer.schedule(syncTask, syncPeriod * 1000L, syncPeriod * 1000L); } *************** *** 52,56 **** protected void setLength(long length) throws IOException { super.setLength(length); ! byteBuffer = file.getChannel().map(mapMode, 0, length); } --- 72,76 ---- protected void setLength(long length) throws IOException { super.setLength(length); ! byteBuffer = file.getChannel().map(FileChannel.MapMode.READ_WRITE, 0, length); } *************** *** 59,67 **** * @param offset Starting file offset * @param b Bytes to be written. - * @throws IOException Thrown in case of I/O error */ ! protected void write(long offset, byte[] b) throws IOException { ! byteBuffer.position((int)offset); ! byteBuffer.put(b); } --- 79,88 ---- * @param offset Starting file offset * @param b Bytes to be written. */ ! protected void write(long offset, byte[] b) { ! synchronized(byteBuffer) { ! byteBuffer.position((int)offset); ! byteBuffer.put(b); ! } } *************** *** 70,78 **** * @param offset Starting file offset * @param b Buffer which receives bytes read from the file. - * @throws IOException Thrown in case of I/O error. */ ! protected void read(long offset, byte[] b) throws IOException { ! byteBuffer.position((int)offset); ! byteBuffer.get(b); } --- 91,100 ---- * @param offset Starting file offset * @param b Buffer which receives bytes read from the file. */ ! protected void read(long offset, byte[] b) { ! synchronized(byteBuffer) { ! byteBuffer.position((int)offset); ! byteBuffer.get(b); ! } } *************** *** 82,86 **** */ public void close() throws IOException { ! super.close(); } --- 104,111 ---- */ public void close() throws IOException { ! if(syncTimer != null) { ! syncTimer.cancel(); ! } ! super.close(); // calls sync() } *************** *** 90,99 **** * This method is automatically invoked when the {@link #close()} * method is called. In other words, you don't have to call sync() before you call close().<p> - * - * @throws IOException Thrown in case of I/O error */ ! protected void sync() throws IOException { ! byteBuffer.force(); } } --- 115,147 ---- * This method is automatically invoked when the {@link #close()} * method is called. In other words, you don't have to call sync() before you call close().<p> */ ! protected void sync() { ! synchronized(byteBuffer) { ! byteBuffer.force(); ! } ! } ! ! protected void beforeUpdate() { ! if(syncMode == RrdNioBackendFactory.SYNC_BEFOREUPDATE) { ! sync(); ! } } + protected void afterUpdate() { + if(syncMode == RrdNioBackendFactory.SYNC_AFTERUPDATE) { + sync(); + } + } + + protected void beforeFetch() { + if(syncMode == RrdNioBackendFactory.SYNC_BEFOREFETCH) { + sync(); + } + } + + protected void afterFetch() { + if(syncMode == RrdNioBackendFactory.SYNC_AFTERFETCH) { + sync(); + } + } } Index: RrdDb.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/core/RrdDb.java,v retrieving revision 1.17 retrieving revision 1.18 diff -C2 -d -r1.17 -r1.18 *** RrdDb.java 28 May 2004 10:22:47 -0000 1.17 --- RrdDb.java 30 May 2004 10:06:47 -0000 1.18 *************** *** 178,181 **** --- 178,182 ---- archives[i] = new Archive(this, arcDefs[i]); } + backend.afterCreate(); } *************** *** 321,324 **** --- 322,326 ---- // XMLReader is a rather huge DOM tree, release memory ASAP reader = null; + backend.afterCreate(); } *************** *** 463,466 **** --- 465,469 ---- throw new RrdException("RRD already closed, cannot store this sample"); } + backend.beforeUpdate(); long newTime = sample.getTime(); long lastTime = header.getLastUpdateTime(); *************** *** 475,478 **** --- 478,482 ---- } header.setLastUpdateTime(newTime); + backend.afterUpdate(); } *************** *** 481,486 **** --- 485,492 ---- throw new RrdException("RRD already closed, cannot fetch data"); } + backend.beforeFetch(); Archive archive = findMatchingArchive(request); FetchPoint[] points = archive.fetch(request); + backend.afterFetch(); return points; } *************** *** 490,495 **** --- 496,503 ---- throw new RrdException("RRD already closed, cannot fetch data"); } + backend.beforeFetch(); Archive archive = findMatchingArchive(request); FetchData fetchData = archive.fetchData(request); + backend.afterFetch(); return fetchData; } *************** *** 909,912 **** --- 917,923 ---- * synchronizes all data in memory with the data in the persisant storage.<p> * + * When this method returns it is guaranteed that RRD data in the persistent storage is + * synchronized with the RrdDb data in memory.<p> + * * @throws IOException Thrown in case of I/O error */ *************** *** 915,917 **** --- 926,939 ---- } + /** + * Sets default backend factory to be used. This method is just an alias for + * {@link RrdBackendFactory#setDefaultFactory(java.lang.String)}.<p> + * @param factoryName Name of the backend factory to be set as default. + * @throws RrdException Thrown if invalid factory name is supplied, or not called + * before the first backend object (before the first RrdDb object) is created. + */ + public static void setDefaultFactory(String factoryName) throws RrdException { + RrdBackendFactory.setDefaultFactory(factoryName); + } + } Index: RrdNioBackendFactory.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/core/RrdNioBackendFactory.java,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** RrdNioBackendFactory.java 25 May 2004 11:35:58 -0000 1.2 --- RrdNioBackendFactory.java 30 May 2004 10:06:48 -0000 1.3 *************** *** 35,38 **** --- 35,112 ---- public static final String NAME = "NIO"; + /** See {@link #setSyncMode(int) for explanation } */ + public static final int SYNC_DEFAULT = 0; // will sync() only on close() + /** See {@link #setSyncMode(int) for explanation } */ + public static final int SYNC_BEFOREUPDATE = 1; + /** See {@link #setSyncMode(int) for explanation } */ + public static final int SYNC_AFTERUPDATE = 2; + /** See {@link #setSyncMode(int) for explanation } */ + public static final int SYNC_BEFOREFETCH = 3; + /** See {@link #setSyncMode(int) for explanation } */ + public static final int SYNC_AFTERFETCH = 4; + /** See {@link #setSyncMode(int) for explanation } */ + public static final int SYNC_BACKGROUND = 5; + /** See {@link #setSyncPeriod(int)} for explanation */ + public static final int DEFAULT_SYNC_PERIOD = 60; // seconds + + private static int syncMode = SYNC_BACKGROUND; + private static int syncPeriod = DEFAULT_SYNC_PERIOD; + + /** + * Returns the current synchronization mode between backend data in memory and data + * in the persistent storage (disk file). + * + * @return Integer representing current synchronization mode (SYNC_DEFAULT, + * SYNC_BEFOREUPDATE, SYNC_AFTERUPDATE, SYNC_BEFOREFETCH, SYNC_AFTERFETCH or + * SYNC_BACKGROUND). See {@link #setSyncMode(int)} for full explanation of these return values. + */ + public static int getSyncMode() { + return syncMode; + } + + /** + * Sets the current synchronization mode between backend data in memory (backend cache) and + * RRD data in the persistant storage (disk file).<p> + * @param syncMode Desired synchronization mode. Possible values are:<p> + * <ul> + * <li>SYNC_DEFAULT: synchronization will be performed only when {@link RrdDb#close()} + * is called (RRD file is closed) or when {@link RrdDb#sync()} method is called. + * <li>SYNC_BEFOREUPDATE: synchronization will be performed before each {@link Sample#update()} + * call (right before RRD file is about to be updated). + * <li>SYNC_AFTERUPDATE: synchronization will be performed after each {@link Sample#update()} + * call (right after RRD file is updated). + * <li>SYNC_BEFOREFETCH: synchronization will be performed before each + * {@link FetchRequest#fetchData()} call (right before data is about to be fetched from a RRD file, + * for example for graph creation) + * <li>SYNC_AFTERFETCH: synchronization will be performed after each + * {@link FetchRequest#fetchData()} call (right after data is fetched from a RRD file) + * <li>SYNC_BACKGROUND (<b>default</b>): synchronization will be performed automatically + * from a separate thread on a regular basis. Period of time between the two consecutive + * synchronizations can be controlled with {@link #setSyncPeriod(int)}. + * </ul> + */ + public static void setSyncMode(int syncMode) { + RrdNioBackendFactory.syncMode = syncMode; + } + + /** + * Returns time between two consecutive background synchronizations. If not changed via + * {@link #setSyncPeriod(int)} method call, defaults to DEFAULT_SYNC_PERIOD (60 seconds). + * See {@link #setSyncPeriod(int)} for more information. + * @return Time in seconds between consecutive background synchronizations. + */ + public static int getSyncPeriod() { + return syncPeriod; + } + + /** + * Sets time between consecutive background synchronizations. Method is effective only if + * synchronization mode is set to SYNC_BACKGROUND. + * @param syncPeriod Time in seconds between consecutive background synchronizations. + */ + public static void setSyncPeriod(int syncPeriod) { + RrdNioBackendFactory.syncPeriod = syncPeriod; + } + /** * Creates RrdNioBackend object for the given file path. *************** *** 46,50 **** */ protected RrdBackend open(String path, boolean readOnly, int lockMode) throws IOException { ! return new RrdNioBackend(path, readOnly, lockMode); } --- 120,124 ---- */ protected RrdBackend open(String path, boolean readOnly, int lockMode) throws IOException { ! return new RrdNioBackend(path, readOnly, lockMode, syncMode, syncPeriod); } |
From: Sasa M. <sa...@us...> - 2004-05-30 10:06:57
|
Update of /cvsroot/jrobin/src In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv23240 Modified Files: Demo.java StressTest.java Log Message: greatly improved RrdNioBackend. By default RrdNioBackend is flushed to the disc every 60 seconds from a separate thread. Index: Demo.java =================================================================== RCS file: /cvsroot/jrobin/src/Demo.java,v retrieving revision 1.17 retrieving revision 1.18 diff -C2 -d -r1.17 -r1.18 *** Demo.java 20 May 2004 10:29:31 -0000 1.17 --- Demo.java 30 May 2004 10:06:46 -0000 1.18 *************** *** 36,51 **** class Demo { ! static final long SEED = 1909752002L; ! static final Random RANDOM = new Random(SEED); static final String FILE = "demo"; - static final String FACTORY_NAME = "FILE"; 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"); --- 36,51 ---- class Demo { ! static final String FACTORY_NAME = "FILE"; ! ! static final long SEED = 1909752002L; static final Random RANDOM = new Random(SEED); static final String FILE = "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 { + RrdDb.setDefaultFactory(FACTORY_NAME); // setup println("== Starting demo"); Index: StressTest.java =================================================================== RCS file: /cvsroot/jrobin/src/StressTest.java,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** StressTest.java 24 May 2004 15:02:28 -0000 1.4 --- StressTest.java 30 May 2004 10:06:47 -0000 1.5 *************** *** 35,55 **** class StressTest { ! public static final String RRD_BACKEND_FACTORY = "NIO"; ! public static final String RRD_PATH = Util.getJRobinDemoPath("stress.rrd"); ! public static final long RRD_START = 946710000L; ! public static final long RRD_STEP = 30; ! public static final String RRD_DATASOURCE_NAME = "T"; ! public static final int RRD_DATASOURCE_COUNT = 6; ! public static final long TIME_START = 1060142010L; ! public static final long TIME_END = 1080013472L; ! public static final String PNG_PATH = Util.getJRobinDemoPath("stress.png"); ! public static final int PNG_WIDTH = 400; ! public static final int PNG_HEIGHT = 250; ! public static void printLapTime(String message) { System.out.println(message + " " + Util.getLapTime()); } --- 35,55 ---- class StressTest { ! static final String FACTORY_NAME = "NIO"; ! static final String RRD_PATH = Util.getJRobinDemoPath("stress.rrd"); ! static final long RRD_START = 946710000L; ! static final long RRD_STEP = 30; ! static final String RRD_DATASOURCE_NAME = "T"; ! static final int RRD_DATASOURCE_COUNT = 6; ! static final long TIME_START = 1060142010L; ! static final long TIME_END = 1080013472L; ! static final String PNG_PATH = Util.getJRobinDemoPath("stress.png"); ! static final int PNG_WIDTH = 400; ! static final int PNG_HEIGHT = 250; ! static void printLapTime(String message) { System.out.println(message + " " + Util.getLapTime()); } *************** *** 75,80 **** System.out.println("********************************************************************"); printLapTime("Starting demo at " + new Date()); ! RrdBackendFactory.setDefaultFactory(RRD_BACKEND_FACTORY); ! printLapTime("Backend factory set to " + RRD_BACKEND_FACTORY); // create RRD database printLapTime("Creating RRD definition"); --- 75,80 ---- System.out.println("********************************************************************"); printLapTime("Starting demo at " + new Date()); ! RrdDb.setDefaultFactory(FACTORY_NAME); ! printLapTime("Backend factory set to " + FACTORY_NAME); // create RRD database printLapTime("Creating RRD definition"); *************** *** 98,102 **** def.addArchive("MAX", 0.5, 1440, 50000); printLapTime("Definition created, creating RRD file"); ! RrdDb rrd = new RrdDb(def); printLapTime("RRD file created: " + RRD_PATH); BufferedReader r = new BufferedReader(new FileReader(args[0])); --- 98,102 ---- def.addArchive("MAX", 0.5, 1440, 50000); printLapTime("Definition created, creating RRD file"); ! RrdDb rrd = RrdDbPool.getInstance().requestRrdDb(def); printLapTime("RRD file created: " + RRD_PATH); BufferedReader r = new BufferedReader(new FileReader(args[0])); *************** *** 140,144 **** gdef.comment("\nOriginal data provided by diy-zoning.sf.net@c"); printLapTime("Graph definition created"); ! RrdGraph g = new RrdGraph(gdef); g.saveAsPNG(PNG_PATH, PNG_WIDTH, PNG_HEIGHT); printLapTime("Graph saved: " + PNG_PATH); --- 140,144 ---- gdef.comment("\nOriginal data provided by diy-zoning.sf.net@c"); printLapTime("Graph definition created"); ! RrdGraph g = new RrdGraph(gdef, true); g.saveAsPNG(PNG_PATH, PNG_WIDTH, PNG_HEIGHT); printLapTime("Graph saved: " + PNG_PATH); |
Update of /cvsroot/jrobin/src/org/jrobin/core In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv18483/org/jrobin/core Modified Files: FetchRequest.java RrdBackend.java RrdDb.java RrdDbPool.java RrdFileBackend.java RrdNioBackend.java Sample.java Log Message: small tweaks Index: RrdDbPool.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/core/RrdDbPool.java,v retrieving revision 1.7 retrieving revision 1.8 diff -C2 -d -r1.7 -r1.8 *** RrdDbPool.java 20 May 2004 10:29:33 -0000 1.7 --- RrdDbPool.java 28 May 2004 10:22:47 -0000 1.8 *************** *** 112,115 **** --- 112,116 ---- private Map rrdMap = new HashMap(); private List rrdGcList = new LinkedList(); + private RrdBackendFactory factory; /** *************** *** 154,158 **** } else { // not found, open it ! RrdDb rrdDb = new RrdDb(path); addRrdEntry(keypath, rrdDb); return rrdDb; --- 155,159 ---- } else { // not found, open it ! RrdDb rrdDb = new RrdDb(path, getFactory()); addRrdEntry(keypath, rrdDb); return rrdDb; *************** *** 174,178 **** String keypath = getCanonicalPath(path); prooveInactive(keypath); ! RrdDb rrdDb = new RrdDb(path, xmlPath); addRrdEntry(keypath, rrdDb); return rrdDb; --- 175,179 ---- String keypath = getCanonicalPath(path); prooveInactive(keypath); ! RrdDb rrdDb = new RrdDb(path, xmlPath, getFactory()); addRrdEntry(keypath, rrdDb); return rrdDb; *************** *** 191,195 **** String keypath = getCanonicalPath(path); prooveInactive(keypath); ! RrdDb rrdDb = new RrdDb(rrdDef); addRrdEntry(keypath, rrdDb); return rrdDb; --- 192,196 ---- String keypath = getCanonicalPath(path); prooveInactive(keypath); ! RrdDb rrdDb = new RrdDb(rrdDef, getFactory()); addRrdEntry(keypath, rrdDb); return rrdDb; *************** *** 370,373 **** --- 371,386 ---- } + private RrdBackendFactory getFactory() throws RrdException { + if(factory == null) { + factory = RrdBackendFactory.getDefaultFactory(); + if(!(factory instanceof RrdFileBackendFactory)) { + factory = null; + throw new RrdException( + "RrdDbPool cannot work with factories not derived from RrdFileBackendFactory"); + } + } + return factory; + } + private class RrdEntry { private RrdDb rrdDb; Index: RrdBackend.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/core/RrdBackend.java,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** RrdBackend.java 21 May 2004 12:30:00 -0000 1.2 --- RrdBackend.java 28 May 2004 10:22:47 -0000 1.3 *************** *** 140,143 **** --- 140,153 ---- public abstract void close() throws IOException; + /** + * This method forces all data cached in memory but not yet stored in the persistant + * storage, to be stored in it. In the base class this method does nothing but + * subclasses might provide real functionality.<p> + * + * @throws IOException Thrown in case of I/O error + */ + protected void sync() throws IOException { + } + final void writeInt(long offset, int value) throws IOException { write(offset, getIntBytes(value)); Index: RrdNioBackend.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/core/RrdNioBackend.java,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** RrdNioBackend.java 20 May 2004 10:34:00 -0000 1.1 --- RrdNioBackend.java 28 May 2004 10:22:47 -0000 1.2 *************** *** 82,88 **** */ public void close() throws IOException { - byteBuffer.force(); super.close(); } } --- 82,99 ---- */ public void close() throws IOException { super.close(); } + /** + * This method forces all data cached in memory but not yet stored in the file, + * to be stored in it. RrdNioBackend uses (a lot of) memory to cache I/O data. + * This method is automatically invoked when the {@link #close()} + * method is called. In other words, you don't have to call sync() before you call close().<p> + * + * @throws IOException Thrown in case of I/O error + */ + protected void sync() throws IOException { + byteBuffer.force(); + } + } Index: FetchRequest.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/core/FetchRequest.java,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** FetchRequest.java 20 May 2004 10:29:32 -0000 1.5 --- FetchRequest.java 28 May 2004 10:22:47 -0000 1.6 *************** *** 168,174 **** */ public FetchPoint[] fetch() throws RrdException, IOException { ! synchronized(parentDb) { ! return parentDb.fetch(this); ! } } --- 168,172 ---- */ public FetchPoint[] fetch() throws RrdException, IOException { ! return parentDb.fetch(this); } *************** *** 182,188 **** */ public FetchData fetchData() throws RrdException, IOException { ! synchronized(parentDb) { ! return parentDb.fetchData(this); ! } } --- 180,184 ---- */ public FetchData fetchData() throws RrdException, IOException { ! return parentDb.fetchData(this); } Index: RrdFileBackend.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/core/RrdFileBackend.java,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** RrdFileBackend.java 21 May 2004 10:40:50 -0000 1.2 --- RrdFileBackend.java 28 May 2004 10:22:47 -0000 1.3 *************** *** 82,85 **** --- 82,86 ---- */ public void close() throws IOException { + sync(); unlockFile(); file.close(); Index: RrdDb.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/core/RrdDb.java,v retrieving revision 1.16 retrieving revision 1.17 diff -C2 -d -r1.16 -r1.17 *** RrdDb.java 20 May 2004 10:29:32 -0000 1.16 --- RrdDb.java 28 May 2004 10:22:47 -0000 1.17 *************** *** 459,463 **** } ! void store(Sample sample) throws IOException, RrdException { if(closed) { throw new RrdException("RRD already closed, cannot store this sample"); --- 459,463 ---- } ! synchronized void store(Sample sample) throws IOException, RrdException { if(closed) { throw new RrdException("RRD already closed, cannot store this sample"); *************** *** 477,481 **** } ! FetchPoint[] fetch(FetchRequest request) throws IOException, RrdException { if(closed) { throw new RrdException("RRD already closed, cannot fetch data"); --- 477,481 ---- } ! synchronized FetchPoint[] fetch(FetchRequest request) throws IOException, RrdException { if(closed) { throw new RrdException("RRD already closed, cannot fetch data"); *************** *** 486,490 **** } ! FetchData fetchData(FetchRequest request) throws IOException, RrdException { if(closed) { throw new RrdException("RRD already closed, cannot fetch data"); --- 486,490 ---- } ! synchronized FetchData fetchData(FetchRequest request) throws IOException, RrdException { if(closed) { throw new RrdException("RRD already closed, cannot fetch data"); *************** *** 696,700 **** * @return Last update time (in seconds). */ ! public long getLastUpdateTime() throws IOException { return header.getLastUpdateTime(); } --- 696,700 ---- * @return Last update time (in seconds). */ ! public synchronized long getLastUpdateTime() throws IOException { return header.getLastUpdateTime(); } *************** *** 717,721 **** * @throws RrdException Thrown in case of JRobin specific error. */ ! public RrdDef getRrdDef() throws RrdException, IOException { // set header long startTime = header.getLastUpdateTime(); --- 717,721 ---- * @throws RrdException Thrown in case of JRobin specific error. */ ! public synchronized RrdDef getRrdDef() throws RrdException, IOException { // set header long startTime = header.getLastUpdateTime(); *************** *** 785,789 **** * @throws RrdException Thrown if supplied argument is not a compatible RrdDb object */ ! public void copyStateTo(RrdUpdater other) throws IOException, RrdException { if(!(other instanceof RrdDb)) { throw new RrdException( --- 785,789 ---- * @throws RrdException Thrown if supplied argument is not a compatible RrdDb object */ ! public synchronized void copyStateTo(RrdUpdater other) throws IOException, RrdException { if(!(other instanceof RrdDb)) { throw new RrdException( *************** *** 898,904 **** * @throws IOException Thrown in case of I/O related error. */ ! public byte[] getBytes() throws IOException { return backend.readAll(); } } --- 898,917 ---- * @throws IOException Thrown in case of I/O related error. */ ! public synchronized byte[] getBytes() throws IOException { return backend.readAll(); } + /** + * This method forces all RRD data cached in memory but not yet stored in the persistant + * storage, to be stored in it. This method should be used only if you RrdDb object uses + * RrdBackend which implements any kind of data caching (like {@link RrdNioBackend}). This method + * need not be called before the {@link #close()} method call since the close() method always + * synchronizes all data in memory with the data in the persisant storage.<p> + * + * @throws IOException Thrown in case of I/O error + */ + public synchronized void sync() throws IOException { + backend.sync(); + } + } Index: Sample.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/core/Sample.java,v retrieving revision 1.7 retrieving revision 1.8 diff -C2 -d -r1.7 -r1.8 *** Sample.java 20 May 2004 10:29:33 -0000 1.7 --- Sample.java 28 May 2004 10:22:47 -0000 1.8 *************** *** 197,203 **** */ public void update() throws IOException, RrdException { ! synchronized(parentDb) { ! parentDb.store(this); ! } clearCurrentValues(); } --- 197,201 ---- */ public void update() throws IOException, RrdException { ! parentDb.store(this); clearCurrentValues(); } |
From: Sasa M. <sa...@us...> - 2004-05-25 11:36:17
|
Update of /cvsroot/jrobin/src/org/jrobin/core In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv12327/org/jrobin/core Modified Files: RrdBackendFactory.java RrdFileBackendFactory.java RrdNioBackendFactory.java Log Message: fixed javadoc Index: RrdFileBackendFactory.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/core/RrdFileBackendFactory.java,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** RrdFileBackendFactory.java 20 May 2004 14:49:29 -0000 1.2 --- RrdFileBackendFactory.java 25 May 2004 11:35:58 -0000 1.3 *************** *** 42,47 **** * @param readOnly True, if the file should be accessed in read/only mode. * False otherwise. ! * @param lockMode One of the following constants: {@link RrdDb.NO_LOCKS}, ! * {@link RrdDb.EXCEPTION_IF_LOCKED} or {@link RrdDb.WAIT_IF_LOCKED}. * @return RrdFileBackend object which handles all I/O operations for the given file path * @throws IOException Thrown in case of I/O error. --- 42,47 ---- * @param readOnly True, if the file should be accessed in read/only mode. * False otherwise. ! * @param lockMode One of the following constants: {@link RrdDb#NO_LOCKS}, ! * {@link RrdDb#EXCEPTION_IF_LOCKED} or {@link RrdDb#WAIT_IF_LOCKED}. * @return RrdFileBackend object which handles all I/O operations for the given file path * @throws IOException Thrown in case of I/O error. Index: RrdBackendFactory.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/core/RrdBackendFactory.java,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** RrdBackendFactory.java 24 May 2004 15:02:29 -0000 1.4 --- RrdBackendFactory.java 25 May 2004 11:35:58 -0000 1.5 *************** *** 157,162 **** * @param readOnly True, if the storage should be accessed in read/only mode. * False otherwise. ! * @param lockMode One of the following constants: {@link RrdDb.NO_LOCKS}, ! * {@link RrdDb.EXCEPTION_IF_LOCKED} or {@link RrdDb.WAIT_IF_LOCKED}. * @return Backend object which handles all I/O operations for the given storage path * @throws IOException Thrown in case of I/O error. --- 157,162 ---- * @param readOnly True, if the storage should be accessed in read/only mode. * False otherwise. ! * @param lockMode One of the following constants: {@link RrdDb#NO_LOCKS}, ! * {@link RrdDb#EXCEPTION_IF_LOCKED} or {@link RrdDb#WAIT_IF_LOCKED}. * @return Backend object which handles all I/O operations for the given storage path * @throws IOException Thrown in case of I/O error. Index: RrdNioBackendFactory.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/core/RrdNioBackendFactory.java,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** RrdNioBackendFactory.java 20 May 2004 10:34:00 -0000 1.1 --- RrdNioBackendFactory.java 25 May 2004 11:35:58 -0000 1.2 *************** *** 40,45 **** * @param readOnly True, if the file should be accessed in read/only mode. * False otherwise. ! * @param lockMode One of the following constants: {@link RrdDb.NO_LOCKS}, ! * {@link RrdDb.EXCEPTION_IF_LOCKED} or {@link RrdDb.WAIT_IF_LOCKED}. * @return RrdNioBackend object which handles all I/O operations for the given file path * @throws IOException Thrown in case of I/O error. --- 40,45 ---- * @param readOnly True, if the file should be accessed in read/only mode. * False otherwise. ! * @param lockMode One of the following constants: {@link RrdDb#NO_LOCKS}, ! * {@link RrdDb#EXCEPTION_IF_LOCKED} or {@link RrdDb#WAIT_IF_LOCKED}. * @return RrdNioBackend object which handles all I/O operations for the given file path * @throws IOException Thrown in case of I/O error. |