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
|
Update of /cvsroot/jrobin/src/org/jrobin/graph In directory sc8-pr-cvs6.sourceforge.net:/tmp/cvs-serv17479/src/org/jrobin/graph Removed Files: ValueAxisUnit.java Title.java Grapher.java LinearInterpolator.java TimeAxisUnit.java ChartGraphics.java Plottable.java CubicSplineInterpolator.java ChartPanel.java Legend.java RrdExportDef.java Print.java GridRange.java Gprint.java TimeGrid.java ValueFormatter.java LegendMarker.java ValueExtractor.java CustomLine.java Comment.java JpegImageWriteParam.java TimeMarker.java FetchSourceList.java RrdExportDefTemplate.java ExportData.java CustomArea.java PlotDef.java ValueGrid.java ValueMarker.java TimeAxisLabel.java FetchSource.java RrdExport.java TimeText.java RrdExporter.java RpnCalculator.java Log Message: this stuff is all broken, and it was not in the jrobinlite tarball, which is what was used to make the 1.5.4 jar --- Legend.java DELETED --- --- CustomArea.java DELETED --- --- LegendMarker.java DELETED --- --- TimeGrid.java DELETED --- --- RrdExportDef.java DELETED --- --- ValueFormatter.java DELETED --- --- LinearInterpolator.java DELETED --- --- TimeAxisLabel.java DELETED --- --- GridRange.java DELETED --- --- TimeText.java DELETED --- --- RrdExporter.java DELETED --- --- RpnCalculator.java DELETED --- --- FetchSource.java DELETED --- --- Plottable.java DELETED --- --- Title.java DELETED --- --- ValueGrid.java DELETED --- --- RrdExportDefTemplate.java DELETED --- --- Gprint.java DELETED --- --- Comment.java DELETED --- --- ChartGraphics.java DELETED --- --- CubicSplineInterpolator.java DELETED --- --- ValueExtractor.java DELETED --- --- Grapher.java DELETED --- --- TimeAxisUnit.java DELETED --- --- Print.java DELETED --- --- PlotDef.java DELETED --- --- CustomLine.java DELETED --- --- ValueAxisUnit.java DELETED --- --- ExportData.java DELETED --- --- TimeMarker.java DELETED --- --- ChartPanel.java DELETED --- --- RrdExport.java DELETED --- --- FetchSourceList.java DELETED --- --- JpegImageWriteParam.java DELETED --- --- ValueMarker.java DELETED --- |
From: Benjamin R. <ran...@us...> - 2007-07-29 01:41:50
|
Update of /cvsroot/jrobin/src/org/jrobin/demo/graph In directory sc8-pr-cvs6.sourceforge.net:/tmp/cvs-serv17479/src/org/jrobin/demo/graph Removed Files: ExportImportDemo.java SwingDemo.java LazyDemo.java LazyDemoOpener.java SwingDemoPanel.java ExportExportDemo.java GraphTemplate.java ExportTemplate.java Log Message: this stuff is all broken, and it was not in the jrobinlite tarball, which is what was used to make the 1.5.4 jar --- GraphTemplate.java DELETED --- --- ExportTemplate.java DELETED --- --- LazyDemoOpener.java DELETED --- --- ExportImportDemo.java DELETED --- --- SwingDemoPanel.java DELETED --- --- ExportExportDemo.java DELETED --- --- SwingDemo.java DELETED --- --- LazyDemo.java DELETED --- |
From: Benjamin R. <ran...@us...> - 2007-07-29 01:41:49
|
Update of /cvsroot/jrobin/maven In directory sc8-pr-cvs6.sourceforge.net:/tmp/cvs-serv17479 Modified Files: pom.xml Added Files: .classpath .project Log Message: this stuff is all broken, and it was not in the jrobinlite tarball, which is what was used to make the 1.5.4 jar --- NEW FILE: .project --- <?xml version="1.0" encoding="UTF-8"?> <projectDescription> <name>jrobin</name> <comment></comment> <projects> </projects> <buildSpec> <buildCommand> <name>org.eclipse.jdt.core.javabuilder</name> <arguments> </arguments> </buildCommand> <buildCommand> <name>org.maven.ide.eclipse.maven2Builder</name> <arguments> </arguments> </buildCommand> </buildSpec> <natures> <nature>org.eclipse.jdt.core.javanature</nature> <nature>org.maven.ide.eclipse.maven2Nature</nature> </natures> </projectDescription> Index: pom.xml =================================================================== RCS file: /cvsroot/jrobin/maven/pom.xml,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** pom.xml 29 Jul 2007 00:59:18 -0000 1.3 --- pom.xml 29 Jul 2007 01:41:46 -0000 1.4 *************** *** 17,30 **** <scope>test</scope> </dependency> - <dependency> - <groupId>org.apache.xmlrpc</groupId> - <artifactId>xmlrpc-client</artifactId> - <version>3.0</version> - </dependency> - <dependency> - <groupId>westhawk</groupId> - <artifactId>snmp</artifactId> - <version>4_13</version> - </dependency> </dependencies> </project> --- 17,20 ---- --- NEW FILE: .classpath --- <?xml version="1.0" encoding="UTF-8"?> <classpath> <classpathentry kind="src" path="src"/> <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/> <classpathentry kind="con" path="org.maven.ide.eclipse.MAVEN2_CLASSPATH_CONTAINER"/> <classpathentry kind="output" path="target/classes"/> </classpath> |
From: Benjamin R. <ran...@us...> - 2007-07-29 01:41:49
|
Update of /cvsroot/jrobin/src/org/jrobin/core In directory sc8-pr-cvs6.sourceforge.net:/tmp/cvs-serv17479/src/org/jrobin/core Removed Files: RrdOpener.java FetchPoint.java RrdDataSet.java Log Message: this stuff is all broken, and it was not in the jrobinlite tarball, which is what was used to make the 1.5.4 jar --- RrdDataSet.java DELETED --- --- FetchPoint.java DELETED --- --- RrdOpener.java DELETED --- |
From: Benjamin R. <ran...@us...> - 2007-07-29 01:41:42
|
Update of /cvsroot/jrobin/maven/.settings In directory sc8-pr-cvs6.sourceforge.net:/tmp/cvs-serv17463/.settings Log Message: Directory /cvsroot/jrobin/maven/.settings added to the repository |
From: Benjamin R. <ran...@us...> - 2007-07-29 00:59:21
|
Update of /cvsroot/jrobin/maven In directory sc8-pr-cvs6.sourceforge.net:/tmp/cvs-serv1409 Modified Files: pom.xml Log Message: add deps Index: pom.xml =================================================================== RCS file: /cvsroot/jrobin/maven/pom.xml,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** pom.xml 29 Jul 2007 00:49:57 -0000 1.2 --- pom.xml 29 Jul 2007 00:59:18 -0000 1.3 *************** *** 1,21 **** ! <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ! xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> ! <modelVersion>4.0.0</modelVersion> ! <groupId>org.jrobin</groupId> ! <artifactId>jrobin</artifactId> ! <packaging>jar</packaging> ! <version>1.5.5-SNAPSHOT</version> ! <name>jrobin</name> ! <url>http://www.jrobin.org</url> ! <build> ! <sourceDirectory>src</sourceDirectory> ! </build> ! <dependencies> ! <dependency> ! <groupId>junit</groupId> ! <artifactId>junit</artifactId> ! <version>3.8.1</version> ! <scope>test</scope> ! </dependency> ! </dependencies> ! </project> --- 1,31 ---- ! <?xml version="1.0" encoding="UTF-8"?> ! <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> ! <modelVersion>4.0.0</modelVersion> ! <groupId>org.jrobin</groupId> ! <artifactId>jrobin</artifactId> ! <name>jrobin</name> ! <version>1.5.5-SNAPSHOT</version> ! <url>http://www.jrobin.org</url> ! <build> ! <sourceDirectory>src</sourceDirectory> ! </build> ! <dependencies> ! <dependency> ! <groupId>junit</groupId> ! <artifactId>junit</artifactId> ! <version>3.8.1</version> ! <scope>test</scope> ! </dependency> ! <dependency> ! <groupId>org.apache.xmlrpc</groupId> ! <artifactId>xmlrpc-client</artifactId> ! <version>3.0</version> ! </dependency> ! <dependency> ! <groupId>westhawk</groupId> ! <artifactId>snmp</artifactId> ! <version>4_13</version> ! </dependency> ! </dependencies> ! </project> ! |
From: Benjamin R. <ran...@us...> - 2007-07-29 00:50:00
|
Update of /cvsroot/jrobin/maven In directory sc8-pr-cvs6.sourceforge.net:/tmp/cvs-serv30009 Modified Files: pom.xml Added Files: .cvsignore Log Message: it builds, now add deps --- NEW FILE: .cvsignore --- target Index: pom.xml =================================================================== RCS file: /cvsroot/jrobin/maven/pom.xml,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** pom.xml 29 Jul 2007 00:44:27 -0000 1.1 --- pom.xml 29 Jul 2007 00:49:57 -0000 1.2 *************** *** 8,11 **** --- 8,14 ---- <name>jrobin</name> <url>http://www.jrobin.org</url> + <build> + <sourceDirectory>src</sourceDirectory> + </build> <dependencies> <dependency> |
From: Benjamin R. <ran...@us...> - 2007-07-29 00:44:31
|
Update of /cvsroot/jrobin/maven In directory sc8-pr-cvs6.sourceforge.net:/tmp/cvs-serv28031/maven Added Files: pom.xml Log Message: add maven dir --- NEW FILE: pom.xml --- <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.jrobin</groupId> <artifactId>jrobin</artifactId> <packaging>jar</packaging> <version>1.5.5-SNAPSHOT</version> <name>jrobin</name> <url>http://www.jrobin.org</url> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> </dependencies> </project> |
From: Benjamin R. <ran...@us...> - 2007-07-29 00:42:28
|
Update of /cvsroot/jrobin/maven In directory sc8-pr-cvs6.sourceforge.net:/tmp/cvs-serv27209/maven Log Message: Directory /cvsroot/jrobin/maven added to the repository |
From: Tarus B. <ta...@us...> - 2006-12-21 18:29:49
|
Update of /cvsroot/jrobin/ant In directory sc8-pr-cvs6.sourceforge.net:/tmp/cvs-serv21180 Modified Files: build.xml Log Message: Prolly should commit this. Index: build.xml =================================================================== RCS file: /cvsroot/jrobin/ant/build.xml,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** build.xml 22 Oct 2004 13:27:20 -0000 1.4 --- build.xml 21 Dec 2006 18:29:42 -0000 1.5 *************** *** 1,201 **** ! <!-- ! /* ============================================================ ! * 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. ! */ ! --> ! ! <project name="JRobin" default="dist" basedir="."> ! <description>JRobin build file</description> ! ! <!-- VARIABLES --> ! <property name="version" value="1.4.0" /> ! <property name="who" value="Sasa Markovic <sa...@jr...>"/> ! <property name="cwd" location=".."/> ! ! <property name="classes" value="classes"/> ! <property name="doc" value="doc"/> ! <property name="javadoc" value="${doc}/javadoc"/> ! <property name="dist" value="dist"/> ! <property name="src" value="src"/> ! <property name="libs" value="lib" /> ! <property name="ant" value="ant" /> ! <property name="lib-snmp" value="snmp-1.3.jar"/> ! <property name="lib-xmlrpc" value="xmlrpc-1.2-b1.jar"/> ! <property name="lib-jrobin" value="jrobin-${version}.jar"/> ! <property name="lib-demo" value="jrobin-demo-${version}.jar"/> ! <property name="lib-mrtg-client" value="mrtg-client-${version}.jar"/> ! <property name="lib-mrtg-server" value="mrtg-server-${version}.jar"/> ! <property name="lib-inspector" value="inspector-${version}.jar"/> ! <property name="lib-convertor" value="convertor-${version}.jar"/> ! <property name="res" value="res"/> ! <property name="res-mrtg" value="${res}/mrtg"/> ! <property name="classpath" value="${cwd}/${libs}/${lib-snmp}:${cwd}/${libs}/${lib-xmlrpc}"/> ! <property name="tarfile" value="jrobin-${version}.tar"/> ! <property name="tgzfile" value="jrobin-${version}.tar.gz"/> ! ! <!-- TARGETS --> ! <target name="init"> ! <tstamp/> ! </target> ! ! <target name="clean" depends="init"> ! <delete includeemptydirs="true"> ! <fileset dir="${cwd}" > ! <include name="${classes}/**/*"/> ! <include name="${dist}/jrobin*.tar.gz"/> ! <include name="${javadoc}/**/*"/> ! <include name="${libs}/${lib-jrobin}" /> ! <include name="${libs}/${lib-mrtg-client}" /> ! <include name="${libs}/${lib-mrtg-server}" /> ! <include name="${libs}/${lib-inspector}" /> ! <include name="${libs}/${lib-convertor}" /> ! <include name="${libs}/${lib-demo}" /> ! </fileset> ! </delete> ! </target> ! ! <target name="compile" depends="init"> ! <mkdir dir="${cwd}/${classes}"/> ! <javac ! srcdir="${cwd}/${src}" destdir="${cwd}/${classes}" ! classpath="${classpath}" ! compiler="modern" source="1.4" ! /> ! </target> ! ! <target name="core-lib" depends="compile"> ! <delete file="${cwd}/${libs}/${lib-jrobin}" /> ! <jar jarfile="${cwd}/${libs}/${lib-jrobin}" basedir="${cwd}/${classes}"> ! <manifest> ! <attribute name="Main-Class" value="org.jrobin.core.RrdDb"/> ! </manifest> ! <include name="org/jrobin/core/**/*.class"/> ! <include name="org/jrobin/graph/**/*.class"/> ! </jar> ! </target> ! ! <target name="demo-lib" depends="core-lib"> ! <delete file="${cwd}/${libs}/${lib-demo}" /> ! <jar jarfile="${cwd}/${libs}/${lib-demo}" basedir="${cwd}/${classes}"> ! <manifest> ! <attribute name="Main-Class" value="org.jrobin.demo.Demo"/> ! <attribute name="Class-Path" value="${lib-jrobin}"/> ! </manifest> ! <include name="org/jrobin/demo/**/*.class"/> ! </jar> ! </target> ! ! <target name="mrtg-server-lib" depends="core-lib"> ! <delete file="${cwd}/${libs}/${lib-mrtg-server}" /> ! <jar jarfile="${cwd}/${libs}/${lib-mrtg-server}" basedir="${cwd}/${classes}"> ! <manifest> ! <attribute name="Main-Class" value="org.jrobin.mrtg.server.Server"/> ! <attribute name="Class-Path" value="${lib-xmlrpc} ${lib-snmp} ${lib-jrobin}"/> ! </manifest> ! <include name="org/jrobin/mrtg/*.class"/> ! <include name="org/jrobin/mrtg/server/*.class"/> ! </jar> ! </target> ! ! <target name="mrtg-client-lib" depends="mrtg-server-lib"> ! <delete file="${cwd}/${libs}/${lib-mrtg-client}" /> ! <jar jarfile="${cwd}/${libs}/${lib-mrtg-client}" basedir="${cwd}/${classes}"> ! <include name="org/jrobin/mrtg/*.class"/> ! <include name="org/jrobin/mrtg/client/*.class"/> ! </jar> ! <jar jarfile="${cwd}/${libs}/${lib-mrtg-client}" basedir="${cwd}" update="true" > ! <include name="${res-mrtg}/**/*"/> ! <manifest> ! <attribute name="Main-Class" value="org.jrobin.mrtg.client.Client"/> ! <attribute name="Class-Path" value="${lib-xmlrpc}"/> ! </manifest> ! </jar> ! </target> ! ! <target name="inspector-lib" depends="core-lib"> ! <delete file="${cwd}/${libs}/${lib-inspector}" /> ! <jar jarfile="${cwd}/${libs}/${lib-inspector}" basedir="${cwd}/${classes}"> ! <manifest> ! <attribute name="Main-Class" value="org.jrobin.inspector.RrdInspector"/> ! <attribute name="Class-Path" value="${lib-jrobin}"/> ! </manifest> ! <include name="org/jrobin/inspector/*.class"/> ! </jar> ! </target> ! ! <target name="convertor-lib" depends="core-lib"> ! <delete file="${cwd}/${libs}/${lib-convertor}" /> ! <jar jarfile="${cwd}/${libs}/${lib-convertor}" basedir="${cwd}/${classes}"> ! <manifest> ! <attribute name="Main-Class" value="org.jrobin.convertor.Convertor"/> ! <attribute name="Class-Path" value="${lib-jrobin}"/> ! </manifest> ! <include name="org/jrobin/convertor/*.class"/> ! </jar> ! </target> ! ! <target name="all-libs" depends="core-lib,demo-lib,mrtg-server-lib,mrtg-client-lib,inspector-lib,convertor-lib"/> ! ! <target name="javadoc" depends="compile"> ! <javadoc author="false" version="false" ! destdir="${cwd}/${javadoc}" ! packagenames="org.jrobin.core.*,org.jrobin.graph.*" ! excludepackagenames="org.jrobin.core.jrrd.*" ! source="1.4" ! sourcepath="${cwd}/${src}" ! classpath="${classpath}" ! access="protected" ! /> ! </target> ! ! <target name="dist" depends="all-libs,javadoc"> ! <mkdir dir="${cwd}/${dist}"/> ! <delete file="${cwd}/${dist}/${tarfile}>"/> ! <delete file="${cwd}/${dist}/${tgzfile}>"/> ! <property name="prefix" value="jrobin-${version}"/> ! <tar destfile="${cwd}/${dist}/${tarfile}"> ! <tarfileset dir="${cwd}/${doc}" prefix="${prefix}/${doc}"> ! <include name="**/*"/> ! </tarfileset> ! <tarfileset dir="${cwd}/${libs}" prefix="${prefix}/${libs}"> ! <include name="*.jar"/> ! </tarfileset> ! <tarfileset dir="${cwd}/${src}" prefix="${prefix}/${src}"> ! <exclude name="**/dev/**/*"/> ! <exclude name="**/cmd/**/*"/> ! <include name="**/*.java"/> ! </tarfileset> ! <tarfileset dir="${cwd}/${res}" prefix="${prefix}/${res}"> ! <include name="**/*"/> ! </tarfileset> ! <tarfileset dir="${cwd}/${ant}" prefix="${prefix}/${ant}"> ! <include name="*.xml"/> ! </tarfileset> ! </tar> ! <gzip src="${cwd}/${dist}/${tarfile}" zipfile="${cwd}/${dist}/${tgzfile}"/> ! <delete file="${cwd}/${dist}/${tarfile}"/> ! </target> ! ! </project> ! --- 1,140 ---- ! <!-- ! /* ============================================================ ! * JRobin : Pure java implementation of RRDTool's functionality ! * ============================================================ ! * ! * Project Info: http://www.jrobin.org ! * Project Lead: Sasa Markovic (sa...@jr...) ! * ! * (C) Copyright 2003-2005, 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. ! */ ! --> ! ! <project name="JRobin" default="jrobin" basedir="."> ! <description>JRobinLite Build File</description> ! ! <!-- VARIABLES --> ! <property name="version" value="1.5.4"/> ! <property name="who" value="Sasa Markovic <sa...@eu...>"/> ! <property name="home" location=".."/> ! ! <property name="classes" value="classes"/> ! <property name="doc" value="doc"/> ! <property name="javadoc" value="${doc}/javadoc"/> ! <property name="src" value="src"/> ! <property name="lib" value="lib"/> ! <property name="ant" value="ant"/> ! <property name="dist" value="dist"/> ! <property name="tmpfile" value="tmp.tar"/> ! <property name="lib-jrobin" value="jrobin-${version}.jar"/> ! <property name="lib-inspector" value="inspector-${version}.jar"/> ! <property name="lib-convertor" value="convertor-${version}.jar"/> ! <property name="dist-prefix" value="JRobinLite-${version}"/> ! <property name="dist-file" value="${dist-prefix}.tar.gz"/> ! ! ! <!-- TARGETS --> ! <target name="init"> ! <tstamp/> ! <mkdir dir="${home}/${classes}"/> ! <mkdir dir="${home}/${doc}"/> ! <mkdir dir="${home}/${javadoc}"/> ! <mkdir dir="${home}/${lib}"/> ! <mkdir dir="${home}/${dist}"/> ! </target> ! ! <target name="clean" depends="init"> ! <delete> ! <fileset dir="${home}"> ! <include name="${classes}/**/*.class"/> ! <include name="${lib}/**/*"/> ! <include name="${doc}/**/*"/> ! <include name="${dist}/**/*"/> ! </fileset> ! </delete> ! </target> ! ! <target name="compile" depends="init"> ! <javac ! srcdir="${home}/${src}" destdir="${home}/${classes}" ! compiler="modern" source="1.5" ! /> ! </target> ! ! <target name="jrobin" depends="compile"> ! <delete file="${home}/${lib}/${lib-jrobin}"/> ! <jar jarfile="${home}/${lib}/${lib-jrobin}" basedir="${home}/${classes}"> ! <manifest> ! <attribute name="Main-Class" value="org.jrobin.cmd.RrdCommander"/> ! </manifest> ! <include name="org/jrobin/cmd/**/*.class"/> ! <include name="org/jrobin/convertor/**/*.class"/> ! <include name="org/jrobin/core/**/*.class"/> ! <include name="org/jrobin/data/**/*.class"/> ! <include name="org/jrobin/demo/**/*.class"/> ! <include name="org/jrobin/graph/**/*.class"/> ! <include name="org/jrobin/inspector/**/*.class"/> ! </jar> ! <delete file="${home}/${lib}/${lib-convertor}"/> ! <jar jarfile="${home}/${lib}/${lib-convertor}" basedir="${home}/${classes}"> ! <manifest> ! <attribute name="Main-Class" value="org.jrobin.convertor.Convertor"/> ! <attribute name="Class-Path" value="${lib-jrobin}"/> ! </manifest> ! <include name="org/jrobin/convertor/**/*.class"/> ! </jar> ! <jar jarfile="${home}/${lib}/${lib-inspector}" basedir="${home}/${classes}"> ! <manifest> ! <attribute name="Main-Class" value="org.jrobin.inspector.RrdInspector"/> ! <attribute name="Class-Path" value="${lib-jrobin}"/> ! </manifest> ! <include name="org/jrobin/inspector/**/*.class"/> ! </jar> ! </target> ! ! <target name="javadoc" depends="compile"> ! <javadoc author="false" version="false" ! destdir="${home}/${javadoc}" ! packagenames="org.jrobin.cmd.*,org.jrobin.convertor.*,org.jrobin.core.*,org.jrobin.data.*,org.jrobin.demo.*,org.jrobin.graph.*,org.jrobin.inspector.*" ! excludepackagenames="org.jrobin.core.jrrd.*" ! source="1.5" ! sourcepath="${home}/${src}" ! access="protected" ! /> ! </target> ! ! <target name="dist" depends="clean,jrobin,javadoc"> ! <tar destfile="${home}/${dist}/${tmpfile}"> ! <tarfileset dir="${home}/${doc}" prefix="${dist-prefix}/${doc}"> ! <include name="**/*"/> ! </tarfileset> ! <tarfileset dir="${home}/${lib}" prefix="${dist-prefix}/${lib}"> ! <include name="**/*"/> ! </tarfileset> ! <tarfileset dir="${home}/${src}" prefix="${dist-prefix}/${src}"> ! <include name="**/*.java"/> ! </tarfileset> ! <tarfileset dir="${home}/${classes}" prefix="${dist-prefix}/${classes}"> ! <include name="**/*.class"/> ! </tarfileset> ! <tarfileset dir="${home}/${ant}" prefix="${dist-prefix}/${ant}"> ! <include name="*.xml"/> ! </tarfileset> ! </tar> ! <gzip src="${home}/${dist}/${tmpfile}" zipfile="${home}/${dist}/${dist-file}"/> ! <delete file="${home}/${dist}/${tmpfile}"/> ! </target> ! </project> ! |
Update of /cvsroot/jrobin/src/org/jrobin/core In directory sc8-pr-cvs6.sourceforge.net:/tmp/cvs-serv9082/org/jrobin/core Modified Files: ArcDef.java ArcState.java Archive.java ConsolFuns.java DataImporter.java Datasource.java DsDef.java DsTypes.java FetchData.java FetchRequest.java Header.java Robin.java RrdAllocator.java RrdBackend.java RrdBackendFactory.java RrdDb.java RrdDbPool.java RrdDef.java RrdDefTemplate.java RrdDouble.java RrdDoubleArray.java RrdException.java RrdFileBackend.java RrdFileBackendFactory.java RrdInt.java RrdLong.java RrdMemoryBackend.java RrdMemoryBackendFactory.java RrdNioBackend.java RrdNioBackendFactory.java RrdPrimitive.java RrdSafeFileBackend.java RrdSafeFileBackendFactory.java RrdString.java RrdToolReader.java RrdToolkit.java RrdUpdater.java Sample.java Util.java XmlReader.java XmlTemplate.java XmlWriter.java Log Message: Adding the new 1.5.4 code Index: FetchData.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/core/FetchData.java,v retrieving revision 1.18 retrieving revision 1.19 diff -C2 -d -r1.18 -r1.19 *** FetchData.java 23 Jan 2005 20:31:24 -0000 1.18 --- FetchData.java 21 Dec 2006 18:02:41 -0000 1.19 *************** *** 1,540 **** ! /* ============================================================ ! * JRobin : Pure java implementation of RRDTool's functionality ! * ============================================================ ! * ! * Project Info: http://www.jrobin.org ! * Project Lead: Sasa Markovic (sa...@jr...); ! * ! * (C) Copyright 2003, by Sasa Markovic. ! * ! * Developers: Sasa Markovic (sa...@jr...) [...1039 lines suppressed...] ! } ! ! private DataProcessor createDataProcessor(String rpnExpression) throws RrdException { ! DataProcessor dataProcessor = new DataProcessor(request.getFetchStart(), request.getFetchEnd()); ! for (String dsName : dsNames) { ! dataProcessor.addDatasource(dsName, this); ! } ! if (rpnExpression != null) { ! dataProcessor.addDatasource(RPN_SOURCE_NAME, rpnExpression); ! try { ! dataProcessor.processData(); ! } ! catch (IOException ioe) { ! // highly unlikely, since all datasources have already calculated values ! throw new RuntimeException("Impossible error: " + ioe); ! } ! } ! return dataProcessor; ! } ! } Index: RrdFileBackend.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/core/RrdFileBackend.java,v retrieving revision 1.13 retrieving revision 1.14 diff -C2 -d -r1.13 -r1.14 *** RrdFileBackend.java 17 Dec 2004 09:27:47 -0000 1.13 --- RrdFileBackend.java 21 Dec 2006 18:02:41 -0000 1.14 *************** *** 1,219 **** ! /* ============================================================ ! * JRobin : Pure java implementation of RRDTool's functionality ! * ============================================================ ! * ! * Project Info: http://www.jrobin.org ! * Project Lead: Sasa Markovic (sa...@jr...); ! * ! * (C) Copyright 2003, by Sasa Markovic. ! * ! * Developers: Sasa Markovic (sa...@jr...) ! * Arne Vandamme (cob...@jr...) ! * ! * This library is free software; you can redistribute it and/or modify it under the terms ! * of the GNU Lesser General Public License as published by the Free Software Foundation; ! * either version 2.1 of the License, or (at your option) any later version. ! * ! * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; ! * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. ! * See the GNU Lesser General Public License for more details. ! * ! * You should have received a copy of the GNU Lesser General Public License along with this ! * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, ! * Boston, MA 02111-1307, USA. ! */ ! ! package org.jrobin.core; ! ! import java.io.IOException; ! import java.io.RandomAccessFile; ! import java.nio.channels.FileLock; ! import java.util.HashSet; ! import java.util.Set; ! ! /** ! * 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> ! * <p/> ! * This backend is based on the RandomAccessFile class (java.io.* package). ! */ ! public class RrdFileBackend extends RrdBackend { ! private static final long LOCK_DELAY = 100; // 0.1sec ! ! private static Set openFiles = new HashSet(); ! ! /** read/write file status */ ! protected boolean readOnly; ! /** locking mode */ ! protected int lockMode; ! ! /** radnom access file handle */ ! protected RandomAccessFile file; ! /** file lock */ ! protected FileLock fileLock; ! ! /** ! * Creates RrdFileBackend object for the given file path, backed by RandomAccessFile object. ! * @param path Path to a file ! * @param readOnly True, if file should be open in a read-only mode. False otherwise ! * @param lockMode Locking mode, as described in {@link RrdDb#getLockMode()} ! * @throws IOException Thrown in case of I/O error ! */ ! protected RrdFileBackend(String path, boolean readOnly, int lockMode) throws IOException { ! super(path); ! this.readOnly = readOnly; ! this.lockMode = lockMode; ! file = new RandomAccessFile(path, readOnly ? "r" : "rw"); ! try { ! lockFile(); ! registerWriter(); ! } ! catch(IOException ioe) { ! close(); ! throw ioe; ! } ! } ! ! private void lockFile() throws IOException { ! switch (lockMode) { ! case RrdDb.EXCEPTION_IF_LOCKED: ! fileLock = file.getChannel().tryLock(); ! if (fileLock == null) { ! // could not obtain lock ! throw new IOException("Access denied. " + "File [" + getPath() + "] already locked"); ! } ! break; ! case RrdDb.WAIT_IF_LOCKED: ! while (fileLock == null) { ! fileLock = file.getChannel().tryLock(); ! if (fileLock == null) { ! // could not obtain lock, wait a little, than try again ! try { ! Thread.sleep(LOCK_DELAY); ! } ! catch (InterruptedException e) { ! // NOP ! } ! } ! } ! break; ! case RrdDb.NO_LOCKS: ! break; ! } ! } ! ! private void registerWriter() throws IOException { ! if (!readOnly) { ! String path = getPath(); ! String canonicalPath = getCanonicalPath(path); ! synchronized (openFiles) { ! if (openFiles.contains(canonicalPath)) { ! throw new IOException("File \"" + path + "\" already open for R/W access. " + ! "You cannot open the same file for R/W access twice"); ! } ! else { ! openFiles.add(canonicalPath); ! } ! } ! } ! } ! ! /** ! * Closes the underlying RRD file. ! * ! * @throws IOException Thrown in case of I/O error ! */ ! public void close() throws IOException { ! unregisterWriter(); ! try { ! unlockFile(); ! } ! finally { ! file.close(); ! } ! } ! ! private void unlockFile() throws IOException { ! if (fileLock != null) { ! fileLock.release(); ! } ! } ! ! private void unregisterWriter() throws IOException { ! if (!readOnly) { ! String path = getPath(); ! String canonicalPath = getCanonicalPath(path); ! synchronized (openFiles) { ! openFiles.remove(canonicalPath); ! } ! } ! } ! ! /** ! * Returns canonical path to the file on the disk. ! * ! * @param path File path ! * @return Canonical file path ! * @throws IOException Thrown in case of I/O error ! */ ! public static String getCanonicalPath(String path) throws IOException { ! return Util.getCanonicalPath(path); ! } ! ! /** ! * Returns canonical path to the file on the disk. ! * ! * @return Canonical file path ! * @throws IOException Thrown in case of I/O error ! */ ! public String getCanonicalPath() throws IOException { ! return RrdFileBackend.getCanonicalPath(getPath()); ! } ! ! /** ! * Writes bytes to the underlying RRD file on the disk ! * ! * @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 { ! file.seek(offset); ! file.write(b); ! } ! ! /** ! * Reads a number of bytes from the RRD file on the disk ! * ! * @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 { ! file.seek(offset); ! if (file.read(b) != b.length) { ! throw new IOException("Not enough bytes available in file " + getPath()); ! } ! } ! ! /** ! * Returns RRD file length. ! * ! * @return File length. ! * @throws IOException Thrown in case of I/O error. ! */ ! public long getLength() throws IOException { ! return file.length(); ! } ! ! /** ! * Sets length of the underlying RRD file. This method is called only once, immediately ! * after a new RRD file gets created. ! * ! * @param length Length of the RRD file ! * @throws IOException Thrown in case of I/O error. ! */ ! protected void setLength(long length) throws IOException { ! file.setLength(length); ! } ! } --- 1,136 ---- ! /* ============================================================ ! * JRobin : Pure java implementation of RRDTool's functionality ! * ============================================================ ! * ! * Project Info: http://www.jrobin.org ! * Project Lead: Sasa Markovic (sa...@jr...); ! * ! * (C) Copyright 2003-2005, by Sasa Markovic. ! * ! * Developers: Sasa Markovic (sa...@jr...) ! * ! * ! * This library is free software; you can redistribute it and/or modify it under the terms ! * of the GNU Lesser General Public License as published by the Free Software Foundation; ! * either version 2.1 of the License, or (at your option) any later version. ! * ! * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; ! * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. ! * See the GNU Lesser General Public License for more details. ! * ! * You should have received a copy of the GNU Lesser General Public License along with this ! * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, ! * Boston, MA 02111-1307, USA. ! */ ! ! package org.jrobin.core; ! ! import java.io.IOException; ! import java.io.RandomAccessFile; ! ! /** ! * 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> ! * <p/> ! * This backend is based on the RandomAccessFile class (java.io.* package). ! */ ! public class RrdFileBackend extends RrdBackend { ! /** ! * read/write file status ! */ ! protected boolean readOnly; ! /** ! * radnom access file handle ! */ ! protected RandomAccessFile file; ! ! /** ! * Creates RrdFileBackend object for the given file path, backed by RandomAccessFile object. ! * ! * @param path Path to a file ! * @param readOnly True, if file should be open in a read-only mode. False otherwise ! * @throws IOException Thrown in case of I/O error ! */ ! protected RrdFileBackend(String path, boolean readOnly) throws IOException { ! super(path); ! this.readOnly = readOnly; ! this.file = new RandomAccessFile(path, readOnly ? "r" : "rw"); ! } ! ! /** ! * Closes the underlying RRD file. ! * ! * @throws IOException Thrown in case of I/O error ! */ ! public void close() throws IOException { ! file.close(); ! } ! ! /** ! * Returns canonical path to the file on the disk. ! * ! * @param path File path ! * @return Canonical file path ! * @throws IOException Thrown in case of I/O error ! */ ! public static String getCanonicalPath(String path) throws IOException { ! return Util.getCanonicalPath(path); ! } ! ! /** ! * Returns canonical path to the file on the disk. ! * ! * @return Canonical file path ! * @throws IOException Thrown in case of I/O error ! */ ! public String getCanonicalPath() throws IOException { ! return RrdFileBackend.getCanonicalPath(getPath()); ! } ! ! /** ! * Writes bytes to the underlying RRD file on the disk ! * ! * @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 { ! file.seek(offset); ! file.write(b); ! } ! ! /** ! * Reads a number of bytes from the RRD file on the disk ! * ! * @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 { ! file.seek(offset); ! if (file.read(b) != b.length) { ! throw new IOException("Not enough bytes available in file " + getPath()); ! } ! } ! ! /** ! * Returns RRD file length. ! * ! * @return File length. ! * @throws IOException Thrown in case of I/O error. ! */ ! public long getLength() throws IOException { ! return file.length(); ! } ! ! /** ! * Sets length of the underlying RRD file. This method is called only once, immediately ! * after a new RRD file gets created. ! * ! * @param length Length of the RRD file ! * @throws IOException Thrown in case of I/O error. ! */ ! protected void setLength(long length) throws IOException { ! file.setLength(length); ! } ! } Index: RrdFileBackendFactory.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/core/RrdFileBackendFactory.java,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** RrdFileBackendFactory.java 13 Jul 2004 18:42:24 -0000 1.5 --- RrdFileBackendFactory.java 21 Dec 2006 18:02:41 -0000 1.6 *************** *** 1,69 **** ! /* ============================================================ ! * JRobin : Pure java implementation of RRDTool's functionality ! * ============================================================ ! * ! * Project Info: http://www.jrobin.org ! * Project Lead: Sasa Markovic (sa...@jr...); ! * ! * (C) Copyright 2003, by Sasa Markovic. ! * ! * Developers: Sasa Markovic (sa...@jr...) ! * Arne Vandamme (cob...@jr...) ! * ! * This library is free software; you can redistribute it and/or modify it under the terms ! * of the GNU Lesser General Public License as published by the Free Software Foundation; ! * either version 2.1 of the License, or (at your option) any later version. ! * ! * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; ! * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. ! * See the GNU Lesser General Public License for more details. ! * ! * You should have received a copy of the GNU Lesser General Public License along with this ! * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, ! * Boston, MA 02111-1307, USA. ! */ ! ! package org.jrobin.core; ! ! import java.io.IOException; ! import java.io.File; ! ! /** ! * 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 { ! /** factory name, "FILE" */ ! public static final String NAME = "FILE"; ! ! /** ! * Creates RrdFileBackend object for the given file path. ! * @param path File path ! * @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. ! */ ! protected RrdBackend open(String path, boolean readOnly, int lockMode) throws IOException { ! return new RrdFileBackend(path, readOnly, lockMode); ! } ! ! /** ! * Method to determine if a file with the given path already exists. ! * @param path File path ! * @return True, if such file exists, false otherwise. ! */ ! protected boolean exists(String path) { ! return new File(path).exists(); ! } ! ! /** ! * Returns the name of this factory. ! * @return Factory name (equals to string "FILE") ! */ ! public String getFactoryName() { ! return NAME; ! } ! } --- 1,71 ---- ! /* ============================================================ ! * JRobin : Pure java implementation of RRDTool's functionality ! * ============================================================ ! * ! * Project Info: http://www.jrobin.org ! * Project Lead: Sasa Markovic (sa...@jr...); ! * ! * (C) Copyright 2003-2005, by Sasa Markovic. ! * ! * Developers: Sasa Markovic (sa...@jr...) ! * ! * ! * This library is free software; you can redistribute it and/or modify it under the terms ! * of the GNU Lesser General Public License as published by the Free Software Foundation; ! * either version 2.1 of the License, or (at your option) any later version. ! * ! * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; ! * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. ! * See the GNU Lesser General Public License for more details. ! * ! * You should have received a copy of the GNU Lesser General Public License along with this ! * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, ! * Boston, MA 02111-1307, USA. ! */ ! ! package org.jrobin.core; ! ! import java.io.IOException; ! ! /** ! * 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 { ! /** ! * factory name, "FILE" ! */ ! public static final String NAME = "FILE"; ! ! /** ! * Creates RrdFileBackend object for the given file path. ! * ! * @param path File path ! * @param readOnly True, if the file should be accessed in read/only mode. ! * False otherwise. ! * @return RrdFileBackend object which handles all I/O operations for the given file path ! * @throws IOException Thrown in case of I/O error. ! */ ! protected RrdBackend open(String path, boolean readOnly) throws IOException { ! return new RrdFileBackend(path, readOnly); ! } ! ! /** ! * Method to determine if a file with the given path already exists. ! * ! * @param path File path ! * @return True, if such file exists, false otherwise. ! */ ! protected boolean exists(String path) { ! return Util.fileExists(path); ! } ! ! /** ! * Returns the name of this factory. ! * ! * @return Factory name (equals to string "FILE") ! */ ! public String getFactoryName() { ! return NAME; ! } ! } Index: XmlTemplate.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/core/XmlTemplate.java,v retrieving revision 1.9 retrieving revision 1.10 diff -C2 -d -r1.9 -r1.10 *** XmlTemplate.java 11 Jul 2004 22:02:52 -0000 1.9 --- XmlTemplate.java 21 Dec 2006 18:02:42 -0000 1.10 *************** *** 1,325 **** ! /* ============================================================ ! * JRobin : Pure java implementation of RRDTool's functionality ! * ============================================================ ! * ! * Project Info: http://www.jrobin.org ! * Project Lead: Sasa Markovic (sa...@jr...); ! * ! * (C) Copyright 2003, by Sasa Markovic. ! * ! * Developers: Sasa Markovic (sa...@jr...) ! * Arne Vandamme (cob...@jr...) ! * ! * This library is free software; you can redistribute it and/or modify it under the terms ! * of the GNU Lesser General Public License as published by the Free Software Foundation; ! * either version 2.1 of the License, or (at your option) any later version. ! * ! * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; ! * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. ! * See the GNU Lesser General Public License for more details. ! * ! * You should have received a copy of the GNU Lesser General Public License along with this ! * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, ! * Boston, MA 02111-1307, USA. ! */ ! ! package org.jrobin.core; ! ! import org.w3c.dom.Node; ! import org.w3c.dom.Element; ! import org.xml.sax.InputSource; ! ! import java.io.IOException; ! import java.io.File; ! import java.util.*; ! import java.util.regex.Pattern; ! import java.util.regex.Matcher; ! import java.awt.*; ! ! /** ! * Class used as a base class for various XML template related classes. Class provides ! * methods for XML source parsing and XML tree traversing. XML source may have unlimited ! * number of placeholders (variables) in the format <code>${variable_name}</code>. ! * Methods are provided to specify variable values at runtime. ! * Note that this class has limited functionality: XML source gets parsed, and variable ! * values are collected. You have to extend this class to do something more useful.<p> ! */ ! public abstract class XmlTemplate { ! private static final String PATTERN_STRING = "\\$\\{(\\w+)\\}"; ! private static final Pattern PATTERN = Pattern.compile(PATTERN_STRING); ! ! protected Element root; ! private HashMap valueMap = new HashMap(); ! private HashSet validatedNodes = new HashSet(); ! ! protected XmlTemplate(InputSource xmlSource) throws IOException, RrdException { ! root = Util.Xml.getRootElement(xmlSource); ! } ! ! protected XmlTemplate(String xmlString) throws IOException, RrdException { ! root = Util.Xml.getRootElement(xmlString); ! } ! ! protected XmlTemplate(File xmlFile) throws IOException, RrdException { ! root = Util.Xml.getRootElement(xmlFile); ! } ! ! /** ! * Removes all placeholder-value mappings. ! */ ! public void clearValues() { ! valueMap.clear(); ! } ! ! /** ! * Sets value for a single XML template variable. Variable name should be specified ! * without leading '${' and ending '}' placeholder markers. For example, for a placeholder ! * <code>${start}</code>, specify <code>start</start> for the <code>name</code> parameter. ! * @param name variable name ! * @param value value to be set in the XML template ! */ ! public void setVariable(String name, String value) { ! valueMap.put(name, value); ! } ! ! /** ! * Sets value for a single XML template variable. Variable name should be specified ! * without leading '${' and ending '}' placeholder markers. For example, for a placeholder ! * <code>${start}</code>, specify <code>start</start> for the <code>name</code> parameter. ! * @param name variable name ! * @param value value to be set in the XML template ! */ ! public void setVariable(String name, int value) { ! valueMap.put(name, new Integer(value)); ! } ! ! /** ! * Sets value for a single XML template variable. Variable name should be specified ! * without leading '${' and ending '}' placeholder markers. For example, for a placeholder ! * <code>${start}</code>, specify <code>start</start> for the <code>name</code> parameter. ! * @param name variable name ! * @param value value to be set in the XML template ! */ ! public void setVariable(String name, long value) { ! valueMap.put(name, new Long(value)); ! } ! ! /** ! * Sets value for a single XML template variable. Variable name should be specified ! * without leading '${' and ending '}' placeholder markers. For example, for a placeholder ! * <code>${start}</code>, specify <code>start</start> for the <code>name</code> parameter. ! * @param name variable name ! * @param value value to be set in the XML template ! */ ! public void setVariable(String name, double value) { ! valueMap.put(name, new Double(value)); ! } ! ! /** ! * Sets value for a single XML template variable. Variable name should be specified ! * without leading '${' and ending '}' placeholder markers. For example, for a placeholder ! * <code>${start}</code>, specify <code>start</start> for the <code>name</code> parameter. ! * @param name variable name ! * @param value value to be set in the XML template ! */ ! public void setVariable(String name, Color value) { ! valueMap.put(name, "#" + Integer.toHexString(value.getRGB() & 0xFFFFFF)); ! } ! ! /** ! * Sets value for a single XML template variable. Variable name should be specified ! * without leading '${' and ending '}' placeholder markers. For example, for a placeholder ! * <code>${start}</code>, specify <code>start</start> for the <code>name</code> parameter. ! * @param name variable name ! * @param value value to be set in the XML template ! */ ! public void setVariable(String name, Date value) { ! setVariable(name, Util.getTimestamp(value)); ! } ! ! /** ! * Sets value for a single XML template variable. Variable name should be specified ! * without leading '${' and ending '}' placeholder markers. For example, for a placeholder ! * <code>${start}</code>, specify <code>start</start> for the <code>name</code> parameter. ! * @param name variable name ! * @param value value to be set in the XML template ! */ ! public void setVariable(String name, GregorianCalendar value) { ! setVariable(name, Util.getTimestamp(value)); ! } ! ! /** ! * Sets value for a single XML template variable. Variable name should be specified ! * without leading '${' and ending '}' placeholder markers. For example, for a placeholder ! * <code>${start}</code>, specify <code>start</start> for the <code>name</code> parameter. ! * @param name variable name ! * @param value value to be set in the XML template ! */ ! public void setVariable(String name, boolean value) { ! valueMap.put(name, "" + value); ! } ! ! /** ! * Searches the XML template to see if there are variables in there that ! * will need to be set. ! * ! * @return True if variables were detected, false if not. ! */ ! public boolean hasVariables() { ! return PATTERN.matcher( root.toString() ).find(); ! } ! ! /** ! * Returns the list of variables that should be set in this template. ! * ! * @return List of variable names as an array of strings. ! */ ! public String[] getVariables() ! { ! ArrayList list = new ArrayList(); ! Matcher m = PATTERN.matcher( root.toString() ); ! ! while ( m.find() ) ! { ! String var = m.group(1); ! if ( !list.contains( var ) ) ! list.add( var ); ! } ! ! return (String[]) list.toArray( new String[list.size()] ); ! } ! ! protected static Node[] getChildNodes(Node parentNode, String childName) { ! return Util.Xml.getChildNodes(parentNode, childName); ! } ! ! protected static Node[] getChildNodes(Node parentNode) { ! return Util.Xml.getChildNodes(parentNode, null); ! } ! ! protected static Node getFirstChildNode(Node parentNode, String childName) throws RrdException { ! return Util.Xml.getFirstChildNode(parentNode, childName); ! } ! ! protected boolean hasChildNode(Node parentNode, String childName) { ! return Util.Xml.hasChildNode(parentNode, childName); ! } ! ! protected String getChildValue( Node parentNode, String childName ) throws RrdException { ! return getChildValue( parentNode, childName, true ); ! } ! ! protected String getChildValue(Node parentNode, String childName, boolean trim) throws RrdException { ! String value = Util.Xml.getChildValue(parentNode, childName, trim); ! return resolveMappings(value); ! } ! ! protected String getValue( Node parentNode ) { ! return getValue( parentNode, true ); ! } ! ! protected String getValue(Node parentNode, boolean trim ) { ! String value = Util.Xml.getValue(parentNode, trim); ! return resolveMappings(value); ! } ! ! private String resolveMappings(String templateValue) { ! if(templateValue == null) { ! return null; ! } ! Matcher matcher = PATTERN.matcher(templateValue); ! StringBuffer result = new StringBuffer(); ! int lastMatchEnd = 0; ! while(matcher.find()) { ! String var = matcher.group(1); ! if(valueMap.containsKey(var)) { ! // mapping found ! result.append(templateValue.substring(lastMatchEnd, matcher.start())); ! result.append(valueMap.get(var).toString()); ! lastMatchEnd = matcher.end(); ! } ! else { ! // no mapping found - this is illegal ! // throw runtime exception ! throw new IllegalArgumentException( ! "No mapping found for template variable ${" + var + "}"); ! } ! } ! result.append(templateValue.substring(lastMatchEnd)); ! return result.toString(); ! } ! ! protected int getChildValueAsInt(Node parentNode, String childName) throws RrdException { ! String valueStr = getChildValue(parentNode, childName); ! return Integer.parseInt(valueStr); ! } ! ! protected int getValueAsInt(Node parentNode) { ! String valueStr = getValue(parentNode); ! return Integer.parseInt(valueStr); ! } ! ! protected long getChildValueAsLong(Node parentNode, String childName) throws RrdException { ! String valueStr = getChildValue(parentNode, childName); ! return Long.parseLong(valueStr); ! } ! ! protected long getValueAsLong(Node parentNode) { ! String valueStr = getValue(parentNode); ! return Long.parseLong(valueStr); ! } ! ! protected double getChildValueAsDouble(Node parentNode, String childName) throws RrdException { ! String valueStr = getChildValue(parentNode, childName); ! return Util.parseDouble(valueStr); ! } ! ! protected double getValueAsDouble(Node parentNode) { ! String valueStr = getValue(parentNode); ! return Util.parseDouble(valueStr); ! } ! ! protected boolean getChildValueAsBoolean(Node parentNode, String childName) throws RrdException { ! String valueStr = getChildValue(parentNode, childName); ! return Util.parseBoolean(valueStr); ! } ! ! protected boolean getValueAsBoolean(Node parentNode) { ! String valueStr = getValue(parentNode); ! return Util.parseBoolean(valueStr); ! } ! ! protected boolean isEmptyNode(Node node) { ! // comment node or empty text node ! return node.getNodeName().equals("#comment") || ! (node.getNodeName().equals("#text") && node.getNodeValue().trim().length() == 0); ! } ! ! protected void validateTagsOnlyOnce(Node parentNode, String[] allowedChildNames) throws RrdException { ! // validate node only once ! if(validatedNodes.contains(parentNode)) { ! return; ! } ! Node[] childs = getChildNodes(parentNode); ! main: ! for(int i = 0; i < childs.length; i++) { ! String childName = childs[i].getNodeName(); ! for(int j = 0; j < allowedChildNames.length; j++) { ! if(allowedChildNames[j].equals(childName)) { ! // only one such tag is allowed ! allowedChildNames[j] = "<--removed-->"; ! continue main; ! } ! else if(allowedChildNames[j].equals(childName + "*")) { ! // several tags allowed ! continue main; ! } ! } ! if(!isEmptyNode(childs[i])) { ! throw new RrdException("Unexpected tag encountered: <" + childName + ">"); ! } ! } ! // everything is OK ! validatedNodes.add(parentNode); ! } ! } --- 1,348 ---- ! /* ============================================================ ! * JRobin : Pure java implementation of RRDTool's functionality ! * ============================================================ ! * ! * Project Info: http://www.jrobin.org ! * Project Lead: Sasa Markovic (sa...@jr...); ! * ! * (C) Copyright 2003-2005, by Sasa Markovic. ! * ! * Developers: Sasa Markovic (sa...@jr...) ! * ! * ! * This library is free software; you can redistribute it and/or modify it under the terms ! * of the GNU Lesser General Public License as published by the Free Software Foundation; ! * either version 2.1 of the License, or (at your option) any later version. ! * ! * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; ! * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. ! * See the GNU Lesser General Public License for more details. ! * ! * You should have received a copy of the GNU Lesser General Public License along with this ! * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, ! * Boston, MA 02111-1307, USA. ! */ ! ! package org.jrobin.core; ! ! import org.w3c.dom.Element; ! import org.w3c.dom.Node; ! import org.xml.sax.InputSource; ! ! import java.awt.*; ! import java.io.File; ! import java.io.IOException; ! import java.util.*; ! import java.util.regex.Matcher; ! import java.util.regex.Pattern; ! ! /** ! * Class used as a base class for various XML template related classes. Class provides ! * methods for XML source parsing and XML tree traversing. XML source may have unlimited ! * number of placeholders (variables) in the format <code>${variable_name}</code>. ! * Methods are provided to specify variable values at runtime. ! * Note that this class has limited functionality: XML source gets parsed, and variable ! * values are collected. You have to extend this class to do something more useful.<p> ! */ ! public abstract class XmlTemplate { ! private static final String PATTERN_STRING = "\\$\\{(\\w+)\\}"; ! private static final Pattern PATTERN = Pattern.compile(PATTERN_STRING); ! ! protected Element root; ! private HashMap<String, Object> valueMap = new HashMap<String, Object>(); ! private HashSet<Node> validatedNodes = new HashSet<Node>(); ! ! protected XmlTemplate(InputSource xmlSource) throws IOException, RrdException { ! root = Util.Xml.getRootElement(xmlSource); ! } ! ! protected XmlTemplate(String xmlString) throws IOException, RrdException { ! root = Util.Xml.getRootElement(xmlString); ! } ! ! protected XmlTemplate(File xmlFile) throws IOException, RrdException { ! root = Util.Xml.getRootElement(xmlFile); ! } ! ! /** ! * Removes all placeholder-value mappings. ! */ ! public void clearValues() { ! valueMap.clear(); ! } ! ! /** ! * Sets value for a single XML template variable. Variable name should be specified ! * without leading '${' and ending '}' placeholder markers. For example, for a placeholder ! * <code>${start}</code>, specify <code>start</start> for the <code>name</code> parameter. ! * ! * @param name variable name ! * @param value value to be set in the XML template ! */ ! public void setVariable(String name, String value) { ! valueMap.put(name, value); ! } ! ! /** ! * Sets value for a single XML template variable. Variable name should be specified ! * without leading '${' and ending '}' placeholder markers. For example, for a placeholder ! * <code>${start}</code>, specify <code>start</start> for the <code>name</code> parameter. ! * ! * @param name variable name ! * @param value value to be set in the XML template ! */ ! public void setVariable(String name, int value) { ! valueMap.put(name, value); ! } ! ! /** ! * Sets value for a single XML template variable. Variable name should be specified ! * without leading '${' and ending '}' placeholder markers. For example, for a placeholder ! * <code>${start}</code>, specify <code>start</start> for the <code>name</code> parameter. ! * ! * @param name variable name ! * @param value value to be set in the XML template ! */ ! public void setVariable(String name, long value) { ! valueMap.put(name, value); ! } ! ! /** ! * Sets value for a single XML template variable. Variable name should be specified ! * without leading '${' and ending '}' placeholder markers. For example, for a placeholder ! * <code>${start}</code>, specify <code>start</start> for the <code>name</code> parameter. ! * ! * @param name variable name ! * @param value value to be set in the XML template ! */ ! public void setVariable(String name, double value) { ! valueMap.put(name, value); ! } ! ! /** ! * Sets value for a single XML template variable. Variable name should be specified ! * without leading '${' and ending '}' placeholder markers. For example, for a placeholder ! * <code>${start}</code>, specify <code>start</start> for the <code>name</code> parameter. ! * ! * @param name variable name ! * @param value value to be set in the XML template ! */ ! public void setVariable(String name, Color value) { ! String r = byteToHex(value.getRed()); ! String g = byteToHex(value.getGreen()); ! String b = byteToHex(value.getBlue()); ! String a = byteToHex(value.getAlpha()); ! valueMap.put(name, "#" + r + g + b + a); ! } ! ! private String byteToHex(int i) { ! String s = Integer.toHexString(i); ! while (s.length() < 2) { ! s = "0" + s; ! } ! return s; ! } ! ! /** ! * Sets value for a single XML template variable. Variable name should be specified ! * without leading '${' and ending '}' placeholder markers. For example, for a placeholder ! * <code>${start}</code>, specify <code>start</start> for the <code>name</code> parameter. ! * ! * @param name variable name ! * @param value value to be set in the XML template ! */ ! public void setVariable(String name, Date value) { ! setVariable(name, Util.getTimestamp(value)); ! } ! ! /** ! * Sets value for a single XML template variable. Variable name should be specified ! * without leading '${' and ending '}' placeholder markers. For example, for a placeholder ! * <code>${start}</code>, specify <code>start</start> for the <code>name</code> parameter. ! * ! * @param name variable name ! * @param value value to be set in the XML template ! */ ! public void setVariable(String name, Calendar value) { ! setVariable(name, Util.getTimestamp(value)); ! } ! ! /** ! * Sets value for a single XML template variable. Variable name should be specified ! * without leading '${' and ending '}' placeholder markers. For example, for a placeholder ! * <code>${start}</code>, specify <code>start</start> for the <code>name</code> parameter. ! * ! * @param name variable name ! * @param value value to be set in the XML template ! */ ! public void setVariable(String name, boolean value) { ! valueMap.put(name, "" + value); ! } ! ! /** ! * Searches the XML template to see if there are variables in there that ! * will need to be set. ! * ! * @return True if variables were detected, false if not. ! */ ! public boolean hasVariables() { ! return PATTERN.matcher(root.toString()).find(); ! } ! ! /** ! * Returns the list of variables that should be set in this template. ! * ! * @return List of variable names as an array of strings. ! */ ! public String[] getVariables() { ! ArrayList<String> list = new ArrayList<String>(); ! Matcher m = PATTERN.matcher(root.toString()); ! ! while (m.find()) { ! String var = m.group(1); ! if (!list.contains(var)) { ! list.add(var); ! } ! } ! ! return list.toArray(new String[list.size()]); ! } ! ! protected static Node[] getChildNodes(Node parentNode, String childName) { ! return Util.Xml.getChildNodes(parentNode, childName); ! } ! ! protected static Node[] getChildNodes(Node parentNode) { ! return Util.Xml.getChildNodes(parentNode, null); ! } ! ! protected static Node getFirstChildNode(Node parentNode, String childName) throws RrdException { ! return Util.Xml.getFirstChildNode(parentNode, childName); ! } ! ! protected boolean hasChildNode(Node parentNode, String childName) { ! return Util.Xml.hasChildNode(parentNode, childName); ! } ! ! protected String getChildValue(Node parentNode, String childName) throws RrdException { ! return getChildValue(parentNode, childName, true); ! } ! ! protected String getChildValue(Node parentNode, String childName, boolean trim) throws RrdException { ! String value = Util.Xml.getChildValue(parentNode, childName, trim); ! return resolveMappings(value); ! } ! ! protected String getValue(Node parentNode) { ! return getValue(parentNode, true); ! } ! ! protected String getValue(Node parentNode, boolean trim) { ! String value = Util.Xml.getValue(parentNode, trim); ! return resolveMappings(value); ! } ! ! private String resolveMappings(String templateValue) { ! if (templateValue == null) { ! return null; ! } ! Matcher matcher = PATTERN.matcher(templateValue); ! StringBuffer result = new StringBuffer(); ! int lastMatchEnd = 0; ! while (matcher.find()) { ! String var = matcher.group(1); ! if (valueMap.containsKey(var)) { ! // mapping found ! result.append(templateValue.substring(lastMatchEnd, matcher.start())); ! result.append(valueMap.get(var).toString()); ! lastMatchEnd = matcher.end(); ! } ! else { ! // no mapping found - this is illegal ! // throw runtime exception ! throw new IllegalArgumentException("No mapping found for template variable ${" + var + "}"); ! } ! } ! result.append(templateValue.substring(lastMatchEnd)); ! return result.toString(); ! } ! ! protected int getChildValueAsInt(Node parentNode, String childName) throws RrdException { ! String valueStr = getChildValue(parentNode, childName); ! return Integer.parseInt(valueStr); ! } ! ! protected int getValueAsInt(Node parentNode) { ! String valueStr = getValue(parentNode); ! return Integer.parseInt(valueStr); ! } ! ! protected long getChildValueAsLong(Node parentNode, String childName) throws RrdException { ! String valueStr = getChildValue(parentNode, childName); ! return Long.parseLong(valueStr); ! } ! ! protected long getValueAsLong(Node parentNode) { ! String valueStr = getValue(parentNode); ! return Long.parseLong(valueStr); ! } ! ! protected double getChildValueAsDouble(Node parentNode, String childName) throws RrdException { ! String valueStr = getChildValue(parentNode, childName); ! return Util.parseDouble(valueStr); ! } ! ! protected double getValueAsDouble(Node parentNode) { ! String valueStr = getValue(parentNode); ! return Util.parseDouble(valueStr); ! } ! ! protected boolean getChildValueAsBoolean(Node parentNode, String childName) throws RrdException { ! String valueStr = getChildValue(parentNode, childName); ! return Util.parseBoolean(valueStr); ! } ! ! protected boolean getValueAsBoolean(Node parentNode) { ! String valueStr = getValue(parentNode); ! return Util.parseBoolean(valueStr); ! } ! ! protected Paint getValueAsColor(Node parentNode) throws RrdException { ! String rgbStr = getValue(parentNode); ! return Util.parseColor(rgbStr); ! } ! ! protected boolean isEmptyNode(Node node) { ! // comment node or empty text node ! return node.getNodeName().equals("#comment") || ! (node.getNodeName().equals("#text") && node.getNodeValue().trim().length() == 0); ! } ! ! protected void validateTagsOnlyOnce(Node parentNode, String[] allowedChildNames) throws RrdException { ! // validate node only once ! if (validatedNodes.contains(parentNode)) { ! return; ! } ! Node[] childs = getChildNodes(parentNode); ! main: ! for (Node child : childs) { ! String childName = child.getNodeName(); ! for (int j = 0; j < allowedChildNames.length; j++) { ! if (allowedChildNames[j].equals(childName)) { ! // only one such tag is allowed ! allowedChildNames[j] = "<--removed-->"; ! continue main; ! } ! else if (allowedChildNames[j].equals(childName + "*")) { ! // several tags allowed ! continue main; ! } ! } ! if (!isEmptyNode(child)) { ! throw new RrdException("Unexpected tag encountered: <" + childName + ">"); ! } ! } ! // everything is OK ! validatedNodes.add(parentNode); ! } ! } Index: RrdDouble.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/core/RrdDouble.java,v retrieving revision 1.11 retrieving revision 1.12 diff -C2 -d -r1.11 -r1.12 *** RrdDouble.java 9 Nov 2004 11:36:53 -0000 1.11 --- RrdDouble.java 21 Dec 2006 18:02:41 -0000 1.12 *************** *** 1,57 **** ! /* ============================================================ ! * JRobin : Pure java implementation of RRDTool's functionality ! * ============================================================ ! * ! * Project Info: http://www.jrobin.org ! * Project Lead: Sasa Markovic (sa...@jr...); ! * ! * (C) Copyright 2003, by Sasa Markovic. ! * ! * Developers: Sasa Markovic (sa...@jr...) ! * Arne Vandamme (cob...@jr...) ! * ! * This library is free software; you can redistribute it and/or modify it under the terms ! * of the GNU Lesser General Public License as published by the Free Software Foundation; ! * either version 2.1 of the License, or (at your option) any later version. ! * ! * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; ! * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. ! * See the GNU Lesser General Public License for more details. ! * ! * You should have received a copy of the GNU Lesser General Public License along with this ! * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, ! * Boston, MA 02111-1307, USA. ! */ ! ! package org.jrobin.core; ! ! import java.io.IOException; ! ! class RrdDouble extends RrdPrimitive { ! private double cache; ! private boolean cached = false; ! ! RrdDouble(RrdUpdater updater, boolean isConstant) throws IOException { ! super(updater, RrdDouble.RRD_DOUBLE, isConstant); ! } ! ! RrdDouble(RrdUpdater updater) throws IOException { ! super(updater, RrdDouble.RRD_DOUBLE, false); ! } ! ! void set(double value) throws IOException { ! if(!isCachingAllowed()) { ! writeDouble(value); ! } ! // caching allowed ! else if(!cached || !Util.equal(cache, value)) { ! // update cache ! writeDouble(cache = value); ! cached = true; ! } ! } ! ! double get() throws IOException { ! return cached? cache: readDouble(); ! } ! } --- 1,57 ---- ! /* ============================================================ ! * JRobin : Pure java implementation of RRDTool's functionality ! * ============================================================ ! * ! * Project Info: http://www.jrobin.org ! * Project Lead: Sasa Markovic (sa...@jr...); ! * ! * (C) Copyright 2003-2005, by Sasa Markovic. ! * ! * Developers: Sasa Markovic (sa...@jr...) ! * ! * ! * This library is free software; you can redistribute it and/or modify it under the terms ! * of the GNU Lesser General Public License as published by the Free Software Foundation; ! * either version 2.1 of the License, or (at your option) any later version. ! * ! * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; ! * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. ! * See the GNU Lesser General Public License for more details. ! * ! * You should have received a copy of the GNU Lesser General Public License along with this ! * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, ! * Boston, MA 02111-1307, USA. ! */ ! ! package org.jrobin.core; ! ! import java.io.IOException; ! ! class RrdDouble extends RrdPrimitive { ! private double cache; ! private boolean cached = false; ! ! RrdDouble(RrdUpdater updater, boolean isConstant) throws IOException { ! super(updater, RrdDouble.RRD_DOUBLE, isConstant); ! } ! ! RrdDouble(RrdUpdater updater) throws IOException { ! super(updater, RrdDouble.RRD_DOUBLE, false); ! } ! ! void set(double value) throws IOException { ! if (!isCachingAllowed()) { ! writeDouble(value); ! } ! // caching allowed ! else if (!cached || !Util.equal(cache, value)) { ! // update cache ! writeDouble(cache = value); ! cached = true; ! } ! } ! ! double get() throws IOException { ! return cached ? cache : readDouble(); ! } ! } Index: RrdUpdater.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/core/RrdUpdater.java,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** RrdUpdater.java 20 May 2004 10:29:33 -0000 1.4 --- RrdUpdater.java 21 Dec 2006 18:02:42 -0000 1.5 *************** *** 1,34 **** ! /* ============================================================ ! * JRobin : Pure java implementation of RRDTool's functionality ! * ============================================================ ! * ! * Project Info: http://www.jrobin.org ! * Project Lead: Sasa Markovic (sa...@jr...); ! * ! * (C) Copyright 2003, by Sasa Markovic. ! * ! * Developers: Sasa Markovic (sa...@jr...) ! * Arne Vandamme (cob...@jr...) ! * ! * This library is free software; you can redistribute it and/or modify it under the terms ! * of the GNU Lesser General Public License as published by the Free Software Foundation; ! * either version 2.1 of the License, or (at your option) any later version. ! * ! * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; ! * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. ! * See the GNU Lesser General Public License for more details. ! * ! * You should have received a copy of the GNU Lesser General Public License along with this ! * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, ! * Boston, MA 02111-1307, USA. ! */ ! ! package org.jrobin.core; ! ! import java.io.IOException; ! ! interface RrdUpdater { ! public RrdBackend getRrdBackend(); ! public void copyStateTo(RrdUpdater updater) throws IOException, RrdException; ! public RrdAllocator getRrdAllocator(); ! } --- 1,36 ---- ! /* ============================================================ ! * JRobin : Pure java implementation of RRDTool's functionality ! * ============================================================ ! * ! * Project Info: http://www.jrobin.org ! * Project Lead: Sasa Markovic (sa...@jr...); ! * ! * (C) Copyright 2003-2005, by Sasa Markovic. ! * ! * Developers: Sasa Markovic (sa...@jr...) ! * ! * ! * This library is free software; you can redistribute it and/or modify it under the terms ! * of the GNU Lesser General Public License as published by the Free Software Foundation; ! * either version 2.1 of the License, or (at your option) any later version. ! * ! * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; ! * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. ! * See the GNU Lesser General Public License for more details. ! * ! * You should have received a copy of the GNU Lesser General Public License along with this ! * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, ! * Boston, MA 02111-1307, USA. ! */ ! ! package org.jrobin.core; ! ! import java.io.IOException; ! ! interface RrdUpdater { ! public RrdBackend getRrdBackend(); ! ! public void copyStateTo(RrdUpdater updater) throws IOException, RrdException; ! ! public RrdAllocator getRrdAllocator(); ! } Index: RrdString.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/core/RrdString.java,v retrieving revision 1.11 retrieving revision 1.12 diff -C2 -d -r1.11 -r1.12 *** RrdString.java 9 Nov 2004 11:36:53 -0000 1.11 --- RrdString.java 21 Dec 2006 18:02:41 -0000 1.12 *************** *** 1,55 **** ! /* ============================================================ ! * 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. ! */ ! ! package org.jrobin.core; ! ! import java.io.IOException; ! ! class RrdString extends RrdPrimitive { ! private String cache; ! ! RrdString(RrdUpdater updater, boolean isConstant) throws IOException { ! super(updater, RrdPrimitive.RRD_STRING, isConstant); ! } ! ! RrdString(RrdUpdater updater) throws IOException { ! this(updater, false); ! } ! ! void set(String value) throws IOException { ! if(!isCachingAllowed()) { ! writeString(value); ! } ! // caching allowed ! else if(cache == null || !cache.equals(value)) { ! // update cache ! writeString(cache = value); ! } ! } ! ! String get() throws IOException { ! return (cache != null)? cache: readString(); ! } ! } --- 1,55 ---- ! /* ============================================================ ! * JRobin : Pure java implementation of RRDTool's functionality ! * ============================================================ ! * ! * Project Info: http://www.jrobin.org ! * Project Lead: Sasa Markovic (sa...@jr...); ! * ! * (C) Copyright 2003-2005, 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...) ! * ! * ! * 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.core; ! ! import java.io.IOException; ! ! class RrdString extends RrdPrimitive { ! private String cache; ! ! RrdString(RrdUpdater updater, boolean isConstant) throws IOException { ! super(updater, RrdPrimitive.RRD_STRING, isConstant); ! } ! ! RrdString(RrdUpdater updater) throws IOException { ! this(updater, false); ! } ! ! void set(String value) throws IOException { ! if (!isCachingAllowed()) { ! writeString(value); ! } ! // caching allowed ! else if (cache == null || !cache.equals(value)) { ! // update cache ! writeString(cache = value); ! } ! } ! ! String get() throws IOException { ! return (cache != null) ? cache : readString(); ! } ! } Index: XmlWriter.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/core/XmlWriter.java,v retrieving revision 1.6 retrieving revision 1.7 diff -C2 -d -r1.6 -r1.7 *** XmlWriter.java 8 Mar 2004 13:14:39 -0000 1.6 --- XmlWriter.java 21 Dec 2006 18:02:42 -0000 1.7 *************** *** 1,197 **** ! /* ============================================================ ! * JRobin : Pure java implementation of RRDTool's functionality ! * ============================================================ ! * ! * Project Info: http://www.jrobin.org ! * Project Lead: Sasa Markovic (sa...@jr...); ! * ! * (C) Copyright 2003, by Sasa Markovic. ! * ! * Developers: Sasa Markovic (sa...@jr...) ! * Arne Vandamme (cob...@jr...) ! * ! * This library is free software; you can redistribute it and/or modify it under the terms ! * of the GNU Lesser General Public License as published by the Free Software Foundation; ! * either version 2.1 of the License, or (at your option) any later version. ! * ! * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; ! * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. ! * See the GNU Lesser General Public License for more details. ! * ! * You should have received a copy of the GNU Lesser General Public License along with this ! * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, ! * Boston, MA 02111-1307, USA. ! */ ! ! package org.jrobin.core; ! ! import java.io.OutputStream; ! import java.io.PrintWriter; ! import java.io.File; ! import java.util.Stack; ! import java.awt.*; ! ! /** ! * Extremely simple utility class used to create XML documents. ! */ ! public class XmlWriter { ! static final String INDENT_STR = " "; ! ! private PrintWriter writer; ! private StringBuffer indent = new StringBuffer(""); ! private Stack openTags = new Stack(); ! ! /** ! * Creates XmlWriter with the specified output stream to send XML code to. ! * @param stream Output stream which receives XML code ! */ ! public XmlWriter(OutputStream stream) { ! writer = new PrintWriter(stream); ! } ! ! /** ! * Opens XML tag ! * @param tag XML tag name ! */ ! public void startTag(String tag) { ! writer.println(indent + "<" + tag + ">"); ! openTags.push(tag); ! indent.append(INDENT_STR); ! } ! ! /** ! * Closes the corresponding XML tag ! */ ! public void closeTag() { ! String tag = (String) openTags.pop(); ! indent.setLength(indent.length() - INDENT_STR.length()); ! writer.println(indent + "</" + tag + ">"); ! } ! ! /** ! * Writes <tag>value</tag> to output stream ! * @param tag XML tag name ! * @param value value to be placed between <code><tag></code> and <code></tag></code> ! */ ! public void writeTag(String tag, Object value) { ! if(value != null) { ! writer.println(indent + "<" + tag + ">" + ! escape(value.toString()) + "</" + tag + ">"); ! } ! else { ! writer.println(indent + "<" + tag + "></" + tag + ">"); ! } ! } ! ! /** ! * Writes <tag>value</tag> to output stream ! * @param tag XML tag name ! * @param value value to be placed between <code><tag></code> and <code></tag></code> ! */ ! public void writeTag(String tag, int value) { ! writeTag(tag, "" + value); ! } ! ! /** ! * Writes <tag>value</tag> to output stream ! * @param tag XML tag name ! * @param value value to be placed between <code><tag></code> and <code></tag></code> ! */ ! public void writeTag(String tag, long value) { ! writeTag(tag, "" + value); ! } ! ! /** ! * Writes <tag>value</tag> to output stream ! * @param tag XML tag name ! * @param value value to be placed between <code><tag></code> and <code></tag></code> ! */ ! public void writeTag(String tag, double value, String nanString) { ! writeTag(tag, Util.formatDouble(value, nanString, true)); ! } ! ! /** ! * Writes <tag>value</tag> to output stream ! * @param tag XML tag name ! * @param value value to be placed between <code><tag></code> and <code></tag></code> ! */ ! public void writeTag(String tag, double value) { ! writeTag(tag, Util.formatDouble(value, true)); ! } ! ! /** ! * Writes <tag>value</tag> to output stream ! * @param tag XML ta... [truncated message content] |
From: Tarus B. <ta...@us...> - 2006-12-21 18:03:16
|
Update of /cvsroot/jrobin/src/org/jrobin/core/jrrd In directory sc8-pr-cvs6.sourceforge.net:/tmp/cvs-serv9082/org/jrobin/core/jrrd Modified Files: Archive.java CDPStatusBlock.java ConsolidationFunctionType.java Constants.java DataChunk.java DataSource.java DataSourceType.java Header.java PDPStatusBlock.java RRDException.java RRDFile.java RRDatabase.java Log Message: Adding the new 1.5.4 code Index: DataSourceType.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/core/jrrd/DataSourceType.java,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** DataSourceType.java 22 Jul 2004 09:34:10 -0000 1.1 --- DataSourceType.java 21 Dec 2006 18:02:42 -0000 1.2 *************** *** 1,127 **** ! /* ! * Copyright (C) 2001 Ciaran Treanor <ci...@co...> ! * ! * Distributable under GPL license. ! * See terms of license at gnu.org. ! * ! * $Id$ ! */ ! package org.jrobin.core.jrrd; ! ! /** ! * Class DataSourceType ! * ! * @author <a href="mailto:ci...@co...">Ciaran Treanor</a> ! * @version $Revision$ ! */ ! public class DataSourceType { ! ! private static final int _COUNTER = 0; ! private static final String STR_COUNTER = "COUNTER"; ! ! /** ! * Field COUNTER ! */ ! public static final DataSourceType COUNTER = ! new DataSourceType(_COUNTER); ! private static final int _ABSOLUTE = 1; ! private static final String STR_ABSOLUTE = "ABSOLUTE"; ! ! /** ! * Field ABSOLUTE ! */ ! public static final DataSourceType ABSOLUTE = ! new DataSourceType(_ABSOLUTE); ! private static final int _GAUGE = 2; ! private static final String STR_GAUGE = "GAUGE"; ! ! /** ! * Field GAUGE ! */ ! public static final DataSourceType GAUGE = new DataSourceType(_GAUGE); ! private static final int _DERIVE = 3; ! private static final String STR_DERIVE = "DERIVE"; ! ! /** ! * Field DERIVE ! */ ! public static final DataSourceType DERIVE = new DataSourceType(_DERIVE); ! private int type; ! ! private DataSourceType(int type) { ! this.type = type; ! } ! ! /** ! * Returns a <code>DataSourceType</code> with the given name. ! * ! * @param s name of the <code>DataSourceType</code> required. ! * @return a <code>DataSourceType</code> with the given name. ! */ ! public static DataSourceType get(String s) { ! ! if (s.equalsIgnoreCase(STR_COUNTER)) { ! return COUNTER; ! } else if (s.equalsIgnoreCase(STR_ABSOLUTE)) { ! return ABSOLUTE; ! } else if (s.equalsIgnoreCase(STR_GAUGE)) { ! return GAUGE; ! } else if (s.equalsIgnoreCase(STR_DERIVE)) { ! return DERIVE; ! } else { ! throw new IllegalArgumentException("Invalid DataSourceType"); ! } ! } ! ! /** ! * Compares this object against the specified object. ! * ! * @return <code>true</code> if the objects are the same, ! * <code>false</code> otherwise. ! */ ! public boolean equals(Object obj) { ! ! if (!(obj instanceof DataSourceType)) { ! throw new IllegalArgumentException("Not a DataSourceType"); ! } ! ! return (((DataSourceType) obj).type == type) ! ? true ! : false; ! } ! ! /** ! * Returns a string representation of this object. ! * ! * @return a string representation of this object. ! */ ! public String toString() { ! ! String strType; ! ! switch (type) { ! ! case _COUNTER: ! strType = STR_COUNTER; ! break; ! ! case _ABSOLUTE: ! strType = STR_ABSOLUTE; ! break; ! ! case _GAUGE: ! strType = STR_GAUGE; ! break; ! ! case _DERIVE: ! strType = STR_DERIVE; ! break; ! ! default : ! // Don't you just hate it when you see a line like this? ! throw new RuntimeException("This should never happen"); ! } ! ! return strType; ! } ! } --- 1,131 ---- ! /* ! * Copyright (C) 2001 Ciaran Treanor <ci...@co...> ! * ! * Distributable under GPL license. ! * See terms of license at gnu.org. ! * ! * $Id$ ! */ ! package org.jrobin.core.jrrd; ! ! /** ! * Class DataSourceType ! * ! * @author <a href="mailto:ci...@co...">Ciaran Treanor</a> ! * @version $Revision$ ! */ ! public class DataSourceType { ! ! private static final int _COUNTER = 0; ! private static final String STR_COUNTER = "COUNTER"; ! ! /** ! * Field COUNTER ! */ ! public static final DataSourceType COUNTER = ! new DataSourceType(_COUNTER); ! private static final int _ABSOLUTE = 1; ! private static final String STR_ABSOLUTE = "ABSOLUTE"; ! ! /** ! * Field ABSOLUTE ! */ ! public static final DataSourceType ABSOLUTE = ! new DataSourceType(_ABSOLUTE); ! private static final int _GAUGE = 2; ! private static final String STR_GAUGE = "GAUGE"; ! ! /** ! * Field GAUGE ! */ ! public static final DataSourceType GAUGE = new DataSourceType(_GAUGE); ! private static final int _DERIVE = 3; ! private static final String STR_DERIVE = "DERIVE"; ! ! /** ! * Field DERIVE ! */ ! public static final DataSourceType DERIVE = new DataSourceType(_DERIVE); ! private int type; ! ! private DataSourceType(int type) { ! this.type = type; ! } ! ! /** ! * Returns a <code>DataSourceType</code> with the given name. ! * ! * @param s name of the <code>DataSourceType</code> required. ! * @return a <code>DataSourceType</code> with the given name. ! */ ! public static DataSourceType get(String s) { ! ! if (s.equalsIgnoreCase(STR_COUNTER)) { ! return COUNTER; ! } ! else if (s.equalsIgnoreCase(STR_ABSOLUTE)) { ! return ABSOLUTE; ! } ! else if (s.equalsIgnoreCase(STR_GAUGE)) { ! return GAUGE; ! } ! else if (s.equalsIgnoreCase(STR_DERIVE)) { ! return DERIVE; ! } ! else { ! throw new IllegalArgumentException("Invalid DataSourceType"); ! } ! } ! ! /** ! * Compares this object against the specified object. ! * ! * @return <code>true</code> if the objects are the same, ! * <code>false</code> otherwise. ! */ ! public boolean equals(Object obj) { ! ! if (!(obj instanceof DataSourceType)) { ! throw new IllegalArgumentException("Not a DataSourceType"); ! } ! ! return (((DataSourceType) obj).type == type) ! ? true ! : false; ! } ! ! /** ! * Returns a string representation of this object. ! * ! * @return a string representation of this object. ! */ ! public String toString() { ! ! String strType; ! ! switch (type) { ! ! case _COUNTER: ! strType = STR_COUNTER; ! break; ! ! case _ABSOLUTE: ! strType = STR_ABSOLUTE; ! break; ! ! case _GAUGE: ! strType = STR_GAUGE; ! break; ! ! case _DERIVE: ! strType = STR_DERIVE; ! break; ! ! default : ! // Don't you just hate it when you see a line like this? ! throw new RuntimeException("This should never happen"); ! } ! ! return strType; ! } ! } Index: ConsolidationFunctionType.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/core/jrrd/ConsolidationFunctionType.java,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** ConsolidationFunctionType.java 22 Jul 2004 09:34:10 -0000 1.1 --- ConsolidationFunctionType.java 21 Dec 2006 18:02:42 -0000 1.2 *************** *** 1,128 **** ! /* ! * Copyright (C) 2001 Ciaran Treanor <ci...@co...> ! * ! * Distributable under GPL license. ! * See terms of license at gnu.org. ! * ! * $Id$ ! */ ! package org.jrobin.core.jrrd; ! ! /** ! * Class ConsolidationFunctionType ! * ! * @author <a href="mailto:ci...@co...">Ciaran Treanor</a> ! * @version $Revision$ ! */ ! public class ConsolidationFunctionType { ! ! private static final int _AVERAGE = 0; ! private static final String STR_AVERAGE = "AVERAGE"; ! ! /** ! * Field AVERAGE ! */ ! public static final ConsolidationFunctionType AVERAGE = ! new ConsolidationFunctionType(_AVERAGE); ! private static final int _MIN = 1; ! private static final String STR_MIN = "MIN"; ! ! /** ! * Field MIN ! */ ! public static final ConsolidationFunctionType MIN = ! new ConsolidationFunctionType(_MIN); ! private static final int _MAX = 2; ! private static final String STR_MAX = "MAX"; ! ! /** ! * Field MAX ! */ ! public static final ConsolidationFunctionType MAX = ! new ConsolidationFunctionType(_MAX); ! private static final int _LAST = 3; ! private static final String STR_LAST = "LAST"; ! ! /** ! * Field LAST ! */ ! public static final ConsolidationFunctionType LAST = ! new ConsolidationFunctionType(_LAST); ! private int type; ! ! private ConsolidationFunctionType(int type) { ! this.type = type; ! } ! ! /** ! * Returns a <code>ConsolidationFunctionType</code> with the given name. ! * ! * @param s name of the <code>ConsolidationFunctionType</code> required. ! * @return a <code>ConsolidationFunctionType</code> with the given name. ! */ ! public static ConsolidationFunctionType get(String s) { ! ! if (s.equalsIgnoreCase(STR_AVERAGE)) { ! return AVERAGE; ! } else if (s.equalsIgnoreCase(STR_MIN)) { ! return MIN; ! } else if (s.equalsIgnoreCase(STR_MAX)) { ! return MAX; ! } else if (s.equalsIgnoreCase(STR_LAST)) { ! return LAST; ! } else { ! throw new IllegalArgumentException("Invalid ConsolidationFunctionType"); ! } ! } ! ! /** ! * Compares this object against the specified object. ! * ! * @return <code>true</code> if the objects are the same, ! * <code>false</code> otherwise. ! */ ! public boolean equals(Object o) { ! ! if (!(o instanceof ConsolidationFunctionType)) { ! throw new IllegalArgumentException("Not a ConsolidationFunctionType"); ! } ! ! return (((ConsolidationFunctionType) o).type == type) ! ? true ! : false; ! } ! ! /** ! * Returns a string representation of this object. ! * ! * @return a string representation of this object. ! */ ! public String toString() { ! ! String strType; ! ! switch (type) { ! ! case _AVERAGE: ! strType = STR_AVERAGE; ! break; ! ! case _MIN: ! strType = STR_MIN; ! break; ! ! case _MAX: ! strType = STR_MAX; ! break; ! ! case _LAST: ! strType = STR_LAST; ! break; ! ! default : ! throw new RuntimeException("This should never happen"); ! } ! ! return strType; ! } ! } --- 1,132 ---- ! /* ! * Copyright (C) 2001 Ciaran Treanor <ci...@co...> ! * ! * Distributable under GPL license. ! * See terms of license at gnu.org. ! * ! * $Id$ ! */ ! package org.jrobin.core.jrrd; ! ! /** ! * Class ConsolidationFunctionType ! * ! * @author <a href="mailto:ci...@co...">Ciaran Treanor</a> ! * @version $Revision$ ! */ ! public class ConsolidationFunctionType { ! ! private static final int _AVERAGE = 0; ! private static final String STR_AVERAGE = "AVERAGE"; ! ! /** ! * Field AVERAGE ! */ ! public static final ConsolidationFunctionType AVERAGE = ! new ConsolidationFunctionType(_AVERAGE); ! private static final int _MIN = 1; ! private static final String STR_MIN = "MIN"; ! ! /** ! * Field MIN ! */ ! public static final ConsolidationFunctionType MIN = ! new ConsolidationFunctionType(_MIN); ! private static final int _MAX = 2; ! private static final String STR_MAX = "MAX"; ! ! /** ! * Field MAX ! */ ! public static final ConsolidationFunctionType MAX = ! new ConsolidationFunctionType(_MAX); ! private static final int _LAST = 3; ! private static final String STR_LAST = "LAST"; ! ! /** ! * Field LAST ! */ ! public static final ConsolidationFunctionType LAST = ! new ConsolidationFunctionType(_LAST); ! private int type; ! ! private ConsolidationFunctionType(int type) { ! this.type = type; ! } ! ! /** ! * Returns a <code>ConsolidationFunctionType</code> with the given name. ! * ! * @param s name of the <code>ConsolidationFunctionType</code> required. ! * @return a <code>ConsolidationFunctionType</code> with the given name. ! */ ! public static ConsolidationFunctionType get(String s) { ! ! if (s.equalsIgnoreCase(STR_AVERAGE)) { ! return AVERAGE; ! } ! else if (s.equalsIgnoreCase(STR_MIN)) { ! return MIN; ! } ! else if (s.equalsIgnoreCase(STR_MAX)) { ! return MAX; ! } ! else if (s.equalsIgnoreCase(STR_LAST)) { ! return LAST; ! } ! else { ! throw new IllegalArgumentException("Invalid ConsolidationFunctionType"); ! } ! } ! ! /** ! * Compares this object against the specified object. ! * ! * @return <code>true</code> if the objects are the same, ! * <code>false</code> otherwise. ! */ ! public boolean equals(Object o) { ! ! if (!(o instanceof ConsolidationFunctionType)) { ! throw new IllegalArgumentException("Not a ConsolidationFunctionType"); ! } ! ! return (((ConsolidationFunctionType) o).type == type) ! ? true ! : false; ! } ! ! /** ! * Returns a string representation of this object. ! * ! * @return a string representation of this object. ! */ ! public String toString() { ! ! String strType; ! ! switch (type) { ! ! case _AVERAGE: ! strType = STR_AVERAGE; ! break; ! ! case _MIN: ! strType = STR_MIN; ! break; ! ! case _MAX: ! strType = STR_MAX; ! break; ! ! case _LAST: ! strType = STR_LAST; ! break; ! ! default : ! throw new RuntimeException("This should never happen"); ! } ! ! return strType; ! } ! } Index: RRDException.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/core/jrrd/RRDException.java,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** RRDException.java 22 Jul 2004 09:34:10 -0000 1.1 --- RRDException.java 21 Dec 2006 18:02:42 -0000 1.2 *************** *** 1,33 **** ! /* ! * Copyright (C) 2001 Ciaran Treanor <ci...@co...> ! * ! * Distributable under GPL license. ! * See terms of license at gnu.org. ! * ! * $Id$ ! */ ! package org.jrobin.core.jrrd; ! ! /** ! * This exception may be throw if an error occurs while operating ! * on an RRD object. ! * ! * @author <a href="mailto:ci...@co...">Ciaran Treanor</a> ! * @version $Revision$ ! */ ! public class RRDException extends Exception { ! ! /** ! * Constructs an RRDException with no detail message. ! */ ! public RRDException() { ! super(); ! } ! ! /** ! * Constructs an RRDException with the specified detail message. ! */ ! public RRDException(String message) { ! super(message); ! } ! } --- 1,33 ---- ! /* ! * Copyright (C) 2001 Ciaran Treanor <ci...@co...> ! * ! * Distributable under GPL license. ! * See terms of license at gnu.org. ! * ! * $Id$ ! */ ! package org.jrobin.core.jrrd; ! ! /** ! * This exception may be throw if an error occurs while operating ! * on an RRD object. ! * ! * @author <a href="mailto:ci...@co...">Ciaran Treanor</a> ! * @version $Revision$ ! */ ! public class RRDException extends Exception { ! ! /** ! * Constructs an RRDException with no detail message. ! */ ! public RRDException() { ! super(); ! } ! ! /** ! * Constructs an RRDException with the specified detail message. ! */ ! public RRDException(String message) { ! super(message); ! } ! } Index: Header.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/core/jrrd/Header.java,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** Header.java 22 Jul 2004 09:34:10 -0000 1.1 --- Header.java 21 Dec 2006 18:02:42 -0000 1.2 *************** *** 1,112 **** ! /* ! * Copyright (C) 2001 Ciaran Treanor <ci...@co...> ! * ! * Distributable under GPL license. ! * See terms of license at gnu.org. ! * ! * $Id$ ! */ ! package org.jrobin.core.jrrd; ! ! import java.io.*; ! ! /** ! * Instances of this class model the header section of an RRD file. ! * ! * @author <a href="mailto:ci...@co...">Ciaran Treanor</a> ! * @version $Revision$ ! */ ! public class Header implements Constants { ! ! static final long offset = 0; ! long size; ! String version; ! int dsCount; ! int rraCount; ! int pdpStep; ! ! Header(RRDFile file) throws IOException { ! ! if (!file.readString(4).equals(COOKIE)) { ! throw new IOException("Invalid COOKIE"); ! } ! ! if (!(version = file.readString(5)).equals(VERSION)) { ! throw new IOException("Unsupported RRD version (" + version + ")"); ! } ! ! file.align(); ! ! // Consume the FLOAT_COOKIE ! file.readDouble(); ! ! dsCount = file.readInt(); ! rraCount = file.readInt(); ! pdpStep = file.readInt(); ! ! // Skip rest of stat_head_t.par ! file.align(); ! file.skipBytes(80); ! ! size = file.getFilePointer() - offset; ! } ! ! /** ! * Returns the version of the database. ! * ! * @return the version of the database. ! */ ! public String getVersion() { ! return version; ! } ! ! /** ! * Returns the number of <code>DataSource</code>s in the database. ! * ! * @return the number of <code>DataSource</code>s in the database. ! */ ! public int getDSCount() { ! return dsCount; ! } ! ! /** ! * Returns the number of <code>Archive</code>s in the database. ! * ! * @return the number of <code>Archive</code>s in the database. ! */ ! public int getRRACount() { ! return rraCount; ! } ! ! /** ! * Returns the primary data point interval in seconds. ! * ! * @return the primary data point interval in seconds. ! */ ! public int getPDPStep() { ! return pdpStep; ! } ! ! /** ! * Returns a summary the contents of this header. ! * ! * @return a summary of the information contained in this header. ! */ ! public String toString() { ! ! StringBuffer sb = new StringBuffer("[Header: OFFSET=0x00, SIZE=0x"); ! ! sb.append(Long.toHexString(size)); ! sb.append(", version="); ! sb.append(version); ! sb.append(", dsCount="); ! sb.append(dsCount); ! sb.append(", rraCount="); ! sb.append(rraCount); ! sb.append(", pdpStep="); ! sb.append(pdpStep); ! sb.append("]"); ! ! return sb.toString(); ! } ! } --- 1,112 ---- ! /* ! * Copyright (C) 2001 Ciaran Treanor <ci...@co...> ! * ! * Distributable under GPL license. ! * See terms of license at gnu.org. ! * ! * $Id$ ! */ ! package org.jrobin.core.jrrd; ! ! import java.io.IOException; ! ! /** ! * Instances of this class model the header section of an RRD file. ! * ! * @author <a href="mailto:ci...@co...">Ciaran Treanor</a> ! * @version $Revision$ ! */ ! public class Header implements Constants { ! ! static final long offset = 0; ! long size; ! String version; ! int dsCount; ! int rraCount; ! int pdpStep; ! ! Header(RRDFile file) throws IOException { ! ! if (!file.readString(4).equals(COOKIE)) { ! throw new IOException("Invalid COOKIE"); ! } ! ! if (!(version = file.readString(5)).equals(VERSION)) { ! throw new IOException("Unsupported RRD version (" + version + ")"); ! } ! ! file.align(); ! ! // Consume the FLOAT_COOKIE ! file.readDouble(); ! ! dsCount = file.readInt(); ! rraCount = file.readInt(); ! pdpStep = file.readInt(); ! ! // Skip rest of stat_head_t.par ! file.align(); ! file.skipBytes(80); ! ! size = file.getFilePointer() - offset; ! } ! ! /** ! * Returns the version of the database. ! * ! * @return the version of the database. ! */ ! public String getVersion() { ! return version; ! } ! ! /** ! * Returns the number of <code>DataSource</code>s in the database. ! * ! * @return the number of <code>DataSource</code>s in the database. ! */ ! public int getDSCount() { ! return dsCount; ! } ! ! /** ! * Returns the number of <code>Archive</code>s in the database. ! * ! * @return the number of <code>Archive</code>s in the database. ! */ ! public int getRRACount() { ! return rraCount; ! } ! ! /** ! * Returns the primary data point interval in seconds. ! * ! * @return the primary data point interval in seconds. ! */ ! public int getPDPStep() { ! return pdpStep; ! } ! ! /** ! * Returns a summary the contents of this header. ! * ! * @return a summary of the information contained in this header. ! */ ! public String toString() { ! ! StringBuffer sb = new StringBuffer("[Header: OFFSET=0x00, SIZE=0x"); ! ! sb.append(Long.toHexString(size)); ! sb.append(", version="); ! sb.append(version); ! sb.append(", dsCount="); ! sb.append(dsCount); ! sb.append(", rraCount="); ! sb.append(rraCount); ! sb.append(", pdpStep="); ! sb.append(pdpStep); ! sb.append("]"); ! ! return sb.toString(); ! } ! } Index: Archive.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/core/jrrd/Archive.java,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** Archive.java 5 Nov 2004 12:22:52 -0000 1.2 --- Archive.java 21 Dec 2006 18:02:42 -0000 1.3 *************** *** 1,404 **** ! /* ! * Copyright (C) 2001 Ciaran Treanor <ci...@co...> ! * ! * Distributable under GPL license. ! * See terms of license at gnu.org. ! * ! * $Id$ ! */ ! package org.jrobin.core.jrrd; ! ! import java.io.IOException; ! import java.io.PrintStream; ! import java.text.*; ! import java.util.*; ! ! /** ! * Instances of this class model an archive section of an RRD file. ! * ! * @author <a href="mailto:ci...@co...">Ciaran Treanor</a> ! * @version $Revision$ ! */ ! public class Archive { ! ! RRDatabase db; ! long offset; ! long dataOffset; ! long size; ! ConsolidationFunctionType type; ! int rowCount; ! int pdpCount; ! double xff; ! ArrayList cdpStatusBlocks; ! int currentRow; ! ! private double[][] values; ! ! Archive(RRDatabase db) throws IOException { ! ! this.db = db; ! ! RRDFile file = db.rrdFile; ! ! offset = file.getFilePointer(); ! type = ! ConsolidationFunctionType.get(file.readString(Constants.CF_NAM_SIZE)); ! rowCount = file.readInt(); ! pdpCount = file.readInt(); ! ! file.align(); ! ! xff = file.readDouble(); ! ! // Skip rest of rra_def_t.par[] ! file.align(); ! file.skipBytes(72); ! ! size = file.getFilePointer() - offset; ! } ! ! /** ! * Returns the type of function used to calculate the consolidated data point. ! * ! * @return the type of function used to calculate the consolidated data point. ! */ ! public ConsolidationFunctionType getType() { ! return type; ! } ! ! void loadCDPStatusBlocks(RRDFile file, int numBlocks) throws IOException { ! ! cdpStatusBlocks = new ArrayList(); ! ! for (int i = 0; i < numBlocks; i++) { ! cdpStatusBlocks.add(new CDPStatusBlock(file)); ! } ! } ! ! /** ! * Returns the <code>CDPStatusBlock</code> at the specified position in this archive. ! * ! * @param index index of <code>CDPStatusBlock</code> to return. ! * @return the <code>CDPStatusBlock</code> at the specified position in this archive. ! */ ! public CDPStatusBlock getCDPStatusBlock(int index) { ! return (CDPStatusBlock) cdpStatusBlocks.get(index); ! } ! ! /** ! * Returns an iterator over the CDP status blocks in this archive in proper sequence. ! * ! * @return an iterator over the CDP status blocks in this archive in proper sequence. ! * @see CDPStatusBlock ! */ ! public Iterator getCDPStatusBlocks() { ! return cdpStatusBlocks.iterator(); ! } ! ! void loadCurrentRow(RRDFile file) throws IOException { ! currentRow = file.readInt(); ! } ! ! void loadData(RRDFile file, int dsCount) throws IOException { ! ! dataOffset = file.getFilePointer(); ! ! // Skip over the data to position ourselves at the start of the next archive ! file.skipBytes(8 * rowCount * dsCount); ! } ! ! DataChunk loadData(DataChunk chunk) throws IOException { ! ! Calendar end = Calendar.getInstance(); ! Calendar start = (Calendar) end.clone(); ! ! start.add(Calendar.DATE, -1); ! ! loadData(chunk, start.getTime().getTime() / 1000, ! end.getTime().getTime() / 1000); ! return chunk; ! } ! ! void loadData(DataChunk chunk, long startTime, long endTime) ! throws IOException { ! ! long pointer; ! ! if (chunk.start < 0) { ! pointer = currentRow + 1; ! } else { ! pointer = currentRow + chunk.start + 1; ! } ! ! db.rrdFile.ras.seek(dataOffset + (pointer * 8)); ! //cat.debug("Archive Base: " + dataOffset + " Archive Pointer: " + pointer); ! //cat.debug("Start Offset: " + chunk.start + " End Offset: " ! // + (rowCount - chunk.end)); ! ! double[][] data = chunk.data; ! ! /* ! * This is also terrible - cleanup - CT ! */ ! int row = 0; ! for (int i = chunk.start; i < rowCount - chunk.end; i++, row++) { ! if (i < 0) { // no valid data yet ! for (int ii = 0; ii < chunk.dsCount; ii++) { ! data[row][ii] = Double.NaN; ! } ! } else if (i >= rowCount) { // past valid data area ! for (int ii = 0; ii < chunk.dsCount; ii++) { ! data[row][ii] = Double.NaN; ! } ! } else { // inside the valid are but the pointer has to be wrapped ! if (pointer >= rowCount) { ! pointer -= rowCount; ! ! db.rrdFile.ras.seek(dataOffset + (pointer * 8)); ! } ! ! for (int ii = 0; ii < chunk.dsCount; ii++) { ! data[row][ii] = db.rrdFile.readDouble(); ! } ! ! pointer++; ! } ! } ! } ! ! void printInfo(PrintStream s, NumberFormat numberFormat, int index) { ! ! StringBuffer sb = new StringBuffer("rra["); ! ! sb.append(index); ! s.print(sb); ! s.print("].cf = \""); ! s.print(type); ! s.println("\""); ! s.print(sb); ! s.print("].rows = "); ! s.println(rowCount); ! s.print(sb); ! s.print("].pdp_per_row = "); ! s.println(pdpCount); ! s.print(sb); ! s.print("].xff = "); ! s.println(xff); ! sb.append("].cdp_prep["); ! ! int cdpIndex = 0; ! ! for (Iterator i = cdpStatusBlocks.iterator(); i.hasNext();) { ! CDPStatusBlock cdp = (CDPStatusBlock) i.next(); ! ! s.print(sb); ! s.print(cdpIndex); ! s.print("].value = "); ! ! double value = cdp.value; ! ! s.println(Double.isNaN(value) ! ? "NaN" ! : numberFormat.format(value)); ! s.print(sb); ! s.print(cdpIndex++); ! s.print("].unknown_datapoints = "); ! s.println(cdp.unknownDatapoints); ! } ! } ! ! void toXml(PrintStream s) { ! ! try { ! s.println("\t<rra>"); ! s.print("\t\t<cf> "); ! s.print(type); ! s.println(" </cf>"); ! s.print("\t\t<pdp_per_row> "); ! s.print(pdpCount); ! s.print(" </pdp_per_row> <!-- "); ! s.print(db.header.pdpStep * pdpCount); ! s.println(" seconds -->"); ! s.print("\t\t<xff> "); ! s.print(xff); ! s.println(" </xff>"); ! s.println(); ! s.println("\t\t<cdp_prep>"); ! ! for (int i = 0; i < cdpStatusBlocks.size(); i++) { ! ((CDPStatusBlock) cdpStatusBlocks.get(i)).toXml(s); ! } ! ! s.println("\t\t</cdp_prep>"); ! s.println("\t\t<database>"); ! ! long timer = -(rowCount - 1); ! int counter = 0; ! int row = currentRow; ! ! db.rrdFile.ras.seek(dataOffset + (row + 1) * 16); ! ! long lastUpdate = db.lastUpdate.getTime() / 1000; ! int pdpStep = db.header.pdpStep; ! NumberFormat numberFormat = new DecimalFormat("0.0000000000E0"); ! SimpleDateFormat dateFormat = ! new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z"); ! ! while (counter++ < rowCount) { ! row++; ! ! if (row == rowCount) { ! row = 0; ! ! db.rrdFile.ras.seek(dataOffset); ! } ! ! long now = (lastUpdate - lastUpdate % (pdpCount * pdpStep)) ! + (timer * pdpCount * pdpStep); ! ! timer++; ! ! s.print("\t\t\t<!-- "); ! s.print(dateFormat.format(new Date(now * 1000))); ! s.print(" / "); ! s.print(now); ! s.print(" --> "); ! ! for (int col = 0; col < db.header.dsCount; col++) { ! s.print("<v> "); ! ! double value = db.rrdFile.readDouble(); ! ! // NumberFormat doesn't know how to handle NaN ! if (Double.isNaN(value)) { ! s.print("NaN"); ! } else { ! s.print(numberFormat.format(value)); ! } ! ! s.print(" </v>"); ! } ! ! s.println("</row>"); ! } ! ! s.println("\t\t</database>"); ! s.println("\t</rra>"); ! } catch (IOException e) { // Is the best thing to do here? ! throw new RuntimeException(e.getMessage()); ! } ! } ! ! /* ! // THIS IS THE ORIGINAL CODE: BUGGY! Replaced by Sasa Markovic with a new method ! // Funny: the bug will appear only if dsCount != 2 :) ! public double[][] getValuesOriginal() throws IOException { ! if (values != null) { ! return values; ! } ! values = new double[db.header.dsCount][rowCount]; ! int row = currentRow; ! db.rrdFile.ras.seek(dataOffset + (row + 1) * 16); // <----- BUG (resolved below) ! for (int counter = 0; counter < rowCount; counter++) { ! row++; ! if (row == rowCount) { ! row = 0; ! db.rrdFile.ras.seek(dataOffset); ! } ! for (int col = 0; col < db.header.dsCount; col++) { ! double value = db.rrdFile.readDouble(); ! values[col][counter] = value; ! } ! } ! return values; ! } ! */ ! ! // Resolved bug from the original method (see above) ! public double[][] getValues() throws IOException { ! // OK PART ! if (values != null) { ! return values; ! } ! values = new double[db.header.dsCount][rowCount]; ! int row = currentRow; ! // HERE ARE THE DRAGONS! ! db.rrdFile.ras.seek(dataOffset + (row + 1) * db.header.dsCount * 8); ! // OK, TOO! ! for (int counter = 0; counter < rowCount; counter++) { ! row++; ! if (row == rowCount) { ! row = 0; ! db.rrdFile.ras.seek(dataOffset); ! } ! for (int col = 0; col < db.header.dsCount; col++) { ! double value = db.rrdFile.readDouble(); ! values[col][counter] = value; ! } ! } ! return values; ! } ! ! /** ! * Returns the number of primary data points required for a consolidated ! * data point in this archive. ! * ! * @return the number of primary data points required for a consolidated ! * data point in this archive. ! */ ! public int getPdpCount() { ! return pdpCount; ! } ! ! /** ! * Returns the number of entries in this archive. ! * ! * @return the number of entries in this archive. ! */ ! public int getRowCount() { ! return rowCount; ! } ! ! /** ! * Returns the X-Files Factor for this archive. ! * ! * @return the X-Files Factor for this archive. ! */ ! public double getXff() { ! return xff; ! } ! ! /** ! * Returns a summary the contents of this archive. ! * ! * @return a summary of the information contained in this archive. ! */ ! public String toString() { ! ! StringBuffer sb = new StringBuffer("[Archive: OFFSET=0x"); ! ! sb.append(Long.toHexString(offset)); ! sb.append(", SIZE=0x"); ! sb.append(Long.toHexString(size)); ! sb.append(", type="); ! sb.append(type); ! sb.append(", rowCount="); ! sb.append(rowCount); ! sb.append(", pdpCount="); ! sb.append(pdpCount); ! sb.append(", xff="); ! sb.append(xff); ! sb.append(", currentRow="); ! sb.append(currentRow); ! sb.append("]"); ! ! for (Iterator i = cdpStatusBlocks.iterator(); i.hasNext();) { ! CDPStatusBlock cdp = (CDPStatusBlock) i.next(); ! ! sb.append("\n\t\t"); ! sb.append(cdp.toString()); ! } ! ! return sb.toString(); ! } ! } --- 1,414 ---- ! /* ! * Copyright (C) 2001 Ciaran Treanor <ci...@co...> ! * ! * Distributable under GPL license. ! * See terms of license at gnu.org. ! * ! * $Id$ ! */ ! package org.jrobin.core.jrrd; ! ! import java.io.IOException; ! import java.io.PrintStream; ! import java.text.DecimalFormat; ! import java.text.NumberFormat; ! import java.text.SimpleDateFormat; ! import java.util.ArrayList; ! import java.util.Calendar; ! import java.util.Date; ! import java.util.Iterator; ! ! /** ! * Instances of this class model an archive section of an RRD file. ! * ! * @author <a href="mailto:ci...@co...">Ciaran Treanor</a> ! * @version $Revision$ ! */ ! public class Archive { ! ! RRDatabase db; ! long offset; ! long dataOffset; ! long size; ! ConsolidationFunctionType type; ! int rowCount; ! int pdpCount; ! double xff; ! ArrayList<CDPStatusBlock> cdpStatusBlocks; ! int currentRow; ! ! private double[][] values; ! ! Archive(RRDatabase db) throws IOException { ! ! this.db = db; ! ! RRDFile file = db.rrdFile; ! ! offset = file.getFilePointer(); ! type = ! ConsolidationFunctionType.get(file.readString(Constants.CF_NAM_SIZE)); ! rowCount = file.readInt(); ! pdpCount = file.readInt(); ! ! file.align(); ! ! xff = file.readDouble(); ! ! // Skip rest of rra_def_t.par[] ! file.align(); ! file.skipBytes(72); ! ! size = file.getFilePointer() - offset; ! } ! ! /** ! * Returns the type of function used to calculate the consolidated data point. ! * ! * @return the type of function used to calculate the consolidated data point. ! */ ! public ConsolidationFunctionType getType() { ! return type; ! } ! ! void loadCDPStatusBlocks(RRDFile file, int numBlocks) throws IOException { ! ! cdpStatusBlocks = new ArrayList<CDPStatusBlock>(); ! ! for (int i = 0; i < numBlocks; i++) { ! cdpStatusBlocks.add(new CDPStatusBlock(file)); ! } ! } ! ! /** ! * Returns the <code>CDPStatusBlock</code> at the specified position in this archive. ! * ! * @param index index of <code>CDPStatusBlock</code> to return. ! * @return the <code>CDPStatusBlock</code> at the specified position in this archive. ! */ ! public CDPStatusBlock getCDPStatusBlock(int index) { ! return cdpStatusBlocks.get(index); ! } ! ! /** ! * Returns an iterator over the CDP status blocks in this archive in proper sequence. ! * ! * @return an iterator over the CDP status blocks in this archive in proper sequence. ! * @see CDPStatusBlock ! */ ! public Iterator<CDPStatusBlock> getCDPStatusBlocks() { ! return cdpStatusBlocks.iterator(); ! } ! ! void loadCurrentRow(RRDFile file) throws IOException { ! currentRow = file.readInt(); ! } ! ! void loadData(RRDFile file, int dsCount) throws IOException { ! ! dataOffset = file.getFilePointer(); ! ! // Skip over the data to position ourselves at the start of the next archive ! file.skipBytes(8 * rowCount * dsCount); ! } ! ! DataChunk loadData(DataChunk chunk) throws IOException { ! ! Calendar end = Calendar.getInstance(); ! Calendar start = (Calendar) end.clone(); ! ! start.add(Calendar.DATE, -1); ! ! loadData(chunk, start.getTime().getTime() / 1000, ! end.getTime().getTime() / 1000); ! return chunk; ! } ! ! void loadData(DataChunk chunk, long startTime, long endTime) ! throws IOException { ! ! long pointer; ! ! if (chunk.start < 0) { ! pointer = currentRow + 1; ! } ! else { ! pointer = currentRow + chunk.start + 1; ! } ! ! db.rrdFile.ras.seek(dataOffset + (pointer * 8)); ! //cat.debug("Archive Base: " + dataOffset + " Archive Pointer: " + pointer); ! //cat.debug("Start Offset: " + chunk.start + " End Offset: " ! // + (rowCount - chunk.end)); ! ! double[][] data = chunk.data; ! ! /* ! * This is also terrible - cleanup - CT ! */ ! int row = 0; ! for (int i = chunk.start; i < rowCount - chunk.end; i++, row++) { ! if (i < 0) { // no valid data yet ! for (int ii = 0; ii < chunk.dsCount; ii++) { ! data[row][ii] = Double.NaN; ! } ! } ! else if (i >= rowCount) { // past valid data area ! for (int ii = 0; ii < chunk.dsCount; ii++) { ! data[row][ii] = Double.NaN; ! } ! } ! else { // inside the valid are but the pointer has to be wrapped ! if (pointer >= rowCount) { ! pointer -= rowCount; ! ! db.rrdFile.ras.seek(dataOffset + (pointer * 8)); ! } ! ! for (int ii = 0; ii < chunk.dsCount; ii++) { ! data[row][ii] = db.rrdFile.readDouble(); ! } ! ! pointer++; ! } ! } ! } ! ! void printInfo(PrintStream s, NumberFormat numberFormat, int index) { ! ! StringBuffer sb = new StringBuffer("rra["); ! ! sb.append(index); ! s.print(sb); ! s.print("].cf = \""); ! s.print(type); ! s.println("\""); ! s.print(sb); ! s.print("].rows = "); ! s.println(rowCount); ! s.print(sb); ! s.print("].pdp_per_row = "); ! s.println(pdpCount); ! s.print(sb); ! s.print("].xff = "); ! s.println(xff); ! sb.append("].cdp_prep["); ! ! int cdpIndex = 0; ! ! for (Iterator<CDPStatusBlock> i = cdpStatusBlocks.iterator(); i.hasNext();) { ! CDPStatusBlock cdp = i.next(); ! ! s.print(sb); ! s.print(cdpIndex); ! s.print("].value = "); ! ! double value = cdp.value; ! ! s.println(Double.isNaN(value) ! ? "NaN" ! : numberFormat.format(value)); ! s.print(sb); ! s.print(cdpIndex++); ! s.print("].unknown_datapoints = "); ! s.println(cdp.unknownDatapoints); ! } ! } ! ! void toXml(PrintStream s) { ! ! try { ! s.println("\t<rra>"); ! s.print("\t\t<cf> "); ! s.print(type); ! s.println(" </cf>"); ! s.print("\t\t<pdp_per_row> "); ! s.print(pdpCount); ! s.print(" </pdp_per_row> <!-- "); ! s.print(db.header.pdpStep * pdpCount); ! s.println(" seconds -->"); ! s.print("\t\t<xff> "); ! s.print(xff); ! s.println(" </xff>"); ! s.println(); ! s.println("\t\t<cdp_prep>"); ! ! for (int i = 0; i < cdpStatusBlocks.size(); i++) { ! cdpStatusBlocks.get(i).toXml(s); ! } ! ! s.println("\t\t</cdp_prep>"); ! s.println("\t\t<database>"); ! ! long timer = -(rowCount - 1); ! int counter = 0; ! int row = currentRow; ! ! db.rrdFile.ras.seek(dataOffset + (row + 1) * 16); ! ! long lastUpdate = db.lastUpdate.getTime() / 1000; ! int pdpStep = db.header.pdpStep; ! NumberFormat numberFormat = new DecimalFormat("0.0000000000E0"); ! SimpleDateFormat dateFormat = ! new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z"); ! ! while (counter++ < rowCount) { ! row++; ! ! if (row == rowCount) { ! row = 0; ! ! db.rrdFile.ras.seek(dataOffset); ! } ! ! long now = (lastUpdate - lastUpdate % (pdpCount * pdpStep)) ! + (timer * pdpCount * pdpStep); ! ! timer++; ! ! s.print("\t\t\t<!-- "); ! s.print(dateFormat.format(new Date(now * 1000))); ! s.print(" / "); ! s.print(now); ! s.print(" --> "); ! ! for (int col = 0; col < db.header.dsCount; col++) { ! s.print("<v> "); ! ! double value = db.rrdFile.readDouble(); ! ! // NumberFormat doesn't know how to handle NaN ! if (Double.isNaN(value)) { ! s.print("NaN"); ! } ! else { ! s.print(numberFormat.format(value)); ! } ! ! s.print(" </v>"); ! } ! ! s.println("</row>"); ! } ! ! s.println("\t\t</database>"); ! s.println("\t</rra>"); ! } ! catch (IOException e) { // Is the best thing to do here? ! throw new RuntimeException(e.getMessage()); ! } ! } ! ! /* ! // THIS IS THE ORIGINAL CODE: BUGGY! Replaced by Sasa Markovic with a new method ! // Funny: the bug will appear only if dsCount != 2 :) ! public double[][] getValuesOriginal() throws IOException { ! if (values != null) { ! return values; ! } ! values = new double[db.header.dsCount][rowCount]; ! int row = currentRow; ! db.rrdFile.ras.seek(dataOffset + (row + 1) * 16); // <----- BUG (resolved below) ! for (int counter = 0; counter < rowCount; counter++) { ! row++; ! if (row == rowCount) { ! row = 0; ! db.rrdFile.ras.seek(dataOffset); ! } ! for (int col = 0; col < db.header.dsCount; col++) { ! double value = db.rrdFile.readDouble(); ! values[col][counter] = value; ! } ! } ! return values; ! } ! */ ! ! // Resolved bug from the original method (see above) ! public double[][] getValues() throws IOException { ! // OK PART ! if (values != null) { ! return values; ! } ! values = new double[db.header.dsCount][rowCount]; ! int row = currentRow; ! // HERE ARE THE DRAGONS! ! db.rrdFile.ras.seek(dataOffset + (row + 1) * db.header.dsCount * 8); ! // OK, TOO! ! for (int counter = 0; counter < rowCount; counter++) { ! row++; ! if (row == rowCount) { ! row = 0; ! db.rrdFile.ras.seek(dataOffset); ! } ! for (int col = 0; col < db.header.dsCount; col++) { ! double value = db.rrdFile.readDouble(); ! values[col][counter] = value; ! } ! } ! return values; ! } ! ! /** ! * Returns the number of primary data points required for a consolidated ! * data point in this archive. ! * ! * @return the number of primary data points required for a consolidated ! * data point in this archive. ! */ ! public int getPdpCount() { ! return pdpCount; ! } ! ! /** ! * Returns the number of entries in this archive. ! * ! * @return the number of entries in this archive. ! */ ! public int getRowCount() { ! return rowCount; ! } ! ! /** ! * Returns the X-Files Factor for this archive. ! * ! * @return the X-Files Factor for this archive. ! */ ! public double getXff() { ! return xff; ! } ! ! /** ! * Returns a summary the contents of this archive. ! * ! * @return a summary of the information contained in this archive. ! */ ! public String toString() { ! ! StringBuffer sb = new StringBuffer("[Archive: OFFSET=0x"); ! ! sb.append(Long.toHexString(offset)); ! sb.append(", SIZE=0x"); ! sb.append(Long.toHexString(size)); ! sb.append(", type="); ! sb.append(type); ! sb.append(", rowCount="); ! sb.append(rowCount); ! sb.append(", pdpCount="); ! sb.append(pdpCount); ! sb.append(", xff="); ! sb.append(xff); ! sb.append(", currentRow="); ! sb.append(currentRow); ! sb.append("]"); ! ! for (Iterator<CDPStatusBlock> i = cdpStatusBlocks.iterator(); i.hasNext();) { ! CDPStatusBlock cdp = i.next(); ! ! sb.append("\n\t\t"); ! sb.append(cdp.toString()); ! } ! ! return sb.toString(); ! } ! } Index: RRDFile.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/core/jrrd/RRDFile.java,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** RRDFile.java 22 Jul 2004 09:34:10 -0000 1.1 --- RRDFile.java 21 Dec 2006 18:02:42 -0000 1.2 *************** *** 1,169 **** ! /* ! * Copyright (C) 2001 Ciaran Treanor <ci...@co...> ! * ! * Distributable under GPL license. ! * See terms of license at gnu.org. ! * ! * $Id$ ! */ ! package org.jrobin.core.jrrd; ! ! import java.io.*; ! ! /** ! * This class is a quick hack to read information from an RRD file. Writing ! * to RRD files is not currently supported. As I said, this is a quick hack. ! * Some thought should be put into the overall design of the file IO. ! * <p/> ! * Currently this can read RRD files that were generated on Solaris (Sparc) ! * and Linux (x86). ! * ! * @author <a href="mailto:ci...@co...">Ciaran Treanor</a> ! * @version $Revision$ ! */ ! public class RRDFile implements Constants { ! ! boolean bigEndian; ! int alignment; ! RandomAccessFile ras; ! byte[] buffer; ! ! RRDFile(String name) throws IOException { ! this(new File(name)); ! } ! ! RRDFile(File file) throws IOException { ! ! ras = new RandomAccessFile(file, "r"); ! buffer = new byte[128]; ! ! initDataLayout(file); ! } ! ! private void initDataLayout(File file) throws IOException { ! ! if (file.exists()) { // Load the data formats from the file ! ras.read(buffer, 0, 24); ! ! int index; ! ! if ((index = indexOf(FLOAT_COOKIE_BIG_ENDIAN, buffer)) != -1) { ! bigEndian = true; ! } else if ((index = indexOf(FLOAT_COOKIE_LITTLE_ENDIAN, buffer)) ! != -1) { ! bigEndian = false; ! } else { ! throw new IOException("Invalid RRD file"); ! } ! ! switch (index) { ! ! case 12: ! alignment = 4; ! break; ! ! case 16: ! alignment = 8; ! break; ! ! default : ! throw new RuntimeException("Unsupported architecture"); ! } ! } else { // Default to data formats for this hardware architecture ! } ! ! ras.seek(0); // Reset file pointer to start of file ! } ! ! private int indexOf(byte[] pattern, byte[] array) { ! return (new String(array)).indexOf(new String(pattern)); ! } ! ! boolean isBigEndian() { ! return bigEndian; ! } ! ! int getAlignment() { ! return alignment; ! } ! ! double readDouble() throws IOException { ! ! //double value; ! byte[] tx = new byte[8]; ! ! ras.read(buffer, 0, 8); ! ! if (bigEndian) { ! tx = buffer; ! } else { ! for (int i = 0; i < 8; i++) { ! tx[7 - i] = buffer[i]; ! } ! } ! ! DataInputStream reverseDis = ! new DataInputStream(new ByteArrayInputStream(tx)); ! ! return reverseDis.readDouble(); ! } ! ! int readInt() throws IOException { ! return readInt(false); ! } ! ! int readInt(boolean dump) throws IOException { ! ! ras.read(buffer, 0, 4); ! ! int value; ! ! if (bigEndian) { ! value = (0xFF & buffer[3]) | ((0xFF & buffer[2]) << 8) ! | ((0xFF & buffer[1]) << 16) | ((0xFF & buffer[0]) << 24); ! } else { ! value = (0xFF & buffer[0]) | ((0xFF & buffer[1]) << 8) ! | ((0xFF & buffer[2]) << 16) | ((0xFF & buffer[3]) << 24); ! } ! ! return value; ! } ! ! String readString(int maxLength) throws IOException { ! ! ras.read(buffer, 0, maxLength); ! ! return new String(buffer, 0, maxLength).trim(); ! } ! ! void skipBytes(int n) throws IOException { ! ras.skipBytes(n); ! } ! ! int align(int boundary) throws IOException { ! ! int skip = (int) (boundary - (ras.getFilePointer() % boundary)) % boundary; ! ! if (skip != 0) { ! ras.skipBytes(skip); ! } ! ! return skip; ! } ! ! int align() throws IOException { ! return align(alignment); ! } ! ! long info() throws IOException { ! return ras.getFilePointer(); ! } ! ! long getFilePointer() throws IOException { ! return ras.getFilePointer(); ! } ! ! void close() throws IOException { ! ras.close(); ! } ! } --- 1,174 ---- ! /* ! * Copyright (C) 2001 Ciaran Treanor <ci...@co...> ! * ! * Distributable under GPL license. ! * See terms of license at gnu.org. ! * ! * $Id$ ! */ ! package org.jrobin.core.jrrd; ! ! import java.io.*; ! ! /** ! * This class is a quick hack to read information from an RRD file. Writing ! * to RRD files is not currently supported. As I said, this is a quick hack. ! * Some thought should be put into the overall design of the file IO. ! * <p/> ! * Currently this can read RRD files that were generated on Solaris (Sparc) ! * and Linux (x86). ! * ! * @author <a href="mailto:ci...@co...">Ciaran Treanor</a> ! * @version $Revision$ ! */ ! public class RRDFile implements Constants { ! ! boolean bigEndian; ! int alignment; ! RandomAccessFile ras; ! byte[] buffer; ! ! RRDFile(String name) throws IOException { ! this(new File(name)); ! } ! ! RRDFile(File file) throws IOException { ! ! ras = new RandomAccessFile(file, "r"); ! buffer = new byte[128]; ! ! initDataLayout(file); ! } ! ! private void initDataLayout(File file) throws IOException { ! ! if (file.exists()) { // Load the data formats from the file ! ras.read(buffer, 0, 24); ! ! int index; ! ! if ((index = indexOf(FLOAT_COOKIE_BIG_ENDIAN, buffer)) != -1) { ! bigEndian = true; ! } ! else if ((index = indexOf(FLOAT_COOKIE_LITTLE_ENDIAN, buffer)) ! != -1) { ! bigEndian = false; ! } ! else { ! throw new IOException("Invalid RRD file"); ! } ! ! switch (index) { ! ! case 12: ! alignment = 4; ! break; ! ! case 16: ! alignment = 8; ! break; ! ! default : ! throw new RuntimeException("Unsupported architecture"); ! } ! } ! else { // Default to data formats for this hardware architecture ! } ! ! ras.seek(0); // Reset file pointer to start of file ! } ! ! private int indexOf(byte[] pattern, byte[] array) { ! return (new String(array)).indexOf(new String(pattern)); ! } ! ! boolean isBigEndian() { ! return bigEndian; ! } ! ! int getAlignment() { ! return alignment; ! } ! ! double readDouble() throws IOException { ! ! //double value; ! byte[] tx = new byte[8]; ! ! ras.read(buffer, 0, 8); ! ! if (bigEndian) { ! tx = buffer; ! } ! else { ! for (int i = 0; i < 8; i++) { ! tx[7 - i] = buffer[i]; ! } ! } ! ! DataInputStream reverseDis = ! new DataInputStream(new ByteArrayInputStream(tx)); ! ! return reverseDis.readDouble(); ! } ! ! int readInt() throws IOException { ! return readInt(false); ! } ! ! int readInt(boolean dump) throws IOException { ! ! ras.read(buffer, 0, 4); ! ! int value; ! ! if (bigEndian) { ! value = (0xFF & buffer[3]) | ((0xFF & buffer[2]) << 8) ! | ((0xFF & buffer[1]) << 16) | ((0xFF & buffer[0]) << 24); ! } ! else { ! value = (0xFF & buffer[0]) | ((0xFF & buffer[1]) << 8) ! | ((0xFF & buffer[2]) << 16) | ((0xFF & buffer[3]) << 24); ! } ! ! return value; ! } ! ! String readString(int maxLength) throws IOException { ! ! ras.read(buffer, 0, maxLength); ! ! return new String(buffer, 0, maxLength).trim(); ! } ! ! void skipBytes(int n) throws IOException { ! ras.skipBytes(n); ! } ! ! int align(int boundary) throws IOException { ! ! int skip = (int) (boundary - (ras.getFilePointer() % boundary)) % boundary; ! ! if (skip != 0) { ! ras.skipBytes(skip); ! } ! ! return skip; ! } ! ! int align() throws IOException { ! return align(alignment); ! } ! ! long info() throws IOException { ! return ras.getFilePointer(); ! } ! ! long getFilePointer() throws IOException { ! return ras.getFilePointer(); ! } ! ! void close() throws IOException { ! ras.close(); ! } ! } Index: Constants.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/core/jrrd/Constants.java,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** Constants.java 22 Jul 2004 09:34:10 -0000 1.1 --- Constants.java 21 Dec 2006 18:02:42 -0000 1.2 *************** *** 1,26 **** ! /* ! * Copyright (C) 2001 Ciaran Treanor <ci...@co...> ! * ! * Distributable under GPL license. ! * See terms of license at gnu.org. ! * ! * $Id$ ! */ ! package org.jrobin.core.jrrd; ! ! interface Constants { ! ! int DS_NAM_SIZE = 20; ! int DST_SIZE = 20; ! int CF_NAM_SIZE = 20; ! int LAST_DS_LEN = 30; ! static String COOKIE = "RRD"; ! static String VERSION = "0001"; ! double FLOAT_COOKIE = 8.642135E130; ! static byte[] FLOAT_COOKIE_BIG_ENDIAN = {0x5B, 0x1F, 0x2B, 0x43, ! (byte) 0xC7, (byte) 0xC0, 0x25, ! 0x2F}; ! static byte[] FLOAT_COOKIE_LITTLE_ENDIAN = {0x2F, 0x25, (byte) 0xC0, ! (byte) 0xC7, 0x43, 0x2B, 0x1F, ! 0x5B}; ! } --- 1,26 ---- ! /* ! * Copyright (C) 2001 Ciaran Treanor <ci...@co...> ! * ! * Distributable under GPL license. ! * See terms of license at gnu.org. ! * ! * $Id$ ! */ ! package org.jrobin.core.jrrd; ! ! interface Constants { ! ! int DS_NAM_SIZE = 20; ! int DST_SIZE = 20; ! int CF_NAM_SIZE = 20; ! int LAST_DS_LEN = 30; ! static String COOKIE = "RRD"; ! static String VERSION = "0001"; ! double FLOAT_COOKIE = 8.642135E130; ! static byte[] FLOAT_COOKIE_BIG_ENDIAN = {0x5B, 0x1F, 0x2B, 0x43, ! (byte) 0xC7, (byte) 0xC0, 0x25, ! 0x2F}; ! static byte[] FLOAT_COOKIE_LITTLE_ENDIAN = {0x2F, 0x25, (byte) 0xC0, ! (byte) 0xC7, 0x43, 0x2B, 0x1F, ! 0x5B}; ! } Index: CDPStatusBlock.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/core/jrrd/CDPStatusBlock.java,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** CDPStatusBlock.java 22 Jul 2004 09:34:10 -0000 1.1 --- CDPStatusBlock.java 21 Dec 2006 18:02:42 -0000 1.2 *************** *** 1,86 **** ! /* ! * Copyright (C) 2001 Ciaran Treanor <ci...@co...> ! * ! * Distributable under GPL license. ! * See terms of license at gnu.org. ! * ! * $Id$ ! */ ! package org.jrobin.core.jrrd; ! ! import java.io.IOException; ! import java.io.PrintStream; ! ! /** ! * Instances of this class model the consolidation data point status from an RRD file. ! * ! * @author <a href="mailto:ci...@co...">Ciaran Treanor</a> ! * @version $Revision$ ! */ ! public class CDPStatusBlock { ! ! long offset; ! long size; ! int unknownDatapoints; ! double value; ! ! CDPStatusBlock(RRDFile file) throws IOException { ! ! offset = file.getFilePointer(); ! value = file.readDouble(); ! unknownDatapoints = file.readInt(); ! ! // Skip rest of cdp_prep_t.scratch ! file.skipBytes(68); ! ! size = file.getFilePointer() - offset; ! } ! ! /** ! * Returns the number of unknown primary data points that were integrated. ! * ! * @return the number of unknown primary data points that were integrated. ! */ ! public int getUnknownDatapoints() { ! return unknownDatapoints; ! } ! ! /** ! * Returns the value of this consolidated data point. ! * ! * @return the value of this consolidated data point. ! */ ! public double getValue() { ! return value; ! } ! ! void toXml(PrintStream s) { ! ! s.print("\t\t\t<ds><value> "); ! s.print(value); ! s.print(" </value> <unknown_datapoints> "); ! s.print(unknownDatapoints); ! s.println(" </unknown_datapoints></ds>"); ! } ! ! /** ! * Returns a summary the contents of this CDP status block. ! * ! * @return a summary of the information contained in the CDP status block. ! */ ! public String toString() { ! ! StringBuffer sb = new StringBuffer("[CDPStatusBlock: OFFSET=0x"); ! ! sb.append(Long.toHexString(offset)); ! sb.append(", SIZE=0x"); ! sb.append(Long.toHexString(size)); ! sb.append(", unknownDatapoints="); ! sb.append(unknownDatapoints); ! sb.append(", value="); ! sb.append(value); ! sb.append("]"); ! ! return sb.toString(); ! } ! } --- 1,86 ---- ! /* ! * Copyright (C) 2001 Ciaran Treanor <ci...@co...> ! * ! * Distributable under GPL license. ! * See terms of license at gnu.org. ! * ! * $Id$ ! */ ! package org.jrobin.core.jrrd; ! ! import java.io.IOException; ! import java.io.PrintStream; ! ! /** ! * Instances of this class model the consolidation data point status from an RRD file. ! * ! * @author <a href="mailto:ci...@co...">Ciaran Treanor</a> ! * @version $Revision$ ! */ ! public class CDPStatusBlock { ! ! long offset; ! long size; ! int unknownDatapoints; ! double value; ! ! CDPStatusBlock(RRDFile file) throws IOException { ! ! offset = file.getFilePointer(); ! value = file.readDouble(); ! unknownDatapoints = file.readInt(); ! ! // Skip rest of cdp_prep_t.scratch ! file.skipBytes(68); ! ! size = file.getFilePointer() - offset; ! } ! ! /** ! * Returns the number of unknown primary data points that were integrated. ! * ! * @return the number of unknown primary data points that were integrated. ! */ ! public int getUnknownDatapoints() { ! return unknownDatapoints; ! } ! ! /** ! * Returns the value of this consolidated data point. ! * ! * @return the value of this consolidated data point. ! */ ! public double getValue() { ! return value; ! } ! ! void toXml(PrintStream s) { ! ! s.print("\t\t\t<ds><value> "); ! s.print(value); ! s.print(" </value> <unknown_datapoints> "); ! s.print(unknownDatapoints); ! s.println(" </unknown_datapoints></ds>"); ! } ! ! /** ! * Returns a summary the contents of this CDP status block. ! * ! * @return a summary of the information contained in the CDP status block. ! */ ! public String toString() { ! ! StringBuffer sb = new StringBuffer("[CDPStatusBlock: OFFSET=0x"); ! ! sb.append(Long.toHexString(offset)); ! sb.append(", SIZE=0x"); ! sb.append(Long.toHexString(size)); ! sb.append(", unknownDatapoints="); ! sb.append(unknownDatapoints); ! sb.append(", value="); ! sb.append(value); ! sb.append("]"); ! ! return sb.toString(); ! } ! } Index: RRDatabase.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/core/jrrd/RRDatabase.java,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** RRDatabase.java 22 Jul 2004 09:36:33 -0000 1.2 --- RRDatabase.java 21 Dec 2006 18:02:42 -0000 1.3 *************** *** 1,484 **** ! /* ! * Copyright (C) 2001 Ciaran Treanor <ci...@co...> ! * ! * Distributable under GPL license. ! * See terms of license at gnu.org. ! * ! * $Id$ ! */ ! package org.jrobin.core.jrrd; ! ! import java.io.*; ! import java.util.*; ! import java.text.NumberFormat; ! import java.text.DecimalFormat; ! ! /** ! * Instances of this class model ! * <a href="http://people.ee.ethz.ch/~oetiker/webtools/rrdtool/">Round Robin Database</a> ! * (RRD) files. ! * ! * @author <a href="mailto:ci...@co...">Ciaran Treanor</a> ! * @version $Revision$ ! */ ! public class RRDatabase { ! ! RRDFile rrdFile; ! ! // RRD file name ! private String name; ! Header header; ! ArrayList dataSources; ! ArrayList archives; ! Date lastUpdate; ! ! /** ! * Creates a database to read from. ! * ! * @param name the filename of the file to read from. ! * @throws IOException if an I/O error occurs. ! */ ! public RRDatabase(String name) throws IOException { ! this(new File(name)); ! } ! ! /** ! * Creates a database to read from. ! * ! * @param file the file to read from. ! * @throws IOException if an I/O error occurs. ! */ ! public RRDatabase(File file) throws IOException { ! ! name = file.getName(); ! rrdFile = new RRDFile(file); ! header = new Header(rrdFile); ! ! // Load the data sources ! dataSources = new ArrayList(); ! ! for (int i = 0; i < header.dsCount; i++) { ! DataSource ds = new DataSource(rrdFile); ! ! dataSources.add(ds); ! } ! ! // Load the archives ! archives = new ArrayList(); ! ! for (int i = 0; i < header.rraCount; i++) { ! Archive archive = new Archive(this); ! ! archives.add(archive); ! } ! ! rrdFile.align(); ! ! lastUpdate = new Date((long) (rrdFile.readInt()) * 1000); ! ! // Load PDPStatus(s) ! for (int i = 0; i < header.dsCount; i++) { ! DataSource ds = (DataSource) dataSources.get(i); ! ! ds.loadPDPStatusBlock(rrdFile); ! } ! ! // Load CDPStatus(s) ! for (int i = 0; i < header.rraCount; i++) { ! Archive archive = (Archive) archives.get(i); ! ! archive.loadCDPStatusBlocks(rrdFile, header.dsCount); ! } ! ! // Load current row information for each archive ! for (int i = 0; i < header.rraCount; i++) { ! Archive archive = (Archive) archives.get(i); ! ! archive.loadCurrentRow(rrdFile); ! } ! ! // Now load the data ! for (int i = 0; i < header.rraCount; i++) { ! Archive archive = (Archive) archives.get(i); ! ! archive.loadData(rrdFile, header.dsCount); ! } ! } ! ! /** ! * Returns the <code>Header</code> for this database. ! * ! * @return the <code>Header</code> for this database. ! */ ! public Header getHeader() { ! return header; ! } ! ! /** ! * Returns the date this database was last updated. To convert this date to ! * the form returned by <code>rrdtool last</code> call Date.getTime() and ! * divide the result by 1000. ! * ! * @return the date this database was last updated. ! */ ! public Date getLastUpdate() { ! return lastUpdate; ! } ! ! /** ! * Returns the <code>DataSource</code> at the specified position in this database. ! * ! * @param index index of <code>DataSource</code> to return. ! * @return the <code>DataSource</code> at the specified position in this database ! */ ! public DataSource getDataSource(int index) { ! return (DataSource) dataSources.get(index); ! } ! ! /** ! * Returns an iterator over the data sources in this database in proper sequence. ! * ! * @return an iterator over the data sources in this database in proper sequence. ! */ ! public Iterator getDataSources() { ! return dataSources.iterator(); ! } ! ! /** ! * Returns the <code>Archive</code> at the specified position in this database. ! * ! * @param index index of <code>Archive</code> to return. ! * @return the <code>Archive</code> at the specified position in this database. ! */ ! public Archive getArchi... [truncated message content] |
From: Tarus B. <ta...@us...> - 2006-12-21 18:03:16
|
Update of /cvsroot/jrobin/src/org/jrobin/core/timespec In directory sc8-pr-cvs6.sourceforge.net:/tmp/cvs-serv9082/org/jrobin/core/timespec Modified Files: Epoch.java TimeParser.java TimeScanner.java TimeSpec.java TimeToken.java Log Message: Adding the new 1.5.4 code Index: TimeSpec.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/core/timespec/TimeSpec.java,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** TimeSpec.java 17 Feb 2005 10:43:13 -0000 1.1 --- TimeSpec.java 21 Dec 2006 18:02:42 -0000 1.2 *************** *** 1,164 **** ! /* ============================================================ ! * JRobin : Pure java implementation of RRDTool's functionality ! * ============================================================ ! * ! * Project Info: http://www.jrobin.org ! * Project Lead: Sasa Markovic (sa...@jr...); ! * ! * (C) Copyright 2003, by Sasa Markovic. ! * ! * Developers: Sasa Markovic (sa...@jr...) ! * Arne Vandamme (cob...@jr...) ! * ! * This library is free software; you can redistribute it and/or modify it under the terms ! * of the GNU Lesser General Public License as published by the Free Software Foundation; ! * either version 2.1 of the License, or (at your option) any later version. ! * ! * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; ! * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. ! * See the GNU Lesser General Public License for more details. ! * ! * You should have received a copy of the GNU Lesser General Public License along with this ! * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, ! * Boston, MA 02111-1307, USA. ! */ ! ! package org.jrobin.core.timespec; ! ! import org.jrobin.core.RrdException; ! import org.jrobin.core.Util; ! ! import java.util.GregorianCalendar; ! import java.util.Date; ! import java.util.Calendar; ! ! /** ! * Simple class to represent time obtained by parsing at-style date specification (described ! * in detail on the rrdfetch man page. See javadoc {@link org.jrobin.core.timespec.TimeParser} for more information. ! */ ! public class TimeSpec { ! static final int TYPE_ABSOLUTE = 0; ! static final int TYPE_START = 1; ! static final int TYPE_END = 2; ! ! int type = TYPE_ABSOLUTE; ! int year, month, day, hour, min, sec; ! int wday; ! int dyear, dmonth, dday, dhour, dmin, dsec; ! ! String dateString; ! ! TimeSpec context; ! ! TimeSpec(String dateString) { ! this.dateString = dateString; ! } ! ! void localtime(long timestamp) { ! GregorianCalendar date = new GregorianCalendar(); ! date.setTime(new Date(timestamp * 1000L)); ! year = date.get(Calendar.YEAR) - 1900; ! month = date.get(Calendar.MONTH); ! day = date.get(Calendar.DAY_OF_MONTH); ! hour = date.get(Calendar.HOUR_OF_DAY); ! min = date.get(Calendar.MINUTE); ! sec = date.get(Calendar.SECOND); ! wday = date.get(Calendar.DAY_OF_WEEK) - Calendar.SUNDAY; ! } ! ! GregorianCalendar getTime() throws RrdException { ! GregorianCalendar gc; ! // absoulte time, this is easy ! if(type == TYPE_ABSOLUTE) { ! gc = new GregorianCalendar(year + 1900, month, day, hour, min, sec); ! } ! // relative time, we need a context to evaluate it ! else if(context != null && context.type == TYPE_ABSOLUTE) { ! gc = context.getTime(); ! } ! // how would I guess what time it was? ! else { ! throw new RrdException("Relative times like '" + ! dateString + "' require proper absolute context to be evaluated"); ! } ! gc.add(Calendar.YEAR, dyear); ! gc.add(Calendar.MONTH, dmonth); ! gc.add(Calendar.DAY_OF_MONTH, dday); ! gc.add(Calendar.HOUR_OF_DAY, dhour); ! gc.add(Calendar.MINUTE, dmin); ! gc.add(Calendar.SECOND, dsec); ! return gc; ! } ! ! /** ! * Returns the corresponding timestamp (seconds since Epoch). Example:<p> ! * <pre> ! * TimeParser p = new TimeParser("now-1day"); ! * TimeSpec ts = p.parse(); ! * System.out.println("Timestamp was: " + ts.getTimestamp(); ! * </pre> ! * @return Timestamp (in seconds, no milliseconds) ! * @throws RrdException Thrown if this TimeSpec object does not represent absolute time. ! */ ! public long getTimestamp() throws RrdException { ! return Util.getTimestamp(getTime()); ! } ! ! String dump() { ! return (type == TYPE_ABSOLUTE? "ABSTIME": type == TYPE_START? "START": "END") + ! ": " + year + "/" + month + "/" + day + ! "/" + hour + "/" + min + "/" + sec + " (" + ! dyear + "/" + dmonth + "/" + dday + ! "/" + dhour + "/" + dmin + "/" + dsec + ")"; ! } ! ! /** ! * Use this static method to resolve relative time references and obtain the corresponding ! * GregorianCalendar objects. Example:<p> ! * <pre> ! * TimeParser pStart = new TimeParser("now-1month"); // starting time ! * TimeParser pEnd = new TimeParser("start+1week"); // ending time ! * TimeSpec specStart = pStart.parse(); ! * TimeSpec specEnd = pEnd.parse(); ! * GregorianCalendar[] gc = TimeSpec.getTimes(specStart, specEnd); ! * </pre> ! * @param spec1 Starting time specification ! * @param spec2 Ending time specification ! * @return ! * @throws RrdException Thrown if relative time references cannot be resolved ! */ ! public static GregorianCalendar[] getTimes(TimeSpec spec1, TimeSpec spec2) throws RrdException { ! if(spec1.type == TYPE_START || spec2.type == TYPE_END) { ! throw new RrdException("Recursive time specifications not allowed"); ! } ! spec1.context = spec2; ! spec2.context = spec1; ! return new GregorianCalendar[] { ! spec1.getTime(), ! spec2.getTime() ! }; ! } ! ! /** ! * Use this static method to resolve relative time references and obtain the corresponding ! * timestamps (seconds since epoch). Example:<p> ! * <pre> ! * TimeParser pStart = new TimeParser("now-1month"); // starting time ! * TimeParser pEnd = new TimeParser("start+1week"); // ending time ! * TimeSpec specStart = pStart.parse(); ! * TimeSpec specEnd = pEnd.parse(); ! * long[] ts = TimeSpec.getTimestamps(specStart, specEnd); ! * </pre> ! * @param spec1 Starting time specification ! * @param spec2 Ending time specification ! * @return ! * @throws RrdException Thrown if relative time references cannot be resolved ! */ ! public static long[] getTimestamps(TimeSpec spec1, TimeSpec spec2) throws RrdException { ! GregorianCalendar[] gcs = getTimes(spec1, spec2); ! return new long[] { ! Util.getTimestamp(gcs[0]), Util.getTimestamp(gcs[1]) ! }; ! } ! } ! --- 1,168 ---- ! /* ============================================================ ! * JRobin : Pure java implementation of RRDTool's functionality ! * ============================================================ ! * ! * Project Info: http://www.jrobin.org ! * Project Lead: Sasa Markovic (sa...@jr...); ! * ! * (C) Copyright 2003-2005, by Sasa Markovic. ! * ! * Developers: Sasa Markovic (sa...@jr...) ! * ! * ! * This library is free software; you can redistribute it and/or modify it under the terms ! * of the GNU Lesser General Public License as published by the Free Software Foundation; ! * either version 2.1 of the License, or (at your option) any later version. ! * ! * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; ! * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. ! * See the GNU Lesser General Public License for more details. ! * ! * You should have received a copy of the GNU Lesser General Public License along with this ! * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, ! * Boston, MA 02111-1307, USA. ! */ ! ! package org.jrobin.core.timespec; ! ! import org.jrobin.core.RrdException; ! import org.jrobin.core.Util; ! ! import java.util.Calendar; ! import java.util.Date; ! import java.util.GregorianCalendar; ! ! /** ! * Simple class to represent time obtained by parsing at-style date specification (described ! * in detail on the rrdfetch man page. See javadoc for {@link org.jrobin.core.timespec.TimeParser} ! * for more information. ! */ ! public class TimeSpec { ! static final int TYPE_ABSOLUTE = 0; ! static final int TYPE_START = 1; ! static final int TYPE_END = 2; ! ! int type = TYPE_ABSOLUTE; ! int year, month, day, hour, min, sec; ! int wday; ! int dyear, dmonth, dday, dhour, dmin, dsec; ! ! String dateString; ! ! TimeSpec context; ! ! TimeSpec(String dateString) { ! this.dateString = dateString; ! } ! ! void localtime(long timestamp) { ! GregorianCalendar date = new GregorianCalendar(); ! date.setTime(new Date(timestamp * 1000L)); ! year = date.get(Calendar.YEAR) - 1900; ! month = date.get(Calendar.MONTH); ! day = date.get(Calendar.DAY_OF_MONTH); ! hour = date.get(Calendar.HOUR_OF_DAY); ! min = date.get(Calendar.MINUTE); ! sec = date.get(Calendar.SECOND); ! wday = date.get(Calendar.DAY_OF_WEEK) - Calendar.SUNDAY; ! } ! ! GregorianCalendar getTime() throws RrdException { ! GregorianCalendar gc; ! // absoulte time, this is easy ! if (type == TYPE_ABSOLUTE) { ! gc = new GregorianCalendar(year + 1900, month, day, hour, min, sec); ! } ! // relative time, we need a context to evaluate it ! else if (context != null && context.type == TYPE_ABSOLUTE) { ! gc = context.getTime(); ! } ! // how would I guess what time it was? ! else { ! throw new RrdException("Relative times like '" + ! dateString + "' require proper absolute context to be evaluated"); ! } ! gc.add(Calendar.YEAR, dyear); ! gc.add(Calendar.MONTH, dmonth); ! gc.add(Calendar.DAY_OF_MONTH, dday); ! gc.add(Calendar.HOUR_OF_DAY, dhour); ! gc.add(Calendar.MINUTE, dmin); ! gc.add(Calendar.SECOND, dsec); ! return gc; ! } ! ! /** ! * Returns the corresponding timestamp (seconds since Epoch). Example:<p> ! * <pre> ! * TimeParser p = new TimeParser("now-1day"); ! * TimeSpec ts = p.parse(); ! * System.out.println("Timestamp was: " + ts.getTimestamp(); ! * </pre> ! * ! * @return Timestamp (in seconds, no milliseconds) ! * @throws RrdException Thrown if this TimeSpec object does not represent absolute time. ! */ ! public long getTimestamp() throws RrdException { ! return Util.getTimestamp(getTime()); ! } ! ! String dump() { ! return (type == TYPE_ABSOLUTE ? "ABSTIME" : type == TYPE_START ? "START" : "END") + ! ": " + year + "/" + month + "/" + day + ! "/" + hour + "/" + min + "/" + sec + " (" + ! dyear + "/" + dmonth + "/" + dday + ! "/" + dhour + "/" + dmin + "/" + dsec + ")"; ! } ! ! /** ! * Use this static method to resolve relative time references and obtain the corresponding ! * Calendar objects. Example:<p> ! * <pre> ! * TimeParser pStart = new TimeParser("now-1month"); // starting time ! * TimeParser pEnd = new TimeParser("start+1week"); // ending time ! * TimeSpec specStart = pStart.parse(); ! * TimeSpec specEnd = pEnd.parse(); ! * GregorianCalendar[] gc = TimeSpec.getTimes(specStart, specEnd); ! * </pre> ! * ! * @param spec1 Starting time specification ! * @param spec2 Ending time specification ! * @return Two element array containing Calendar objects ! * @throws RrdException Thrown if relative time references cannot be resolved ! */ ! public static Calendar[] getTimes(TimeSpec spec1, TimeSpec spec2) throws RrdException { ! if (spec1.type == TYPE_START || spec2.type == TYPE_END) { ! throw new RrdException("Recursive time specifications not allowed"); ! } ! spec1.context = spec2; ! spec2.context = spec1; ! return new Calendar[] { ! spec1.getTime(), ! spec2.getTime() ! }; ! } ! ! /** ! * Use this static method to resolve relative time references and obtain the corresponding ! * timestamps (seconds since epoch). Example:<p> ! * <pre> ! * TimeParser pStart = new TimeParser("now-1month"); // starting time ! * TimeParser pEnd = new TimeParser("start+1week"); // ending time ! * TimeSpec specStart = pStart.parse(); ! * TimeSpec specEnd = pEnd.parse(); ! * long[] ts = TimeSpec.getTimestamps(specStart, specEnd); ! * </pre> ! * ! * @param spec1 Starting time specification ! * @param spec2 Ending time specification ! * @return array containing two timestamps (in seconds since epoch) ! * @throws RrdException Thrown if relative time references cannot be resolved ! */ ! public static long[] getTimestamps(TimeSpec spec1, TimeSpec spec2) throws RrdException { ! Calendar[] gcs = getTimes(spec1, spec2); ! return new long[] { ! Util.getTimestamp(gcs[0]), Util.getTimestamp(gcs[1]) ! }; ! } ! } ! Index: TimeParser.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/core/timespec/TimeParser.java,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** TimeParser.java 17 Feb 2005 10:43:13 -0000 1.1 --- TimeParser.java 21 Dec 2006 18:02:42 -0000 1.2 *************** *** 1,432 **** ! /* ============================================================ ! * JRobin : Pure java implementation of RRDTool's functionality ! * ============================================================ ! * ! * Project Info: http://www.jrobin.org ! * Project Lead: Sasa Markovic (sa...@jr...); ! * ! * (C) Copyright 2003, by Sasa Markovic. ! * ! * Developers: Sasa Markovic (sa...@jr...) ! * Arne Vandamme (cob...@jr...) ! * ! * This library is free software; you can redistribute it and/or modify it under the terms ! * of the GNU Lesser General Public License as published by the Free Software Foundation; ! * either version 2.1 of the License, or (at your option) any later version. ! * ! * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; ! * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. ! * See the GNU Lesser General Public License for more details. ! * ! * You should have received a copy of the GNU Lesser General Public License along with this ! * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, ! * Boston, MA 02111-1307, USA. ! */ ! ! /* ! * Java port of Tobi's original parsetime.c routine ! */ ! package org.jrobin.core.timespec; ! ! import org.jrobin.core.RrdException; ! import org.jrobin.core.Util; ! ! /** ! * Class which parses at-style time specification (describided in detail on the rrdfetch man page), ! * used in all RRDTool commands. This code is in most parts just a java port of Tobi's parsetime.c ! * code. ! */ ! public class TimeParser { ! private static final int PREVIOUS_OP = -1; ! ! TimeToken token; ! TimeScanner scanner; ! TimeSpec spec; ! ! int op = TimeToken.PLUS; ! int prev_multiplier = -1; ! ! /** ! * Constructs TimeParser instance from the given input string. ! * @param dateString at-style time specification (read rrdfetch man page ! * for the complete explanation) ! */ ! public TimeParser(String dateString) { ! scanner = new TimeScanner(dateString); ! spec = new TimeSpec(dateString); ! } ! ! private void expectToken(int desired, String errorMessage) throws RrdException { ! token = scanner.nextToken(); ! if (token.id != desired) { ! throw new RrdException(errorMessage); ! } ! } ! ! private void plusMinus(int doop) throws RrdException { ! if (doop >= 0) { ! op = doop; ! expectToken(TimeToken.NUMBER, "There should be number after " + ! (op == TimeToken.PLUS ? '+' : '-')); ! prev_multiplier = -1; /* reset months-minutes guessing mechanics */ ! } ! int delta = Integer.parseInt(token.value); ! token = scanner.nextToken(); ! if (token.id == TimeToken.MONTHS_MINUTES) { ! /* hard job to guess what does that -5m means: -5mon or -5min? */ ! switch (prev_multiplier) { ! case TimeToken.DAYS: ! case TimeToken.WEEKS: ! case TimeToken.MONTHS: ! case TimeToken.YEARS: ! token = scanner.resolveMonthsMinutes(TimeToken.MONTHS); ! break; ! case TimeToken.SECONDS: ! case TimeToken.MINUTES: ! case TimeToken.HOURS: ! token = scanner.resolveMonthsMinutes(TimeToken.MINUTES); ! break; ! default: ! if (delta < 6) { ! token = scanner.resolveMonthsMinutes(TimeToken.MONTHS); ! } else { ! token = scanner.resolveMonthsMinutes(TimeToken.MINUTES); ! } ! } ! } ! prev_multiplier = token.id; ! delta *= (op == TimeToken.PLUS) ? +1 : -1; ! switch (token.id) { ! case TimeToken.YEARS: ! spec.dyear += delta; ! return; ! case TimeToken.MONTHS: ! spec.dmonth += delta; ! return; ! case TimeToken.WEEKS: ! delta *= 7; ! /* FALLTHRU */ ! case TimeToken.DAYS: ! spec.dday += delta; ! return; ! case TimeToken.HOURS: ! spec.dhour += delta; ! return; ! case TimeToken.MINUTES: ! spec.dmin += delta; ! return; ! case TimeToken.SECONDS: ! default: // default is 'seconds' ! spec.dsec += delta; ! return; ! } ! // unreachable statement ! // throw new RrdException("Well-known time unit expected after " + delta); ! } ! ! private void timeOfDay() throws RrdException { ! int hour, minute = 0; ! /* save token status in case we must abort */ ! scanner.saveState(); ! /* first pick out the time of day - we assume a HH (COLON|DOT) MM time */ ! if (token.value.length() > 2) { ! return; ! } ! hour = Integer.parseInt(token.value); ! token = scanner.nextToken(); ! if (token.id == TimeToken.SLASH || token.id == TimeToken.DOT) { ! /* guess we are looking at a date */ ! token = scanner.restoreState(); ! return; ! } ! if (token.id == TimeToken.COLON) { ! expectToken(TimeToken.NUMBER, "Parsing HH:MM syntax, expecting MM as number, got none"); ! minute = Integer.parseInt(token.value); ! if (minute > 59) { ! throw new RrdException("Parsing HH:MM syntax, got MM = " + ! minute + " (>59!)"); ! } ! token = scanner.nextToken(); ! } ! /* check if an AM or PM specifier was given */ ! if (token.id == TimeToken.AM || token.id == TimeToken.PM) { ! if (hour > 12) { ! throw new RrdException("There cannot be more than 12 AM or PM hours"); ! } ! if (token.id == TimeToken.PM) { ! if (hour != 12) { ! /* 12:xx PM is 12:xx, not 24:xx */ ! hour += 12; ! } ! } else { ! if (hour == 12) { ! /* 12:xx AM is 00:xx, not 12:xx */ ! hour = 0; ! } ! } ! token = scanner.nextToken(); ! } else if (hour > 23) { ! /* guess it was not a time then ... */ ! token = scanner.restoreState(); ! return; ! } ! spec.hour = hour; ! spec.min = minute; ! spec.sec = 0; ! if (spec.hour == 24) { ! spec.hour = 0; ! spec.day++; ! } ! } ! ! private void assignDate(long mday, long mon, long year) throws RrdException { ! if (year > 138) { ! if (year > 1970) { ! year -= 1900; ! } else { ! throw new RrdException("Invalid year " + year + ! " (should be either 00-99 or >1900)"); ! } ! } else if (year >= 0 && year < 38) { ! year += 100; /* Allow year 2000-2037 to be specified as */ ! } /* 00-37 until the problem of 2038 year will */ ! /* arise for unices with 32-bit time_t */ ! if (year < 70) { ! throw new RrdException("Won't handle dates before epoch (01/01/1970), sorry"); ! } ! spec.year = (int) year; ! spec.month = (int) mon; ! spec.day = (int) mday; ! } ! ! private void day() throws RrdException { ! long mday = 0, wday, mon, year = spec.year; ! switch (token.id) { ! case TimeToken.YESTERDAY: ! spec.day--; ! /* FALLTRHU */ ! case TimeToken.TODAY: /* force ourselves to stay in today - no further processing */ ! token = scanner.nextToken(); ! break; ! case TimeToken.TOMORROW: ! spec.day++; ! token = scanner.nextToken(); ! break; ! case TimeToken.JAN: ! case TimeToken.FEB: ! case TimeToken.MAR: ! case TimeToken.APR: ! case TimeToken.MAY: ! case TimeToken.JUN: ! case TimeToken.JUL: ! case TimeToken.AUG: ! case TimeToken.SEP: ! case TimeToken.OCT: ! case TimeToken.NOV: ! case TimeToken.DEC: ! /* do month mday [year] */ ! mon = (token.id - TimeToken.JAN); ! expectToken(TimeToken.NUMBER, "the day of the month should follow month name"); ! mday = Long.parseLong(token.value); ! token = scanner.nextToken(); ! if (token.id == TimeToken.NUMBER) { ! year = Long.parseLong(token.value); ! token = scanner.nextToken(); ! } else { ! year = spec.year; ! } ! assignDate(mday, mon, year); ! break; ! case TimeToken.SUN: ! case TimeToken.MON: ! case TimeToken.TUE: ! case TimeToken.WED: ! case TimeToken.THU: ! case TimeToken.FRI: ! case TimeToken.SAT: ! /* do a particular day of the week */ ! wday = (token.id - TimeToken.SUN); ! spec.day += (wday - spec.wday); ! token = scanner.nextToken(); ! break; ! case TimeToken.NUMBER: ! /* get numeric <sec since 1970>, MM/DD/[YY]YY, or DD.MM.[YY]YY */ ! // int tlen = token.value.length(); ! mon = Long.parseLong(token.value); ! if (mon > 10L * 365L * 24L * 60L * 60L) { ! spec.localtime(mon); ! token = scanner.nextToken(); ! break; ! } ! if (mon > 19700101 && mon < 24000101) { /*works between 1900 and 2400 */ ! year = mon / 10000; ! mday = mon % 100; ! mon = (mon / 100) % 100; ! token = scanner.nextToken(); ! } else { ! token = scanner.nextToken(); ! if (mon <= 31 && (token.id == TimeToken.SLASH || token.id == TimeToken.DOT)) { ! int sep = token.id; ! expectToken(TimeToken.NUMBER, "there should be " + ! (sep == TimeToken.DOT ? "month" : "day") + ! " number after " + ! (sep == TimeToken.DOT ? '.' : '/')); ! mday = Long.parseLong(token.value); ! token = scanner.nextToken(); ! if (token.id == sep) { ! expectToken(TimeToken.NUMBER, "there should be year number after " + ! (sep == TimeToken.DOT ? '.' : '/')); ! year = Long.parseLong(token.value); ! token = scanner.nextToken(); ! } ! /* flip months and days for European timing */ ! if (sep == TimeToken.DOT) { ! long x = mday; ! mday = mon; ! mon = x; ! } ! } ! } ! mon--; ! if (mon < 0 || mon > 11) { ! throw new RrdException("Did you really mean month " + (mon + 1)); ! } ! if (mday < 1 || mday > 31) { ! throw new RrdException("I'm afraid that " + mday + ! " is not a valid day of the month"); ! } ! assignDate(mday, mon, year); ! break; ! } ! } ! ! /** ! * Parses the input string specified in the constructor. ! * @return Object representing parsed date/time. ! * @throws RrdException Thrown if the date string cannot be parsed. ! */ ! public TimeSpec parse() throws RrdException { ! long now = Util.getTime(); ! int hr = 0; ! /* this MUST be initialized to zero for midnight/noon/teatime */ ! /* establish the default time reference */ ! spec.localtime(now); ! token = scanner.nextToken(); ! switch (token.id) { ! case TimeToken.PLUS: ! case TimeToken.MINUS: ! break; /* jump to OFFSET-SPEC part */ ! case TimeToken.START: ! spec.type = TimeSpec.TYPE_START; ! /* FALLTHRU */ ! case TimeToken.END: ! if (spec.type != TimeSpec.TYPE_START) { ! spec.type = TimeSpec.TYPE_END; ! } ! spec.year = spec.month = spec.day = spec.hour = spec.min = spec.sec = 0; ! /* FALLTHRU */ ! case TimeToken.NOW: ! int time_reference = token.id; ! token = scanner.nextToken(); ! if (token.id == TimeToken.PLUS || token.id == TimeToken.MINUS) { ! break; ! } ! if (time_reference != TimeToken.NOW) { ! throw new RrdException("Words 'start' or 'end' MUST be followed by +|- offset"); ! } else if (token.id != TimeToken.EOF) { ! throw new RrdException("If 'now' is followed by a token it must be +|- offset"); ! } ! break; ! /* Only absolute time specifications below */ ! case TimeToken.NUMBER: ! timeOfDay(); ! if (token.id != TimeToken.NUMBER) { ! break; ! } ! /* fix month parsing */ ! case TimeToken.JAN: ! case TimeToken.FEB: ! case TimeToken.MAR: ! case TimeToken.APR: ! case TimeToken.MAY: ! case TimeToken.JUN: ! case TimeToken.JUL: ! case TimeToken.AUG: ! case TimeToken.SEP: ! case TimeToken.OCT: ! case TimeToken.NOV: ! case TimeToken.DEC: ! day(); ! if (token.id != TimeToken.NUMBER) { ! break; ! } ! timeOfDay(); ! break; ! ! /* evil coding for TEATIME|NOON|MIDNIGHT - we've initialized ! * hr to zero up above, then fall into this case in such a ! * way so we add +12 +4 hours to it for teatime, +12 hours ! * to it for noon, and nothing at all for midnight, then ! * set our rettime to that hour before leaping into the ! * month scanner ! */ ! case TimeToken.TEATIME: ! hr += 4; ! /* FALLTHRU */ ! case TimeToken.NOON: ! hr += 12; ! /* FALLTHRU */ ! case TimeToken.MIDNIGHT: ! spec.hour = hr; ! spec.min = 0; ! spec.sec = 0; ! token = scanner.nextToken(); ! day(); ! break; ! default: ! throw new RrdException("Unparsable time: " + token.value); ! } ! ! /* ! * the OFFSET-SPEC part ! * ! * (NOTE, the sc_tokid was prefetched for us by the previous code) ! */ ! if (token.id == TimeToken.PLUS || token.id == TimeToken.MINUS) { ! scanner.setContext(false); ! while (token.id == TimeToken.PLUS || token.id == TimeToken.MINUS || ! token.id == TimeToken.NUMBER) { ! if (token.id == TimeToken.NUMBER) { ! plusMinus(PREVIOUS_OP); ! } else { ! plusMinus(token.id); ! } ! token = scanner.nextToken(); ! /* We will get EOF eventually but that's OK, since ! token() will return us as many EOFs as needed */ ! } ! } ! /* now we should be at EOF */ ! if (token.id != TimeToken.EOF) { ! throw new RrdException("Unparsable trailing text: " + token.value); ! } ! return spec; ! } ! ! /* ! public static void main(String[] args) throws IOException { ! BufferedReader r = new BufferedReader(new InputStreamReader(System.in)); ! while (true) { ! String s = r.readLine(); ! try { ! TimeParser p = new TimeParser(s); ! TimeSpec spec = p.parse(); ! System.out.println(spec.getTime().getTime()); ! // System.out.println(spec.dump()); ! } catch (RrdException e) { ! System.err.println("ERROR: " + e); ! } ! } ! } ! */ } \ No newline at end of file --- 1,426 ---- ! /* ============================================================ ! * JRobin : Pure java implementation of RRDTool's functionality ! * ============================================================ ! * ! * Project Info: http://www.jrobin.org ! * Project Lead: Sasa Markovic (sa...@jr...); ! * ! * (C) Copyright 2003-2005, by Sasa Markovic. ! * ! * Developers: Sasa Markovic (sa...@jr...) ! * ! * ! * This library is free software; you can redistribute it and/or modify it under the terms ! * of the GNU Lesser General Public License as published by the Free Software Foundation; ! * either version 2.1 of the License, or (at your option) any later version. ! * ! * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; ! * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. ! * See the GNU Lesser General Public License for more details. ! * ! * You should have received a copy of the GNU Lesser General Public License along with this ! * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, ! * Boston, MA 02111-1307, USA. ! */ ! ! /* ! * Java port of Tobi's original parsetime.c routine ! */ ! package org.jrobin.core.timespec; ! ! import org.jrobin.core.RrdException; ! import org.jrobin.core.Util; ! ! /** ! * Class which parses at-style time specification (describided in detail on the rrdfetch man page), ! * used in all RRDTool commands. This code is in most parts just a java port of Tobi's parsetime.c ! * code. ! */ ! public class TimeParser { ! private static final int PREVIOUS_OP = -1; ! ! TimeToken token; ! TimeScanner scanner; ! TimeSpec spec; ! ! int op = TimeToken.PLUS; ! int prev_multiplier = -1; ! ! /** ! * Constructs TimeParser instance from the given input string. ! * ! * @param dateString at-style time specification (read rrdfetch man page ! * for the complete explanation) ! */ ! public TimeParser(String dateString) { ! scanner = new TimeScanner(dateString); ! spec = new TimeSpec(dateString); ! } ! ! private void expectToken(int desired, String errorMessage) throws RrdException { ! token = scanner.nextToken(); ! if (token.id != desired) { ! throw new RrdException(errorMessage); ! } ! } ! ! private void plusMinus(int doop) throws RrdException { ! if (doop >= 0) { ! op = doop; ! expectToken(TimeToken.NUMBER, "There should be number after " + ! (op == TimeToken.PLUS ? '+' : '-')); ! prev_multiplier = -1; /* reset months-minutes guessing mechanics */ ! } ! int delta = Integer.parseInt(token.value); ! token = scanner.nextToken(); ! if (token.id == TimeToken.MONTHS_MINUTES) { ! /* hard job to guess what does that -5m means: -5mon or -5min? */ ! switch (prev_multiplier) { ! case TimeToken.DAYS: ! case TimeToken.WEEKS: ! case TimeToken.MONTHS: ! case TimeToken.YEARS: ! token = scanner.resolveMonthsMinutes(TimeToken.MONTHS); ! break; ! case TimeToken.SECONDS: ! case TimeToken.MINUTES: ! case TimeToken.HOURS: ! token = scanner.resolveMonthsMinutes(TimeToken.MINUTES); ! break; ! default: ! if (delta < 6) { ! token = scanner.resolveMonthsMinutes(TimeToken.MONTHS); ! } ! else { ! token = scanner.resolveMonthsMinutes(TimeToken.MINUTES); ! } ! } ! } ! prev_multiplier = token.id; ! delta *= (op == TimeToken.PLUS) ? +1 : -1; ! switch (token.id) { ! case TimeToken.YEARS: ! spec.dyear += delta; ! break; ! case TimeToken.MONTHS: ! spec.dmonth += delta; ! break; ! case TimeToken.WEEKS: ! delta *= 7; ! /* FALLTHRU */ ! case TimeToken.DAYS: ! spec.dday += delta; ! break; ! case TimeToken.HOURS: ! spec.dhour += delta; ! break; ! case TimeToken.MINUTES: ! spec.dmin += delta; ! break; ! case TimeToken.SECONDS: ! default: // default is 'seconds' ! spec.dsec += delta; ! break; ! } ! // unreachable statement ! // throw new RrdException("Well-known time unit expected after " + delta); ! } ! ! private void timeOfDay() throws RrdException { ! int hour, minute = 0; ! /* save token status in case we must abort */ ! scanner.saveState(); ! /* first pick out the time of day - we assume a HH (COLON|DOT) MM time */ ! if (token.value.length() > 2) { ! return; ! } ! hour = Integer.parseInt(token.value); ! token = scanner.nextToken(); ! if (token.id == TimeToken.SLASH || token.id == TimeToken.DOT) { ! /* guess we are looking at a date */ ! token = scanner.restoreState(); ! return; ! } ! if (token.id == TimeToken.COLON) { ! expectToken(TimeToken.NUMBER, "Parsing HH:MM syntax, expecting MM as number, got none"); ! minute = Integer.parseInt(token.value); ! if (minute > 59) { ! throw new RrdException("Parsing HH:MM syntax, got MM = " + ! minute + " (>59!)"); ! } ! token = scanner.nextToken(); ! } ! /* check if an AM or PM specifier was given */ ! if (token.id == TimeToken.AM || token.id == TimeToken.PM) { ! if (hour > 12) { ! throw new RrdException("There cannot be more than 12 AM or PM hours"); ! } ! if (token.id == TimeToken.PM) { ! if (hour != 12) { ! /* 12:xx PM is 12:xx, not 24:xx */ ! hour += 12; ! } ! } ! else { ! if (hour == 12) { ! /* 12:xx AM is 00:xx, not 12:xx */ ! hour = 0; ! } ! } ! token = scanner.nextToken(); ! } ! else if (hour > 23) { ! /* guess it was not a time then ... */ ! token = scanner.restoreState(); ! return; ! } ! spec.hour = hour; ! spec.min = minute; ! spec.sec = 0; ! if (spec.hour == 24) { ! spec.hour = 0; ! spec.day++; ! } ! } ! ! private void assignDate(long mday, long mon, long year) throws RrdException { ! if (year > 138) { ! if (year > 1970) { ! year -= 1900; ! } ! else { ! throw new RrdException("Invalid year " + year + ! " (should be either 00-99 or >1900)"); ! } ! } ! else if (year >= 0 && year < 38) { ! year += 100; /* Allow year 2000-2037 to be specified as */ ! } /* 00-37 until the problem of 2038 year will */ ! /* arise for unices with 32-bit time_t */ ! if (year < 70) { ! throw new RrdException("Won't handle dates before epoch (01/01/1970), sorry"); ! } ! spec.year = (int) year; ! spec.month = (int) mon; ! spec.day = (int) mday; ! } ! ! private void day() throws RrdException { ! long mday = 0, wday, mon, year = spec.year; ! switch (token.id) { ! case TimeToken.YESTERDAY: ! spec.day--; ! /* FALLTRHU */ ! case TimeToken.TODAY: /* force ourselves to stay in today - no further processing */ ! token = scanner.nextToken(); ! break; ! case TimeToken.TOMORROW: ! spec.day++; ! token = scanner.nextToken(); ! break; ! case TimeToken.JAN: ! case TimeToken.FEB: ! case TimeToken.MAR: ! case TimeToken.APR: ! case TimeToken.MAY: ! case TimeToken.JUN: ! case TimeToken.JUL: ! case TimeToken.AUG: ! case TimeToken.SEP: ! case TimeToken.OCT: ! case TimeToken.NOV: ! case TimeToken.DEC: ! /* do month mday [year] */ ! mon = (token.id - TimeToken.JAN); ! expectToken(TimeToken.NUMBER, "the day of the month should follow month name"); ! mday = Long.parseLong(token.value); ! token = scanner.nextToken(); ! if (token.id == TimeToken.NUMBER) { ! year = Long.parseLong(token.value); ! token = scanner.nextToken(); ! } ! else { ! year = spec.year; ! } ! assignDate(mday, mon, year); ! break; ! case TimeToken.SUN: ! case TimeToken.MON: ! case TimeToken.TUE: ! case TimeToken.WED: ! case TimeToken.THU: ! case TimeToken.FRI: ! case TimeToken.SAT: ! /* do a particular day of the week */ ! wday = (token.id - TimeToken.SUN); ! spec.day += (wday - spec.wday); ! token = scanner.nextToken(); ! break; ! case TimeToken.NUMBER: ! /* get numeric <sec since 1970>, MM/DD/[YY]YY, or DD.MM.[YY]YY */ ! // int tlen = token.value.length(); ! mon = Long.parseLong(token.value); ! if (mon > 10L * 365L * 24L * 60L * 60L) { ! spec.localtime(mon); ! token = scanner.nextToken(); ! break; ! } ! if (mon > 19700101 && mon < 24000101) { /*works between 1900 and 2400 */ ! year = mon / 10000; ! mday = mon % 100; ! mon = (mon / 100) % 100; ! token = scanner.nextToken(); ! } ! else { ! token = scanner.nextToken(); ! if (mon <= 31 && (token.id == TimeToken.SLASH || token.id == TimeToken.DOT)) { ! int sep = token.id; ! expectToken(TimeToken.NUMBER, "there should be " + ! (sep == TimeToken.DOT ? "month" : "day") + ! " number after " + ! (sep == TimeToken.DOT ? '.' : '/')); ! mday = Long.parseLong(token.value); ! token = scanner.nextToken(); ! if (token.id == sep) { ! expectToken(TimeToken.NUMBER, "there should be year number after " + ! (sep == TimeToken.DOT ? '.' : '/')); ! year = Long.parseLong(token.value); ! token = scanner.nextToken(); ! } ! /* flip months and days for European timing */ ! if (sep == TimeToken.DOT) { ! long x = mday; ! mday = mon; ! mon = x; ! } ! } ! } ! mon--; ! if (mon < 0 || mon > 11) { ! throw new RrdException("Did you really mean month " + (mon + 1)); ! } ! if (mday < 1 || mday > 31) { ! throw new RrdException("I'm afraid that " + mday + ! " is not a valid day of the month"); ! } ! assignDate(mday, mon, year); ! break; ! } ! } ! ! /** ! * Parses the input string specified in the constructor. ! * ! * @return Object representing parsed date/time. ! * @throws RrdException Thrown if the date string cannot be parsed. ! */ ! public TimeSpec parse() throws RrdException { ! long now = Util.getTime(); ! int hr = 0; ! /* this MUST be initialized to zero for midnight/noon/teatime */ ! /* establish the default time reference */ ! spec.localtime(now); ! token = scanner.nextToken(); ! switch (token.id) { ! case TimeToken.PLUS: ! case TimeToken.MINUS: ! break; /* jump to OFFSET-SPEC part */ ! case TimeToken.START: ! spec.type = TimeSpec.TYPE_START; ! /* FALLTHRU */ ! case TimeToken.END: ! if (spec.type != TimeSpec.TYPE_START) { ! spec.type = TimeSpec.TYPE_END; ! } ! spec.year = spec.month = spec.day = spec.hour = spec.min = spec.sec = 0; ! /* FALLTHRU */ ! case TimeToken.NOW: ! int time_reference = token.id; ! token = scanner.nextToken(); ! if (token.id == TimeToken.PLUS || token.id == TimeToken.MINUS) { ! break; ! } ! if (time_reference != TimeToken.NOW) { ! throw new RrdException("Words 'start' or 'end' MUST be followed by +|- offset"); ! } ! else if (token.id != TimeToken.EOF) { ! throw new RrdException("If 'now' is followed by a token it must be +|- offset"); ! } ! break; ! /* Only absolute time specifications below */ ! case TimeToken.NUMBER: ! timeOfDay(); ! if (token.id != TimeToken.NUMBER) { ! break; ! } ! /* fix month parsing */ ! case TimeToken.JAN: ! case TimeToken.FEB: ! case TimeToken.MAR: ! case TimeToken.APR: ! case TimeToken.MAY: ! case TimeToken.JUN: ! case TimeToken.JUL: ! case TimeToken.AUG: ! case TimeToken.SEP: ! case TimeToken.OCT: ! case TimeToken.NOV: ! case TimeToken.DEC: ! day(); ! if (token.id != TimeToken.NUMBER) { ! break; ! } ! timeOfDay(); ! break; ! ! /* evil coding for TEATIME|NOON|MIDNIGHT - we've initialized ! * hr to zero up above, then fall into this case in such a ! * way so we add +12 +4 hours to it for teatime, +12 hours ! * to it for noon, and nothing at all for midnight, then ! * set our rettime to that hour before leaping into the ! * month scanner ! */ ! case TimeToken.TEATIME: ! hr += 4; ! /* FALLTHRU */ ! case TimeToken.NOON: ! hr += 12; ! /* FALLTHRU */ ! case TimeToken.MIDNIGHT: ! spec.hour = hr; ! spec.min = 0; ! spec.sec = 0; ! token = scanner.nextToken(); ! day(); ! break; ! default: ! throw new RrdException("Unparsable time: " + token.value); ! } ! ! /* ! * the OFFSET-SPEC part ! * ! * (NOTE, the sc_tokid was prefetched for us by the previous code) ! */ ! if (token.id == TimeToken.PLUS || token.id == TimeToken.MINUS) { ! scanner.setContext(false); ! while (token.id == TimeToken.PLUS || token.id == TimeToken.MINUS || ! token.id == TimeToken.NUMBER) { ! if (token.id == TimeToken.NUMBER) { ! plusMinus(PREVIOUS_OP); ! } ! else { ! plusMinus(token.id); ! } ! token = scanner.nextToken(); ! /* We will get EOF eventually but that's OK, since ! token() will return us as many EOFs as needed */ ! } ! } ! /* now we should be at EOF */ ! if (token.id != TimeToken.EOF) { ! throw new RrdException("Unparsable trailing text: " + token.value); ! } ! return spec; ! } } \ No newline at end of file Index: Epoch.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/core/timespec/Epoch.java,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** Epoch.java 17 Feb 2005 10:43:13 -0000 1.1 --- Epoch.java 21 Dec 2006 18:02:42 -0000 1.2 *************** *** 1,152 **** ! package org.jrobin.core.timespec; ! ! import org.jrobin.core.RrdException; ! import org.jrobin.core.Util; ! ! import javax.swing.*; ! import java.util.Date; ! import java.awt.*; ! import java.awt.event.ActionListener; ! import java.awt.event.ActionEvent; ! import java.text.SimpleDateFormat; ! import java.text.ParseException; ! ! class Epoch extends JFrame implements Runnable { ! private static final String[] formats = { ! "MM/dd/yy HH:mm:ss", ! "dd.MM.yy HH:mm:ss", ! "yy-MM-dd HH:mm:ss", ! "MM/dd/yy HH:mm", ! "dd.MM.yy HH:mm", ! "yy-MM-dd HH:mm", ! "MM/dd/yy", ! "dd.MM.yy", ! "yy-MM-dd", ! "HH:mm MM/dd/yy", ! "HH:mm dd.MM.yy", ! "HH:mm yy-MM-dd", ! "HH:mm:ss MM/dd/yy", ! "HH:mm:ss dd.MM.yy", ! "HH:mm:ss yy-MM-dd" ! }; ! ! private static final SimpleDateFormat[] parsers = new SimpleDateFormat[formats.length]; ! private static final String helpText; ! ! static { ! for(int i = 0; i < parsers.length; i++) { ! parsers[i] = new SimpleDateFormat(formats[i]); ! parsers[i].setLenient(true); ! } ! StringBuffer tooltipBuff = new StringBuffer("<html><b>Supported input formats:</b><br>"); ! for(int i = 0; i < formats.length; i++) { ! tooltipBuff.append(formats[i] + "<br>"); ! } ! tooltipBuff.append("<b>RRDTool time format</b><br>"); ! tooltipBuff.append("... including timestamps</html>"); ! helpText = tooltipBuff.toString(); ! } ! ! private JLabel topLabel = new JLabel("Enter timestamp or readable date:"); ! private JTextField inputField = new JTextField(25); ! private JButton button = new JButton("Convert"); ! //private JLabel helpLabel = new JLabel(helpText); ! ! private static final SimpleDateFormat OUTPUT_DATE_FORMAT = ! new SimpleDateFormat("MM/dd/yy HH:mm:ss EEE"); ! ! Epoch() { ! super("Epoch"); ! constructUI(); ! setVisible(true); ! new Thread(this).start(); ! } ! ! private void constructUI() { ! JPanel c = (JPanel) getContentPane(); ! c.setLayout(new BorderLayout()); ! ! c.add(topLabel, BorderLayout.NORTH); ! c.add(inputField, BorderLayout.CENTER); ! c.add(button, BorderLayout.EAST); ! // c.add(helpLabel, BorderLayout.WEST); ! ! button.setToolTipText(helpText); ! button.addActionListener(new ActionListener() { ! public void actionPerformed(ActionEvent e) { ! convert(); ! } ! }); ! ! inputField.requestFocus(); ! getRootPane().setDefaultButton(button); ! setResizable(false); ! setDefaultCloseOperation(EXIT_ON_CLOSE); ! pack(); ! centerOnScreen(); ! ! } ! ! void centerOnScreen() { ! Toolkit t = Toolkit.getDefaultToolkit(); ! Dimension screenSize = t.getScreenSize(); ! Dimension frameSize = getPreferredSize(); ! double x = (screenSize.getWidth() - frameSize.getWidth()) / 2; ! double y = (screenSize.getHeight() - frameSize.getHeight()) / 2; ! setLocation((int) x, (int) y); ! } ! ! private void convert() { ! String time = inputField.getText().trim(); ! if(time.length() > 0) { ! // try simple timestamp ! try { ! long timestamp = Long.parseLong(time); ! Date date = new Date(timestamp * 1000L); ! formatDate(date); ! } ! catch(NumberFormatException nfe) { ! // failed, try as a date ! try { ! inputField.setText("" + parseDate(time)); ! } ! catch (RrdException e) { ! inputField.setText("Could not convert, sorry"); ! } ! } ! } ! } ! ! public void run() { ! for(;;) { ! Date now = new Date(); ! long timestamp = now.getTime() / 1000L; ! setTitle(timestamp + " seconds since epoch"); ! try { ! Thread.sleep(1000L); ! } ! catch (InterruptedException e) { ! } ! } ! } ! ! void formatDate(Date date) { ! inputField.setText(OUTPUT_DATE_FORMAT.format(date)); ! } ! ! private long parseDate(String time) throws RrdException { ! for(int i = 0; i < parsers.length; i++) { ! try { ! return Util.getTimestamp(parsers[i].parse(time)); ! } ! catch (ParseException e) { ! } ! } ! return new TimeParser(time).parse().getTimestamp(); ! } ! ! ! public static void main(String[] args) { ! new Epoch(); ! } ! } --- 1,168 ---- ! package org.jrobin.core.timespec; ! ! import org.jrobin.core.RrdException; ! import org.jrobin.core.Util; ! ! import javax.swing.*; ! import java.awt.*; ! import java.awt.event.ActionEvent; ! import java.awt.event.ActionListener; ! import java.text.ParseException; ! import java.text.SimpleDateFormat; ! import java.util.Date; ! ! /** ! * Small swing-based utility to convert timestamps (seconds since epoch) to readable dates and vice versa. ! * Supports at-style time specification (like "now-2d", "noon yesterday") and other human-readable ! * data formats:<p> ! * <ul> ! * <li>MM/dd/yy HH:mm:ss ! * <li>dd.MM.yy HH:mm:ss ! * <li>dd.MM.yy HH:mm:ss ! * <li>MM/dd/yy HH:mm ! * <li>dd.MM.yy HH:mm ! * <li>yy-MM-dd HH:mm ! * <li>MM/dd/yy ! * <li>dd.MM.yy ! * <li>yy-MM-dd ! * <li>HH:mm MM/dd/yy ! * <li>HH:mm dd.MM.yy ! * <li>HH:mm yy-MM-dd ! * <li>HH:mm:ss MM/dd/yy ! * <li>HH:mm:ss dd.MM.yy ! * <li>HH:mm:ss yy-MM-dd ! * </ul> ! * The current timestamp is displayed in the title bar :)<p> ! */ ! public class Epoch extends JFrame { ! private static final String[] supportedFormats = { ! "MM/dd/yy HH:mm:ss", "dd.MM.yy HH:mm:ss", "yy-MM-dd HH:mm:ss", "MM/dd/yy HH:mm", ! "dd.MM.yy HH:mm", "yy-MM-dd HH:mm", "MM/dd/yy", "dd.MM.yy", "yy-MM-dd", "HH:mm MM/dd/yy", ! "HH:mm dd.MM.yy", "HH:mm yy-MM-dd", "HH:mm:ss MM/dd/yy", "HH:mm:ss dd.MM.yy", "HH:mm:ss yy-MM-dd" ! }; ! ! private static final SimpleDateFormat[] parsers = new SimpleDateFormat[supportedFormats.length]; ! private static final String helpText; ! ! private Timer timer = new Timer(1000, new ActionListener() { ! public void actionPerformed(ActionEvent e) { ! showTimestamp(); ! } ! }); ! ! static { ! for (int i = 0; i < parsers.length; i++) { ! parsers[i] = new SimpleDateFormat(supportedFormats[i]); ! parsers[i].setLenient(true); ! } ! StringBuffer tooltipBuff = new StringBuffer("<html><b>Supported input formats:</b><br>"); ! for (String supportedFormat : supportedFormats) { ! tooltipBuff.append(supportedFormat).append("<br>"); ! } ! tooltipBuff.append("<b>AT-style time specification</b><br>"); ! tooltipBuff.append("timestamp<br><br>"); ! tooltipBuff.append("Copyright (C) 2003-2005 Sasa Markovic, All Rights Reserved</html>"); ! helpText = tooltipBuff.toString(); ! } ! ! private JLabel topLabel = new JLabel("Enter timestamp or readable date:"); ! private JTextField inputField = new JTextField(25); ! private JButton convertButton = new JButton("Convert"); ! private JButton helpButton = new JButton("Help"); ! ! private static final SimpleDateFormat OUTPUT_DATE_FORMAT = ! new SimpleDateFormat("MM/dd/yy HH:mm:ss EEE"); ! ! Epoch() { ! super("Epoch"); ! constructUI(); ! timer.start(); ! } ! ! private void constructUI() { ! JPanel c = (JPanel) getContentPane(); ! c.setLayout(new BorderLayout(3, 3)); ! c.add(topLabel, BorderLayout.NORTH); ! c.add(inputField, BorderLayout.WEST); ! c.add(convertButton, BorderLayout.CENTER); ! convertButton.setToolTipText(helpText); ! convertButton.addActionListener(new ActionListener() { ! public void actionPerformed(ActionEvent e) { ! convert(); ! } ! }); ! c.add(helpButton, BorderLayout.EAST); ! helpButton.addActionListener(new ActionListener() { ! public void actionPerformed(ActionEvent e) { ! JOptionPane.showMessageDialog(helpButton, helpText, "Epoch Help", JOptionPane.INFORMATION_MESSAGE); ! } ! }); ! inputField.requestFocus(); ! getRootPane().setDefaultButton(convertButton); ! setResizable(false); ! setDefaultCloseOperation(EXIT_ON_CLOSE); ! pack(); ! centerOnScreen(); ! setVisible(true); ! } ! ! void centerOnScreen() { ! Toolkit t = Toolkit.getDefaultToolkit(); ! Dimension screenSize = t.getScreenSize(); ! Dimension frameSize = getPreferredSize(); ! double x = (screenSize.getWidth() - frameSize.getWidth()) / 2; ! double y = (screenSize.getHeight() - frameSize.getHeight()) / 2; ! setLocation((int) x, (int) y); ! } ! ! private void convert() { ! String time = inputField.getText().trim(); ! if (time.length() > 0) { ! // try simple timestamp ! try { ! long timestamp = Long.parseLong(time); ! Date date = new Date(timestamp * 1000L); ! formatDate(date); ! } ! catch (NumberFormatException nfe) { ! // failed, try as a date ! try { ! inputField.setText("" + parseDate(time)); ! } ! catch (RrdException e) { ! inputField.setText("Could not convert, sorry"); ! } ! } ! } ! } ! ! private void showTimestamp() { ! long timestamp = Util.getTime(); ! setTitle(timestamp + " seconds since epoch"); ! } ! ! void formatDate(Date date) { ! inputField.setText(OUTPUT_DATE_FORMAT.format(date)); ! } ! ! private long parseDate(String time) throws RrdException { ! for (SimpleDateFormat parser : parsers) { ! try { ! return Util.getTimestamp(parser.parse(time)); ! } ! catch (ParseException e) { ! // NOP ! } ! } ! return new TimeParser(time).parse().getTimestamp(); ! } ! ! /** ! * Main method which runs this utility. ! * ! * @param args Not used. ! */ ! public static void main(String[] args) { ! new Epoch(); ! } ! } Index: TimeToken.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/core/timespec/TimeToken.java,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** TimeToken.java 17 Feb 2005 10:43:13 -0000 1.1 --- TimeToken.java 21 Dec 2006 18:02:42 -0000 1.2 *************** *** 1,88 **** ! /* ============================================================ ! * JRobin : Pure java implementation of RRDTool's functionality ! * ============================================================ ! * ! * Project Info: http://www.jrobin.org ! * Project Lead: Sasa Markovic (sa...@jr...); ! * ! * (C) Copyright 2003, by Sasa Markovic. ! * ! * Developers: Sasa Markovic (sa...@jr...) ! * Arne Vandamme (cob...@jr...) ! * ! * This library is free software; you can redistribute it and/or modify it under the terms ! * of the GNU Lesser General Public License as published by the Free Software Foundation; ! * either version 2.1 of the License, or (at your option) any later version. ! * ! * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; ! * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. ! * See the GNU Lesser General Public License for more details. ! * ! * You should have received a copy of the GNU Lesser General Public License along with this ! * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, ! * Boston, MA 02111-1307, USA. ! */ ! ! package org.jrobin.core.timespec; ! ! class TimeToken { ! public static final int MIDNIGHT = 1; ! public static final int NOON = 2; ! public static final int TEATIME = 3; ! public static final int PM = 4; ! public static final int AM = 5; ! public static final int YESTERDAY = 6; ! public static final int TODAY = 7; ! public static final int TOMORROW = 8; ! public static final int NOW = 9; ! public static final int START = 10; ! public static final int END = 11; ! public static final int SECONDS = 12; ! public static final int MINUTES = 13; ! public static final int HOURS = 14; ! public static final int DAYS = 15; ! public static final int WEEKS = 16; ! public static final int MONTHS = 17; ! public static final int YEARS = 18; ! public static final int MONTHS_MINUTES = 19; ! public static final int NUMBER = 20; ! public static final int PLUS = 21; ! public static final int MINUS = 22; ! public static final int DOT = 23; ! public static final int COLON = 24; ! public static final int SLASH = 25; ! public static final int ID = 26; ! public static final int JUNK = 27; ! public static final int JAN = 28; ! public static final int FEB = 29; ! public static final int MAR = 30; ! public static final int APR = 31; ! public static final int MAY = 32; ! public static final int JUN = 33; ! public static final int JUL = 34; ! public static final int AUG = 35; ! public static final int SEP = 36; ! public static final int OCT = 37; ! public static final int NOV = 38; ! public static final int DEC = 39; ! public static final int SUN = 40; ! public static final int MON = 41; ! public static final int TUE = 42; ! public static final int WED = 43; ! public static final int THU = 44; ! public static final int FRI = 45; ! public static final int SAT = 46; ! public static final int EOF = -1; ! ! final String value; /* token name */ ! final int id; /* token id */ ! ! public TimeToken(String value, int id) { ! this.value = value; ! this.id = id; ! } ! ! public String toString() { ! return value + " [" + id + "]"; ! } } \ No newline at end of file --- 1,88 ---- ! /* ============================================================ ! * JRobin : Pure java implementation of RRDTool's functionality ! * ============================================================ ! * ! * Project Info: http://www.jrobin.org ! * Project Lead: Sasa Markovic (sa...@jr...); ! * ! * (C) Copyright 2003-2005, by Sasa Markovic. ! * ! * Developers: Sasa Markovic (sa...@jr...) ! * ! * ! * This library is free software; you can redistribute it and/or modify it under the terms ! * of the GNU Lesser General Public License as published by the Free Software Foundation; ! * either version 2.1 of the License, or (at your option) any later version. ! * ! * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; ! * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. ! * See the GNU Lesser General Public License for more details. ! * ! * You should have received a copy of the GNU Lesser General Public License along with this ! * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, ! * Boston, MA 02111-1307, USA. ! */ ! ! package org.jrobin.core.timespec; ! ! class TimeToken { ! public static final int MIDNIGHT = 1; ! public static final int NOON = 2; ! public static final int TEATIME = 3; ! public static final int PM = 4; ! public static final int AM = 5; ! public static final int YESTERDAY = 6; ! public static final int TODAY = 7; ! public static final int TOMORROW = 8; ! public static final int NOW = 9; ! public static final int START = 10; ! public static final int END = 11; ! public static final int SECONDS = 12; ! public static final int MINUTES = 13; ! public static final int HOURS = 14; ! public static final int DAYS = 15; ! public static final int WEEKS = 16; ! public static final int MONTHS = 17; ! public static final int YEARS = 18; ! public static final int MONTHS_MINUTES = 19; ! public static final int NUMBER = 20; ! public static final int PLUS = 21; ! public static final int MINUS = 22; ! public static final int DOT = 23; ! public static final int COLON = 24; ! public static final int SLASH = 25; ! public static final int ID = 26; ! public static final int JUNK = 27; ! public static final int JAN = 28; ! public static final int FEB = 29; ! public static final int MAR = 30; ! public static final int APR = 31; ! public static final int MAY = 32; ! public static final int JUN = 33; ! public static final int JUL = 34; ! public static final int AUG = 35; ! public static final int SEP = 36; ! public static final int OCT = 37; ! public static final int NOV = 38; ! public static final int DEC = 39; ! public static final int SUN = 40; ! public static final int MON = 41; ! public static final int TUE = 42; ! public static final int WED = 43; ! public static final int THU = 44; ! public static final int FRI = 45; ! public static final int SAT = 46; ! public static final int EOF = -1; ! ! final String value; /* token name */ ! final int id; /* token id */ ! ! public TimeToken(String value, int id) { ! this.value = value; ! this.id = id; ! } ! ! public String toString() { ! return value + " [" + id + "]"; ! } } \ No newline at end of file Index: TimeScanner.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/core/timespec/TimeScanner.java,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** TimeScanner.java 17 Feb 2005 10:43:13 -0000 1.1 --- TimeScanner.java 21 Dec 2006 18:02:42 -0000 1.2 *************** *** 1,208 **** ! /* ============================================================ ! * JRobin : Pure java implementation of RRDTool's functionality ! * ============================================================ ! * ! * Project Info: http://www.jrobin.org ! * Project Lead: Sasa Markovic (sa...@jr...); ! * ! * (C) Copyright 2003, by Sasa Markovic. ! * ! * Developers: Sasa Markovic (sa...@jr...) ! * Arne Vandamme (cob...@jr...) ! * ! * This library is free software; you can redistribute it and/or modify it under the terms ! * of the GNU Lesser General Public License as published by the Free Software Foundation; ! * either version 2.1 of the License, or (at your option) any later version. ! * ! * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; ! * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. ! * See the GNU Lesser General Public License for more details. ! * ! * You should have received a copy of the GNU Lesser General Public License along with this ! * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, ! * Boston, MA 02111-1307, USA. ! */ ! package org.jrobin.core.timespec; ! ! class TimeScanner { ! private String dateString; ! ! private int pos, pos_save; ! private TimeToken token, token_save; ! ! static final TimeToken[] WORDS = { ! new TimeToken("midnight", TimeToken.MIDNIGHT), /* 00:00:00 of today or tomorrow */ ! new TimeToken("noon", TimeToken.NOON), /* 12:00:00 of today or tomorrow */ ! new TimeToken("teatime", TimeToken.TEATIME), /* 16:00:00 of today or tomorrow */ ! new TimeToken("am", TimeToken.AM), /* morning times for 0-12 clock */ ! new TimeToken("pm", TimeToken.PM), /* evening times for 0-12 clock */ ! new TimeToken("tomorrow", TimeToken.TOMORROW), ! new TimeToken("yesterday", TimeToken.YESTERDAY), ! new TimeToken("today", TimeToken.TODAY), ! new TimeToken("now", TimeToken.NOW), ! new TimeToken("n", TimeToken.NOW), ! new TimeToken("start", TimeToken.START), ! new TimeToken("s", TimeToken.START), ! new TimeToken("end", TimeToken.END), ! new TimeToken("e", TimeToken.END), ! new TimeToken("jan", TimeToken.JAN), ! new TimeToken("feb", TimeToken.FEB), ! new TimeToken("mar", TimeToken.MAR), ! new TimeToken("apr", TimeToken.APR), ! new TimeToken("may", TimeToken.MAY), ! new TimeToken("jun", TimeToken.JUN), ! new TimeToken("jul", TimeToken.JUL), ! new TimeToken("aug", TimeToken.AUG), ! new TimeToken("sep", TimeToken.SEP), ! new TimeToken("oct", TimeToken.OCT), ! new TimeToken("nov", TimeToken.NOV), ! new TimeToken("dec", TimeToken.DEC), ! new TimeToken("january", TimeToken.JAN), ! new TimeToken("february", TimeToken.FEB), ! new TimeToken("march", TimeToken.MAR), ! new TimeToken("april", TimeToken.APR), ! new TimeToken("may", TimeToken.MAY), ! new TimeToken("june", TimeToken.JUN), ! new TimeToken("july", TimeToken.JUL), ! new TimeToken("august", TimeToken.AUG), ! new TimeToken("september", TimeToken.SEP), ! new TimeToken("october", TimeToken.OCT), ! new TimeToken("november", TimeToken.NOV), ! new TimeToken("december", TimeToken.DEC), ! new TimeToken("sunday", TimeToken.SUN), ! new TimeToken("su... [truncated message content] |
From: Tarus B. <ta...@us...> - 2006-12-21 18:03:15
|
Update of /cvsroot/jrobin/src/org/jrobin/cmd In directory sc8-pr-cvs6.sourceforge.net:/tmp/cvs-serv9082/org/jrobin/cmd Modified Files: ColonSplitter.java RrdCmdScanner.java RrdCommander.java RrdCreateCmd.java RrdDumpCmd.java RrdFetchCmd.java RrdGraphCmd.java RrdInfoCmd.java RrdLastCmd.java RrdRestoreCmd.java RrdToolCmd.java RrdTuneCmd.java RrdUpdateCmd.java RrdXportCmd.java Log Message: Adding the new 1.5.4 code Index: RrdFetchCmd.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/cmd/RrdFetchCmd.java,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** RrdFetchCmd.java 17 Feb 2005 10:43:12 -0000 1.4 --- RrdFetchCmd.java 21 Dec 2006 18:02:40 -0000 1.5 *************** *** 1,76 **** ! /* ============================================================ ! * JRobin : Pure java implementation of RRDTool's functionality ! * ============================================================ ! * ! * Project Info: http://www.jrobin.org ! * Project Lead: Sasa Markovic (sa...@jr...); ! * ! * (C) Copyright 2003, by Sasa Markovic. ! * ! * Developers: Sasa Markovic (sa...@jr...) ! * Arne Vandamme (cob...@jr...) ! * ! * This library is free software; you can redistribute it and/or modify it under the terms ! * of the GNU Lesser General Public License as published by the Free Software Foundation; ! * either version 2.1 of the License, or (at your option) any later version. ! * ! * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; ! * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. ! * See the GNU Lesser General Public License for more details. ! * ! * You should have received a copy of the GNU Lesser General Public License along with this ! * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, ! * Boston, MA 02111-1307, USA. ! */ ! ! package org.jrobin.cmd; ! ! import org.jrobin.core.RrdException; ! import org.jrobin.core.RrdDb; ! import org.jrobin.core.FetchRequest; ! import org.jrobin.core.FetchData; ! import org.jrobin.core.timespec.TimeParser; ! import org.jrobin.core.timespec.TimeSpec; ! ! import java.io.IOException; ! ! class RrdFetchCmd extends RrdToolCmd { ! static final String DEFAULT_START = "end-1day"; ! static final String DEFAULT_END = "now"; ! ! String getCmdType() { ! return "fetch"; ! } ! ! Object execute() throws RrdException, IOException { ! // --start ! String startStr = getOptionValue("s", "start", DEFAULT_START); ! TimeSpec spec1 = new TimeParser(startStr).parse(); ! // --end ! String endStr = getOptionValue("e", "end", DEFAULT_END); ! TimeSpec spec2 = new TimeParser(endStr).parse(); ! long[] timestamps = TimeSpec.getTimestamps(spec1, spec2); ! // --resolution ! String resolutionStr = getOptionValue("r", "resolution", "1"); ! long resolution = parseLong(resolutionStr); ! // other words ! String[] words = getRemainingWords(); ! if(words.length != 3) { ! throw new RrdException("Invalid rrdfetch syntax"); ! } ! String path = words[1]; ! String consolFun = words[2]; ! RrdDb rrdDb = getRrdDbReference(path); ! try { ! FetchRequest fetchRequest = rrdDb.createFetchRequest( ! consolFun, timestamps[0], timestamps[1], resolution); ! System.out.println(fetchRequest.dump()); ! FetchData fetchData = fetchRequest.fetchData(); ! println(fetchData.toString()); ! return fetchData; ! } ! finally { ! releaseRrdDbReference(rrdDb); ! } ! } ! } --- 1,63 ---- ! /* ============================================================ ! * JRobin : Pure java implementation of RRDTool's functionality ! * ============================================================ ! * ! * Project Info: http://www.jrobin.org ! * Project Lead: Sasa Markovic (sa...@jr...); ! * ! * (C) Copyright 2003-2005, by Sasa Markovic. ! * ! * Developers: Sasa Markovic (sa...@jr...) ! * ! * ! * This library is free software; you can redistribute it and/or modify it under the terms ! * of the GNU Lesser General Public License as published by the Free Software Foundation; ! * either version 2.1 of the License, or (at your option) any later version. ! * ! * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; ! * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. ! * See the GNU Lesser General Public License for more details. ! * ! * You should have received a copy of the GNU Lesser General Public License along with this ! * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, ! * Boston, MA 02111-1307, USA. ! */ ! ! package org.jrobin.cmd; ! ! import org.jrobin.core.*; ! import org.jrobin.graph.RrdGraphConstants; ! ! import java.io.IOException; ! ! class RrdFetchCmd extends RrdToolCmd implements RrdGraphConstants { ! String getCmdType() { ! return "fetch"; ! } ! ! Object execute() throws RrdException, IOException { ! String startStr = getOptionValue("s", "start", DEFAULT_START); ! String endStr = getOptionValue("e", "end", DEFAULT_END); ! long[] timestamps = Util.getTimestamps(startStr, endStr); ! String resolutionStr = getOptionValue("r", "resolution", "1"); ! long resolution = parseLong(resolutionStr); ! // other words ! String[] words = getRemainingWords(); ! if (words.length != 3) { ! throw new RrdException("Invalid rrdfetch syntax"); ! } ! String path = words[1]; ! String consolFun = words[2]; ! RrdDb rrdDb = getRrdDbReference(path); ! try { ! FetchRequest fetchRequest = rrdDb.createFetchRequest(consolFun, timestamps[0], timestamps[1], resolution); ! System.out.println(fetchRequest.dump()); ! FetchData fetchData = fetchRequest.fetchData(); ! println(fetchData.toString()); ! return fetchData; ! } ! finally { ! releaseRrdDbReference(rrdDb); ! } ! } ! } Index: RrdRestoreCmd.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/cmd/RrdRestoreCmd.java,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** RrdRestoreCmd.java 16 Jul 2004 07:40:48 -0000 1.2 --- RrdRestoreCmd.java 21 Dec 2006 18:02:40 -0000 1.3 *************** *** 1,43 **** ! package org.jrobin.cmd; ! ! import org.jrobin.core.RrdException; ! import org.jrobin.core.RrdDb; ! import org.jrobin.core.Datasource; ! ! import java.io.IOException; ! ! class RrdRestoreCmd extends RrdToolCmd { ! ! String getCmdType() { ! return "restore"; ! } ! ! Object execute() throws RrdException, IOException { ! boolean check = getBooleanOption("r", "range-check"); ! String[] words = getRemainingWords(); ! if(words.length != 3) { ! throw new RrdException("Invalid rrdrestore syntax"); ! } ! String xmlPath = words[1]; ! String rrdPath = words[2]; ! RrdDb rrdDb = getRrdDbReference(rrdPath, xmlPath); ! try { ! if(check) { ! int dsCount = rrdDb.getHeader().getDsCount(); ! for(int i = 0; i < dsCount; i++) { ! Datasource ds = rrdDb.getDatasource(i); ! double minValue = ds.getMinValue(); ! double maxValue = ds.getMaxValue(); ! // this will perform range check ! ds.setMinMaxValue(minValue, maxValue, true); ! } ! } ! return rrdPath; ! } ! finally { ! releaseRrdDbReference(rrdDb); ! } ! } ! ! ! } --- 1,64 ---- ! /* ============================================================ ! * JRobin : Pure java implementation of RRDTool's functionality ! * ============================================================ ! * ! * Project Info: http://www.jrobin.org ! * Project Lead: Sasa Markovic (sa...@jr...); ! * ! * (C) Copyright 2003-2005, by Sasa Markovic. ! * ! * Developers: Sasa Markovic (sa...@jr...) ! * ! * ! * This library is free software; you can redistribute it and/or modify it under the terms ! * of the GNU Lesser General Public License as published by the Free Software Foundation; ! * either version 2.1 of the License, or (at your option) any later version. ! * ! * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; ! * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. ! * See the GNU Lesser General Public License for more details. ! * ! * You should have received a copy of the GNU Lesser General Public License along with this ! * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, ! * Boston, MA 02111-1307, USA. ! */ ! package org.jrobin.cmd; ! ! import org.jrobin.core.Datasource; ! import org.jrobin.core.RrdDb; ! import org.jrobin.core.RrdException; ! ! import java.io.IOException; ! ! class RrdRestoreCmd extends RrdToolCmd { ! String getCmdType() { ! return "restore"; ! } ! ! Object execute() throws RrdException, IOException { ! boolean check = getBooleanOption("r", "range-check"); ! String[] words = getRemainingWords(); ! if (words.length != 3) { ! throw new RrdException("Invalid rrdrestore syntax"); ! } ! String xmlPath = words[1]; ! String rrdPath = words[2]; ! RrdDb rrdDb = getRrdDbReference(rrdPath, xmlPath); ! try { ! if (check) { ! int dsCount = rrdDb.getHeader().getDsCount(); ! for (int i = 0; i < dsCount; i++) { ! Datasource ds = rrdDb.getDatasource(i); ! double minValue = ds.getMinValue(); ! double maxValue = ds.getMaxValue(); ! // this will perform range check ! ds.setMinMaxValue(minValue, maxValue, true); ! } ! } ! return rrdPath; ! } ! finally { ! releaseRrdDbReference(rrdDb); ! } ! } ! } Index: RrdTuneCmd.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/cmd/RrdTuneCmd.java,v retrieving revision 1.1.1.1 retrieving revision 1.2 diff -C2 -d -r1.1.1.1 -r1.2 *** RrdTuneCmd.java 6 Sep 2005 20:40:54 -0000 1.1.1.1 --- RrdTuneCmd.java 21 Dec 2006 18:02:40 -0000 1.2 *************** *** 45,52 **** String[] dsNames = getMultipleOptionValues("r", "data-source-rename"); String[] words = getRemainingWords(); ! if(words.length < 2) { throw new RrdException("File name not specified"); } ! if(words.length > 2) { throw new RrdException("Unexpected token encountered: " + words[2]); } --- 45,52 ---- String[] dsNames = getMultipleOptionValues("r", "data-source-rename"); String[] words = getRemainingWords(); ! if (words.length < 2) { throw new RrdException("File name not specified"); } ! if (words.length > 2) { throw new RrdException("Unexpected token encountered: " + words[2]); } *************** *** 55,80 **** try { // heartbeat ! for(int i = 0; i < heartbeats.length; i++) { ! tuneHeartbeat(rrd, heartbeats[i]); } // minimum ! for(int i = 0; i < minimums.length; i++) { ! tuneMinimum(rrd, minimums[i]); } // maximum ! for(int i = 0; i < maximums.length; i++) { ! tuneMaximum(rrd, maximums[i]); } // rename ! for(int i = 0; i < dsNames.length; i++) { ! tuneName(rrd, dsNames[i]); } // type ! for(int i = 0; i < dsTypes.length; i++) { ! tuneType(rrd, dsTypes[i]); } // post festum ! if(heartbeats.length == 0 && minimums.length == 0 && maximums.length == 0 && ! dsTypes.length == 0 && dsNames.length == 0) { dump(rrd); } --- 55,80 ---- try { // heartbeat ! for (String heartbeat : heartbeats) { ! tuneHeartbeat(rrd, heartbeat); } // minimum ! for (String minimum : minimums) { ! tuneMinimum(rrd, minimum); } // maximum ! for (String maximum : maximums) { ! tuneMaximum(rrd, maximum); } // rename ! for (String dsName : dsNames) { ! tuneName(rrd, dsName); } // type ! for (String dsType : dsTypes) { ! tuneType(rrd, dsType); } // post festum ! if (heartbeats.length == 0 && minimums.length == 0 && maximums.length == 0 && ! dsTypes.length == 0 && dsNames.length == 0) { dump(rrd); } *************** *** 88,92 **** private void tuneHeartbeat(RrdDb rrd, String heartbeatStr) throws RrdException, IOException { String[] tokens = new ColonSplitter(heartbeatStr).split(); ! if(tokens.length != 2) { throw new RrdException("Invalid suntax in: " + heartbeatStr); } --- 88,92 ---- private void tuneHeartbeat(RrdDb rrd, String heartbeatStr) throws RrdException, IOException { String[] tokens = new ColonSplitter(heartbeatStr).split(); ! if (tokens.length != 2) { throw new RrdException("Invalid suntax in: " + heartbeatStr); } *************** *** 99,103 **** private void tuneMinimum(RrdDb rrd, String minimumStr) throws RrdException, IOException { String[] tokens = new ColonSplitter(minimumStr).split(); ! if(tokens.length != 2) { throw new RrdException("Invalid suntax in: " + minimumStr); } --- 99,103 ---- private void tuneMinimum(RrdDb rrd, String minimumStr) throws RrdException, IOException { String[] tokens = new ColonSplitter(minimumStr).split(); ! if (tokens.length != 2) { throw new RrdException("Invalid suntax in: " + minimumStr); } *************** *** 110,114 **** private void tuneMaximum(RrdDb rrd, String maximumStr) throws RrdException, IOException { String[] tokens = new ColonSplitter(maximumStr).split(); ! if(tokens.length != 2) { throw new RrdException("Invalid suntax in: " + maximumStr); } --- 110,114 ---- private void tuneMaximum(RrdDb rrd, String maximumStr) throws RrdException, IOException { String[] tokens = new ColonSplitter(maximumStr).split(); ! if (tokens.length != 2) { throw new RrdException("Invalid suntax in: " + maximumStr); } *************** *** 121,125 **** private void tuneName(RrdDb rrd, String nameStr) throws RrdException, IOException { String[] tokens = new ColonSplitter(nameStr).split(); ! if(tokens.length != 2) { throw new RrdException("Invalid suntax in: " + nameStr); } --- 121,125 ---- private void tuneName(RrdDb rrd, String nameStr) throws RrdException, IOException { String[] tokens = new ColonSplitter(nameStr).split(); ! if (tokens.length != 2) { throw new RrdException("Invalid suntax in: " + nameStr); } *************** *** 131,135 **** private void tuneType(RrdDb rrd, String typeStr) throws RrdException, IOException { String[] tokens = new ColonSplitter(typeStr).split(); ! if(tokens.length != 2) { throw new RrdException("Invalid suntax in: " + typeStr); } --- 131,135 ---- private void tuneType(RrdDb rrd, String typeStr) throws RrdException, IOException { String[] tokens = new ColonSplitter(typeStr).split(); ! if (tokens.length != 2) { throw new RrdException("Invalid suntax in: " + typeStr); } *************** *** 143,147 **** StringBuffer line = new StringBuffer(); int n = rrd.getDsCount(); ! for(int i = 0; i < n; i++) { Datasource ds = rrd.getDatasource(i); line.append("DS["); --- 143,147 ---- StringBuffer line = new StringBuffer(); int n = rrd.getDsCount(); ! for (int i = 0; i < n; i++) { Datasource ds = rrd.getDatasource(i); line.append("DS["); *************** *** 149,158 **** line.append("] typ: "); line.append(ds.getDsType()); ! while(line.length() < 24) { line.append(' '); } line.append("hbt: "); line.append(ds.getHeartbeat()); ! while(line.length() < 40) { line.append(' '); } --- 149,158 ---- line.append("] typ: "); line.append(ds.getDsType()); ! while (line.length() < 24) { line.append(' '); } line.append("hbt: "); line.append(ds.getHeartbeat()); ! while (line.length() < 40) { line.append(' '); } Index: RrdGraphCmd.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/cmd/RrdGraphCmd.java,v retrieving revision 1.1.1.1 retrieving revision 1.2 diff -C2 -d -r1.1.1.1 -r1.2 *** RrdGraphCmd.java 6 Sep 2005 20:40:54 -0000 1.1.1.1 --- RrdGraphCmd.java 21 Dec 2006 18:02:40 -0000 1.2 *************** *** 204,208 **** // create diagram finally RrdGraphInfo info = new RrdGraph(gdef).getRrdGraphInfo(); ! if(info.getFilename().equals(RrdGraphConstants.IN_MEMORY_IMAGE)) { println(new String(info.getBytes())); } --- 204,208 ---- // create diagram finally RrdGraphInfo info = new RrdGraph(gdef).getRrdGraphInfo(); ! if (info.getFilename().equals(RrdGraphConstants.IN_MEMORY_IMAGE)) { println(new String(info.getBytes())); } *************** *** 210,217 **** println(info.getWidth() + "x" + info.getHeight()); String[] plines = info.getPrintLines(); ! for(int i = 0; i < plines.length; i++) { ! println(plines[i]); } ! if(info.getImgInfo() != null && info.getImgInfo().length() > 0) { println(info.getImgInfo()); } --- 210,217 ---- println(info.getWidth() + "x" + info.getHeight()); String[] plines = info.getPrintLines(); ! for (String pline : plines) { ! println(pline); } ! if (info.getImgInfo() != null && info.getImgInfo().length() > 0) { println(info.getImgInfo()); } *************** *** 347,354 **** return; } ! for (int i = 0; i < colorOptions.length; i++) { ! String[] tokens = colorOptions[i].split("#"); if (tokens.length != 2) { ! throw new RrdException("Invalid COLOR specification: " + colorOptions[i]); } String colorName = tokens[0]; --- 347,354 ---- return; } ! for (String colorOption : colorOptions) { ! String[] tokens = colorOption.split("#"); if (tokens.length != 2) { ! throw new RrdException("Invalid COLOR specification: " + colorOption); } String colorName = tokens[0]; Index: RrdCreateCmd.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/cmd/RrdCreateCmd.java,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** RrdCreateCmd.java 17 Feb 2005 10:43:12 -0000 1.3 --- RrdCreateCmd.java 21 Dec 2006 18:02:40 -0000 1.4 *************** *** 1,104 **** ! /* ============================================================ ! * JRobin : Pure java implementation of RRDTool's functionality ! * ============================================================ ! * ! * Project Info: http://www.jrobin.org ! * Project Lead: Sasa Markovic (sa...@jr...); ! * ! * (C) Copyright 2003, by Sasa Markovic. ! * ! * Developers: Sasa Markovic (sa...@jr...) ! * Arne Vandamme (cob...@jr...) ! * ! * This library is free software; you can redistribute it and/or modify it under the terms ! * of the GNU Lesser General Public License as published by the Free Software Foundation; ! * either version 2.1 of the License, or (at your option) any later version. ! * ! * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; ! * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. ! * See the GNU Lesser General Public License for more details. ! * ! * You should have received a copy of the GNU Lesser General Public License along with this ! * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, ! * Boston, MA 02111-1307, USA. ! */ ! ! package org.jrobin.cmd; ! ! import org.jrobin.core.RrdException; ! import org.jrobin.core.RrdDef; ! import org.jrobin.core.RrdDb; ! import org.jrobin.core.timespec.TimeParser; ! import org.jrobin.core.timespec.TimeSpec; ! ! import java.io.IOException; ! ! class RrdCreateCmd extends RrdToolCmd { ! static final String DEFAULT_START = "now-10s"; ! static final String DEFAULT_STEP = "300"; ! ! private RrdDef rrdDef; ! ! String getCmdType() { ! return "create"; ! } ! ! Object execute() throws RrdException, IOException { ! String startStr = getOptionValue("b", "start", DEFAULT_START); ! TimeSpec spec = new TimeParser(startStr).parse(); ! long start = spec.getTimestamp(); ! String stepStr = getOptionValue("s", "step", DEFAULT_STEP); ! long step = parseLong(stepStr); ! String[] words = getRemainingWords(); ! if(words.length < 2) { ! throw new RrdException("RRD file path not specified"); ! } ! String path = words[1]; ! rrdDef = new RrdDef(path, start, step); ! for(int i = 2; i < words.length; i++) { ! if(words[i].startsWith("DS:")) { ! parseDef(words[i]); ! } ! else if(words[i].startsWith("RRA:")) { ! parseRra(words[i]); ! } ! else { ! throw new RrdException("Invalid rrdcreate syntax: " + words[i]); ! } ! } ! return createRrdDb(); ! } ! ! private void parseDef(String word) throws RrdException { ! // DEF:name:type:heratbeat:min:max ! String[] tokens = word.split(":"); ! if(tokens.length < 6) { ! throw new RrdException("Invalid DS definition: " + word); ! } ! String dsName = tokens[1]; ! String dsType = tokens[2]; ! long heartbeat = parseLong(tokens[3]); ! double min = parseDouble(tokens[4]); ! double max = parseDouble(tokens[5]); ! rrdDef.addDatasource(dsName, dsType, heartbeat, min, max); ! } ! ! private void parseRra(String word) throws RrdException { ! // RRA:cfun:xff:steps:rows ! String[] tokens = word.split(":"); ! if(tokens.length < 5) { ! throw new RrdException("Invalid RRA definition: " + word); ! } ! String cf = tokens[1]; ! double xff = parseDouble(tokens[2]); ! int steps = parseInt(tokens[3]); ! int rows = parseInt(tokens[4]); ! rrdDef.addArchive(cf, xff, steps, rows); ! } ! ! private String createRrdDb() throws IOException, RrdException { ! RrdDb rrdDb = getRrdDbReference(rrdDef); ! releaseRrdDbReference(rrdDb); ! return rrdDef.getPath(); ! } ! } --- 1,102 ---- ! /* ============================================================ ! * JRobin : Pure java implementation of RRDTool's functionality ! * ============================================================ ! * ! * Project Info: http://www.jrobin.org ! * Project Lead: Sasa Markovic (sa...@jr...); ! * ! * (C) Copyright 2003-2005, by Sasa Markovic. ! * ! * Developers: Sasa Markovic (sa...@jr...) ! * ! * ! * This library is free software; you can redistribute it and/or modify it under the terms ! * of the GNU Lesser General Public License as published by the Free Software Foundation; ! * either version 2.1 of the License, or (at your option) any later version. ! * ! * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; ! * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. ! * See the GNU Lesser General Public License for more details. ! * ! * You should have received a copy of the GNU Lesser General Public License along with this ! * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, ! * Boston, MA 02111-1307, USA. ! */ ! ! package org.jrobin.cmd; ! ! import org.jrobin.core.RrdDb; ! import org.jrobin.core.RrdDef; ! import org.jrobin.core.RrdException; ! import org.jrobin.core.Util; ! ! import java.io.IOException; ! ! class RrdCreateCmd extends RrdToolCmd { ! static final String DEFAULT_START = "now-10s"; ! static final String DEFAULT_STEP = "300"; ! ! private RrdDef rrdDef; ! ! String getCmdType() { ! return "create"; ! } ! ! Object execute() throws RrdException, IOException { ! String startStr = getOptionValue("b", "start", DEFAULT_START); ! long start = Util.getTimestamp(startStr); ! String stepStr = getOptionValue("s", "step", DEFAULT_STEP); ! long step = parseLong(stepStr); ! String[] words = getRemainingWords(); ! if (words.length < 2) { ! throw new RrdException("RRD file path not specified"); ! } ! String path = words[1]; ! rrdDef = new RrdDef(path, start, step); ! for (int i = 2; i < words.length; i++) { ! if (words[i].startsWith("DS:")) { ! parseDef(words[i]); ! } ! else if (words[i].startsWith("RRA:")) { ! parseRra(words[i]); ! } ! else { ! throw new RrdException("Invalid rrdcreate syntax: " + words[i]); ! } ! } ! return createRrdDb(); ! } ! ! private void parseDef(String word) throws RrdException { ! // DEF:name:type:heratbeat:min:max ! String[] tokens = new ColonSplitter(word).split(); ! if (tokens.length < 6) { ! throw new RrdException("Invalid DS definition: " + word); ! } ! String dsName = tokens[1]; ! String dsType = tokens[2]; ! long heartbeat = parseLong(tokens[3]); ! double min = parseDouble(tokens[4]); ! double max = parseDouble(tokens[5]); ! rrdDef.addDatasource(dsName, dsType, heartbeat, min, max); ! } ! ! private void parseRra(String word) throws RrdException { ! // RRA:cfun:xff:steps:rows ! String[] tokens = new ColonSplitter(word).split(); ! if (tokens.length < 5) { ! throw new RrdException("Invalid RRA definition: " + word); ! } ! String cf = tokens[1]; ! double xff = parseDouble(tokens[2]); ! int steps = parseInt(tokens[3]); ! int rows = parseInt(tokens[4]); ! rrdDef.addArchive(cf, xff, steps, rows); ! } ! ! private String createRrdDb() throws IOException, RrdException { ! RrdDb rrdDb = getRrdDbReference(rrdDef); ! releaseRrdDbReference(rrdDb); ! return rrdDef.getPath(); ! } ! } Index: RrdCommander.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/cmd/RrdCommander.java,v retrieving revision 1.7 retrieving revision 1.8 diff -C2 -d -r1.7 -r1.8 *** RrdCommander.java 16 Jul 2004 08:01:09 -0000 1.7 --- RrdCommander.java 21 Dec 2006 18:02:40 -0000 1.8 *************** *** 1,152 **** ! /* ============================================================ ! * JRobin : Pure java implementation of RRDTool's functionality ! * ============================================================ ! * ! * Project Info: http://www.jrobin.org ! * Project Lead: Sasa Markovic (sa...@jr...); ! * ! * (C) Copyright 2003, by Sasa Markovic. ! * ! * Developers: Sasa Markovic (sa...@jr...) ! * Arne Vandamme (cob...@jr...) ! * ! * This library is free software; you can redistribute it and/or modify it under the terms ! * of the GNU Lesser General Public License as published by the Free Software Foundation; ! * either version 2.1 of the License, or (at your option) any later version. ! * ! * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; ! * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. ! * See the GNU Lesser General Public License for more details. ! * ! * You should have received a copy of the GNU Lesser General Public License along with this ! * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, ! * Boston, MA 02111-1307, USA. ! */ ! ! package org.jrobin.cmd; ! ! import org.jrobin.core.RrdException; ! ! import java.io.IOException; ! import java.io.BufferedReader; ! import java.io.InputStreamReader; ! import java.io.File; ! ! /** ! * Class to be used to execute various RRDTool commands (original syntax of RRDTool must be used). ! */ ! public class RrdCommander { ! // just add all new commands here ! private static final RrdToolCmd[] rrdCommands = { ! new RrdCreateCmd(), ! new RrdUpdateCmd(), ! new RrdLastCmd(), ! new RrdFetchCmd(), ! new RrdDumpCmd(), ! new RrdRestoreCmd(), ! new RrdXportCmd() ! }; ! ! /** ! * Checks if the output from any RRDTool command will be visible on the standard output device ! * (console). Default setting is <code>true</code>. ! * ! * @return true, if the output will be visible on the standard output device; false, otherwise. ! */ ! public static synchronized boolean isStandardOutUsed() { ! return RrdToolCmd.isStandardOutUsed(); ! } ! ! /** ! * Method used to control access to stdout (System.out, console) for all RRDTool commands. By default, ! * all RRDTool commands are allowed to print results to stdout, in a form used by RRDTool. ! * ! * @param standardOutUsed <code>true</code> if the output should be visible on the ! * standard output device, <code>false</code> otherwise. ! */ ! public static synchronized void setStandardOutUsed(boolean standardOutUsed) { ! RrdToolCmd.setStandardOutUsed(standardOutUsed); ! } ! /** ! * Checks if the class uses {@link org.jrobin.core.RrdDbPool} internally while executing ! * RRDTool commands. ! * @return true if the pool is used, false otherwise ! */ ! public static synchronized boolean isRrdDbPoolUsed() { ! return RrdToolCmd.isRrdDbPoolUsed(); ! } ! ! /** ! * Forces or prohibits {@link org.jrobin.core.RrdDbPool} usage internally while executing ! * RRDTool commands ! * @param rrdDbPoolUsed true, to force pool usage, false otherwise. ! */ ! public static synchronized void setRrdDbPoolUsed(boolean rrdDbPoolUsed) { ! RrdToolCmd.setRrdDbPoolUsed(rrdDbPoolUsed); ! } ! ! /** ! * Executes single RRDTool command. The command string should start with some ! * well known RRDTool command word (create, update, fetch, graph...)<p> ! * @param command RRDTool command like: <p> ! * <pre> ! * create test.rrd --start "noon yesterday" --step 300 DS:x:GAUGE:600:U:U RRA:0.5:5:1000 ! * update test.rrd N:1000 ! * last test.rrd ! * ... ! * </pre> ! * @return Result of specific RRDTool command. It is guaranteed that the result of any ! * successfully executed command will be always different from null. ! * Unsuccessfully executed commands will always throw ! * an exception, so you need not check for null results.<p> ! * Exact type of the result depends from the ! * type of executed RRDTool command:<p> ! * <ul> ! * <li><b>create</b>: returns java.lang.String containing path to the newly created RRD file. ! * <li><b>last</b>: returns java.lang.Long representing timestamp of the last update. ! * <li><b>update</b>: returns java.lang.Long representing timestamp of the last update. ! *<li><b>dump</b>: returns (very long) java.lang.String representing the content of a RRD file ! * in XML format. ! * <li><b>fetch</b>: returns {@link org.jrobin.core.FetchData} object representing fetched data. ! * <li><b>restore</b>: returns java.lang.String containing path to the restored RRD file. ! * </ul> ! * @throws IOException thrown in case of I/O error ! * @throws RrdException thrown for all other errors (parsing errors, ! * unknown RRDTool syntax/command/option, internal RRD errors...) ! */ ! public static synchronized Object execute(String command) throws IOException, RrdException ! { ! String cmd = command.trim(); ! for(int i = 0; i < rrdCommands.length; i++) { ! if(cmd.startsWith(rrdCommands[i].getCmdType())) { ! return rrdCommands[i].executeCommand(cmd); ! } ! } ! throw new RrdException("Unknown RRDTool command: " + command); ! } ! ! public static void main(String[] args) throws IOException { ! System.out.println("== JRobin's RRDTool commander =="); ! System.out.println("Type a RRDTool command after the dollar sign and press Enter."); ! System.out.println("Start your RRDTool command with 'create', 'update', 'fetch' etc."); ! System.out.println("Use any word starting with a dot '.' to bail out"); ! System.out.println("Current directory is: " + new File(".").getCanonicalPath()); ! System.out.println("================================"); ! RrdToolCmd.setRrdDbPoolUsed(false); ! BufferedReader r = new BufferedReader(new InputStreamReader(System.in)); ! while (true) { ! try { ! System.out.print("$ "); ! String s = r.readLine(); ! if(s.startsWith(".")) { ! return; ! } ! execute(s); ! } catch (IOException e) { ! e.printStackTrace(); ! } catch (RrdException e) { ! e.printStackTrace(); ! } ! } ! } ! } --- 1,174 ---- ! /* ============================================================ ! * JRobin : Pure java implementation of RRDTool's functionality ! * ============================================================ ! * ! * Project Info: http://www.jrobin.org ! * Project Lead: Sasa Markovic (sa...@jr...); ! * ! * (C) Copyright 2003-2005, by Sasa Markovic. ! * ! * Developers: Sasa Markovic (sa...@jr...) ! * ! * ! * This library is free software; you can redistribute it and/or modify it under the terms ! * of the GNU Lesser General Public License as published by the Free Software Foundation; ! * either version 2.1 of the License, or (at your option) any later version. ! * ! * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; ! * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. ! * See the GNU Lesser General Public License for more details. ! * ! * You should have received a copy of the GNU Lesser General Public License along with this ! * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, ! * Boston, MA 02111-1307, USA. ! */ ! ! package org.jrobin.cmd; ! ! import org.jrobin.core.RrdException; ! ! import java.io.BufferedReader; ! import java.io.File; ! import java.io.IOException; ! import java.io.InputStreamReader; ! ! /** ! * Class to be used to execute various RRDTool commands (original syntax of RRDTool 1.0.x must be used). ! * Currently supported commands are CREATE, UPDATE, LAST, FETCH, DUMP, RESTORE, XPORT, GRAPH, TUNE, INFO ! */ ! public class RrdCommander { ! private static final RrdToolCmd[] rrdCommands = { ! new RrdCreateCmd(), ! new RrdUpdateCmd(), ! new RrdLastCmd(), ! new RrdFetchCmd(), ! new RrdDumpCmd(), ! new RrdRestoreCmd(), ! new RrdXportCmd(), ! new RrdGraphCmd(), ! new RrdTuneCmd(), ! new RrdInfoCmd() ! }; ! ! /** ! * Checks if the output from any RRDTool command will be visible on the standard output device ! * (console). Default setting is <code>true</code>. ! * ! * @return true, if the output will be visible on the standard output device; false, otherwise. ! */ ! public static synchronized boolean isStandardOutUsed() { ! return RrdToolCmd.isStandardOutUsed(); ! } ! ! /** ! * Method used to control access to stdout (System.out, console) for all RRDTool commands. By default, ! * all RRDTool commands are allowed to print results to stdout, in a form used by RRDTool. ! * ! * @param standardOutUsed <code>true</code> if the output should be visible on the ! * standard output device, <code>false</code> otherwise. ! */ ! public static synchronized void setStandardOutUsed(boolean standardOutUsed) { ! RrdToolCmd.setStandardOutUsed(standardOutUsed); ! } ! ! /** ! * Checks if the class uses {@link org.jrobin.core.RrdDbPool} internally while executing ! * RRDTool commands. ! * ! * @return true if the pool is used, false otherwise ! */ ! public static synchronized boolean isRrdDbPoolUsed() { ! return RrdToolCmd.isRrdDbPoolUsed(); ! } ! ! /** ! * Forces or prohibits {@link org.jrobin.core.RrdDbPool} usage internally while executing ! * RRDTool commands ! * ! * @param rrdDbPoolUsed true, to force pool usage, false otherwise. ! */ ! public static synchronized void setRrdDbPoolUsed(boolean rrdDbPoolUsed) { ! RrdToolCmd.setRrdDbPoolUsed(rrdDbPoolUsed); ! } ! ! /** ! * Executes single RRDTool command. The command string should start with some ! * well known RRDTool command word (create, update, fetch, graph...)<p> ! * ! * @param command RRDTool command like: <p> ! * <pre> ! * create test.rrd --start "noon yesterday" --step 300 DS:x:GAUGE:600:U:U RRA:AVERAGE:0.5:5:1000 ! * update test.rrd N:1000 ! * last test.rrd ! * ... ! * </pre> ! * @return Result of specific RRDTool command. It is guaranteed that the result of any ! * successfully executed command will be always different from null. ! * Unsuccessfully executed commands will always throw ! * an exception, so you need not check for null results.<p> ! * Exact type of the result depends from the ! * type of executed RRDTool command:<p> ! * <ul> ! * <li><b>create</b>: returns java.lang.String containing path to the newly created RRD file. ! * <li><b>last</b>: returns java.lang.Long representing timestamp of the last update. ! * <li><b>update</b>: returns java.lang.Long representing timestamp of the last update. ! * <li><b>dump</b>: returns (very long) java.lang.String representing the content of a RRD file ! * in XML format. ! * <li><b>fetch</b>: returns {@link org.jrobin.core.FetchData} object representing fetched data. ! * <li><b>restore</b>: returns path to the restored RRD file. ! * <li><b>xport</b>: returns java.lang.String containing exported data ! * <li><b>graph</b>: returns {@link org.jrobin.graph.RrdGraphInfo} object containing graph info ! * <li><b>tune</b>: returns path to the tuned RRD file ! * </ul> ! * @throws IOException thrown in case of I/O error ! * @throws RrdException thrown for all other errors (parsing errors, ! * unknown RRDTool syntax/command/option, internal RRD errors...) ! */ ! public static synchronized Object execute(String command) throws IOException, RrdException { ! String cmd = command.trim(), rrdtool = "rrdtool "; ! if (cmd.startsWith(rrdtool)) { ! cmd = cmd.substring(rrdtool.length()); ! } ! for (RrdToolCmd rrdCommand : rrdCommands) { ! if (cmd.startsWith(rrdCommand.getCmdType() + " ")) { ! return rrdCommand.executeCommand(cmd); ! } ! } ! throw new RrdException("Unknown RRDTool command: " + command); ! } ! ! /** ! * A small demo which allows you to pass arbitrary RRDTool commands to JRobin ! * ! * @param args Not used ! * @throws IOException ! */ ! public static void main(String[] args) throws IOException { ! System.out.println("== JRobin's RRDTool commander =="); ! System.out.println("Type a RRDTool command after the dollar sign and press Enter."); ! System.out.println("Start your RRDTool command with 'create', 'update', 'fetch' etc."); ! System.out.println("Start line with 'create', 'update', 'fetch' etc."); ! System.out.println("Enter dot ('.') to bail out"); ! System.out.println("Current directory is: " + new File(".").getCanonicalPath()); ! System.out.println("================================"); ! RrdToolCmd.setRrdDbPoolUsed(false); ! BufferedReader r = new BufferedReader(new InputStreamReader(System.in)); ! while (true) { ! try { ! System.out.print("$ "); ! String s = r.readLine().trim(); ! if (s.length() > 0) { ! if (!s.startsWith(".")) { ! execute(s); ! } ! else { ! break; ! } ! } ! } ! catch (Exception e) { ! e.printStackTrace(System.err); ! } ! } ! } ! } Index: RrdDumpCmd.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/cmd/RrdDumpCmd.java,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** RrdDumpCmd.java 16 Jul 2004 07:40:48 -0000 1.2 --- RrdDumpCmd.java 21 Dec 2006 18:02:40 -0000 1.3 *************** *** 1,54 **** ! /* ============================================================ ! * JRobin : Pure java implementation of RRDTool's functionality ! * ============================================================ ! * ! * Project Info: http://www.jrobin.org ! * Project Lead: Sasa Markovic (sa...@jr...); ! * ! * (C) Copyright 2003, by Sasa Markovic. ! * ! * Developers: Sasa Markovic (sa...@jr...) ! * Arne Vandamme (cob...@jr...) ! * ! * This library is free software; you can redistribute it and/or modify it under the terms ! * of the GNU Lesser General Public License as published by the Free Software Foundation; ! * either version 2.1 of the License, or (at your option) any later version. ! * ! * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; ! * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. ! * See the GNU Lesser General Public License for more details. ! * ! * You should have received a copy of the GNU Lesser General Public License along with this ! * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, ! * Boston, MA 02111-1307, USA. ! */ ! ! package org.jrobin.cmd; ! ! import org.jrobin.core.RrdException; ! import org.jrobin.core.RrdDb; ! ! import java.io.IOException; ! ! class RrdDumpCmd extends RrdToolCmd { ! String getCmdType() { ! return "dump"; ! } ! ! Object execute() throws RrdException, IOException { ! String[] words = getRemainingWords(); ! if(words.length != 2) { ! throw new RrdException("Invalid rrddump syntax"); ! } ! String path = words[1]; ! RrdDb rrdDb = getRrdDbReference(path); ! try { ! String xml = rrdDb.getXml(); ! println(xml); ! return xml; ! } ! finally { ! releaseRrdDbReference(rrdDb); ! } ! } ! } --- 1,54 ---- ! /* ============================================================ ! * JRobin : Pure java implementation of RRDTool's functionality ! * ============================================================ ! * ! * Project Info: http://www.jrobin.org ! * Project Lead: Sasa Markovic (sa...@jr...); ! * ! * (C) Copyright 2003-2005, by Sasa Markovic. ! * ! * Developers: Sasa Markovic (sa...@jr...) ! * ! * ! * This library is free software; you can redistribute it and/or modify it under the terms ! * of the GNU Lesser General Public License as published by the Free Software Foundation; ! * either version 2.1 of the License, or (at your option) any later version. ! * ! * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; ! * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. ! * See the GNU Lesser General Public License for more details. ! * ! * You should have received a copy of the GNU Lesser General Public License along with this ! * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, ! * Boston, MA 02111-1307, USA. ! */ ! ! package org.jrobin.cmd; ! ! import org.jrobin.core.RrdDb; ! import org.jrobin.core.RrdException; ! ! import java.io.IOException; ! ! class RrdDumpCmd extends RrdToolCmd { ! String getCmdType() { ! return "dump"; ! } ! ! Object execute() throws RrdException, IOException { ! String[] words = getRemainingWords(); ! if (words.length != 2) { ! throw new RrdException("Invalid rrddump syntax"); ! } ! String path = words[1]; ! RrdDb rrdDb = getRrdDbReference(path); ! try { ! String xml = rrdDb.getXml(); ! println(xml); ! return xml; ! } ! finally { ! releaseRrdDbReference(rrdDb); ! } ! } ! } Index: RrdUpdateCmd.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/cmd/RrdUpdateCmd.java,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** RrdUpdateCmd.java 17 Feb 2005 10:43:12 -0000 1.2 --- RrdUpdateCmd.java 21 Dec 2006 18:02:40 -0000 1.3 *************** *** 1,89 **** ! /* ============================================================ ! * JRobin : Pure java implementation of RRDTool's functionality ! * ============================================================ ! * ! * Project Info: http://www.jrobin.org ! * Project Lead: Sasa Markovic (sa...@jr...); ! * ! * (C) Copyright 2003, by Sasa Markovic. ! * ! * Developers: Sasa Markovic (sa...@jr...) ! * Arne Vandamme (cob...@jr...) ! * ! * This library is free software; you can redistribute it and/or modify it under the terms ! * of the GNU Lesser General Public License as published by the Free Software Foundation; ! * either version 2.1 of the License, or (at your option) any later version. ! * ! * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; ! * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. ! * See the GNU Lesser General Public License for more details. ! * ! * You should have received a copy of the GNU Lesser General Public License along with this ! * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, ! * Boston, MA 02111-1307, USA. ! */ ! ! package org.jrobin.cmd; ! ! import org.jrobin.core.*; ! import org.jrobin.core.timespec.TimeParser; ! import org.jrobin.core.timespec.TimeSpec; ! ! import java.io.IOException; ! ! class RrdUpdateCmd extends RrdToolCmd { ! private String[] dsNames; ! ! String getCmdType() { ! return "update"; ! } ! ! Object execute() throws RrdException, IOException { ! String template = getOptionValue("t", "template"); ! if (template != null) { ! dsNames = template.split(":"); ! } ! String[] words = getRemainingWords(); ! if (words.length < 3) { ! throw new RrdException("Insufficent number of parameters for rrdupdate"); ! } ! String path = words[1]; ! RrdDb rrdDb = getRrdDbReference(path); ! try { ! if (dsNames != null) { ! // template specified, check datasource names ! for (int i = 0; i < dsNames.length; i++) { ! rrdDb.getDsIndex(dsNames[i]); // will throw exception if not found ! } ! } ! // parse update strings ! long timestamp = -1; ! for (int i = 2; i < words.length; i++) { ! String[] tokens = words[i].split(":"); ! if (dsNames != null && dsNames.length + 1 != tokens.length) { ! throw new RrdException("Template required " + dsNames.length + " values, " + ! (tokens.length - 1) + " value(s) found in: " + words[i]); ! } ! int dsCount = rrdDb.getHeader().getDsCount(); ! if (dsNames == null && dsCount + 1 != tokens.length) { ! throw new RrdException("Expected " + dsCount + " values, " + ! (tokens.length - 1) + " value(s) found in: " + words[i]); ! } ! TimeSpec spec = new TimeParser(tokens[0]).parse(); ! timestamp = spec.getTimestamp(); ! Sample sample = rrdDb.createSample(timestamp); ! for (int j = 1; j < tokens.length; j++) { ! if (dsNames == null) { ! sample.setValue(j - 1, parseDouble(tokens[j])); ! } else { ! sample.setValue(dsNames[j - 1], parseDouble(tokens[j])); ! } ! } ! sample.update(); ! } ! return new Long(timestamp); ! } finally { ! releaseRrdDbReference(rrdDb); ! } ! } ! } --- 1,90 ---- ! /* ============================================================ ! * JRobin : Pure java implementation of RRDTool's functionality ! * ============================================================ ! * ! * Project Info: http://www.jrobin.org ! * Project Lead: Sasa Markovic (sa...@jr...); ! * ! * (C) Copyright 2003-2005, by Sasa Markovic. ! * ! * Developers: Sasa Markovic (sa...@jr...) ! * ! * ! * This library is free software; you can redistribute it and/or modify it under the terms ! * of the GNU Lesser General Public License as published by the Free Software Foundation; ! * either version 2.1 of the License, or (at your option) any later version. ! * ! * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; ! * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. ! * See the GNU Lesser General Public License for more details. ! * ! * You should have received a copy of the GNU Lesser General Public License along with this ! * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, ! * Boston, MA 02111-1307, USA. ! */ ! ! package org.jrobin.cmd; ! ! import org.jrobin.core.RrdDb; ! import org.jrobin.core.RrdException; ! import org.jrobin.core.Sample; ! import org.jrobin.core.Util; ! ! import java.io.IOException; ! ! class RrdUpdateCmd extends RrdToolCmd { ! String getCmdType() { ! return "update"; ! } ! ! Object execute() throws RrdException, IOException { ! String template = getOptionValue("t", "template"); ! String[] dsNames = (template != null) ? new ColonSplitter(template).split() : null; ! String[] words = getRemainingWords(); ! if (words.length < 3) { ! throw new RrdException("Insufficent number of parameters for rrdupdate command"); ! } ! String path = words[1]; ! RrdDb rrdDb = getRrdDbReference(path); ! try { ! if (dsNames != null) { ! // template specified, check datasource names ! for (String dsName : dsNames) { ! if (!rrdDb.containsDs(dsName)) { ! throw new RrdException("Invalid datasource name: " + dsName); ! } ! } ! } ! // parse update strings ! long timestamp = -1; ! for (int i = 2; i < words.length; i++) { ! String[] tokens = new ColonSplitter(words[i]).split(); ! if (dsNames != null && dsNames.length + 1 != tokens.length) { ! throw new RrdException("Template requires " + dsNames.length + " values, " + ! (tokens.length - 1) + " value(s) found in: " + words[i]); ! } ! int dsCount = rrdDb.getHeader().getDsCount(); ! if (dsNames == null && dsCount + 1 != tokens.length) { ! throw new RrdException("Expected " + dsCount + " values, " + ! (tokens.length - 1) + " value(s) found in: " + words[i]); ! } ! timestamp = Util.getTimestamp(tokens[0]); ! Sample sample = rrdDb.createSample(timestamp); ! for (int j = 1; j < tokens.length; j++) { ! if (dsNames == null) { ! sample.setValue(j - 1, parseDouble(tokens[j])); ! } ! else { ! sample.setValue(dsNames[j - 1], parseDouble(tokens[j])); ! } ! } ! sample.update(); ! } ! return timestamp; ! } ! finally { ! releaseRrdDbReference(rrdDb); ! } ! } ! } ! Index: RrdLastCmd.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/cmd/RrdLastCmd.java,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** RrdLastCmd.java 16 Jul 2004 07:40:48 -0000 1.2 --- RrdLastCmd.java 21 Dec 2006 18:02:40 -0000 1.3 *************** *** 1,55 **** ! /* ============================================================ ! * JRobin : Pure java implementation of RRDTool's functionality ! * ============================================================ ! * ! * Project Info: http://www.jrobin.org ! * Project Lead: Sasa Markovic (sa...@jr...); ! * ! * (C) Copyright 2003, by Sasa Markovic. ! * ! * Developers: Sasa Markovic (sa...@jr...) ! * Arne Vandamme (cob...@jr...) ! * ! * This library is free software; you can redistribute it and/or modify it under the terms ! * of the GNU Lesser General Public License as published by the Free Software Foundation; ! * either version 2.1 of the License, or (at your option) any later version. ! * ! * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; ! * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. ! * See the GNU Lesser General Public License for more details. ! * ! * You should have received a copy of the GNU Lesser General Public License along with this ! * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, ! * Boston, MA 02111-1307, USA. ! */ ! ! package org.jrobin.cmd; ! ! import org.jrobin.core.RrdException; ! import org.jrobin.core.RrdDb; ! ! import java.io.IOException; ! ! class RrdLastCmd extends RrdToolCmd { ! ! String getCmdType() { ! return "last"; ! } ! ! Object execute() throws RrdException, IOException { ! String[] words = getRemainingWords(); ! if(words.length != 2) { ! throw new RrdException("Invalid rrdlast syntax"); ! } ! String path = words[1]; ! RrdDb rrdDb = getRrdDbReference(path); ! try { ! long lastUpdateTime = rrdDb.getLastUpdateTime(); ! println(lastUpdateTime + ""); ! return new Long(lastUpdateTime); ! } ! finally { ! releaseRrdDbReference(rrdDb); ! } ! } ! } --- 1,55 ---- ! /* ============================================================ ! * JRobin : Pure java implementation of RRDTool's functionality ! * ============================================================ ! * ! * Project Info: http://www.jrobin.org ! * Project Lead: Sasa Markovic (sa...@jr...); ! * ! * (C) Copyright 2003-2005, by Sasa Markovic. ! * ! * Developers: Sasa Markovic (sa...@jr...) ! * ! * ! * This library is free software; you can redistribute it and/or modify it under the terms ! * of the GNU Lesser General Public License as published by the Free Software Foundation; ! * either version 2.1 of the License, or (at your option) any later version. ! * ! * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; ! * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. ! * See the GNU Lesser General Public License for more details. ! * ! * You should have received a copy of the GNU Lesser General Public License along with this ! * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, ! * Boston, MA 02111-1307, USA. ! */ ! ! package org.jrobin.cmd; ! ! import org.jrobin.core.RrdDb; ! import org.jrobin.core.RrdException; ! ! import java.io.IOException; ! ! class RrdLastCmd extends RrdToolCmd { ! ! String getCmdType() { ! return "last"; ! } ! ! Object execute() throws RrdException, IOException { ! String[] words = getRemainingWords(); ! if (words.length != 2) { ! throw new RrdException("Invalid rrdlast syntax"); ! } ! String path = words[1]; ! RrdDb rrdDb = getRrdDbReference(path); ! try { ! long lastUpdateTime = rrdDb.getLastUpdateTime(); ! println(lastUpdateTime + ""); ! return lastUpdateTime; ! } ! finally { ! releaseRrdDbReference(rrdDb); ! } ! } ! } Index: RrdToolCmd.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/cmd/RrdToolCmd.java,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** RrdToolCmd.java 16 Jul 2004 08:01:13 -0000 1.5 --- RrdToolCmd.java 21 Dec 2006 18:02:40 -0000 1.6 *************** *** 1,159 **** ! /* ============================================================ ! * JRobin : Pure java implementation of RRDTool's functionality ! * ============================================================ ! * ! * Project Info: http://www.jrobin.org ! * Project Lead: Sasa Markovic (sa...@jr...); ! * ! * (C) Copyright 2003, by Sasa Markovic. ! * ! * Developers: Sasa Markovic (sa...@jr...) ! * Arne Vandamme (cob...@jr...) ! * ! * This library is free software; you can redistribute it and/or modify it under the terms ! * of the GNU Lesser General Public License as published by the Free Software Foundation; ! * either version 2.1 of the License, or (at your option) any later version. ! * ! * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; ! * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. ! * See the GNU Lesser General Public License for more details. ! * ! * You should have received a copy of the GNU Lesser General Public License along with this ! * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, ! * Boston, MA 02111-1307, USA. ! */ ! ! package org.jrobin.cmd; ! ! import org.jrobin.core.RrdException; ! import org.jrobin.core.RrdDb; ! import org.jrobin.core.RrdDbPool; ! import org.jrobin.core.RrdDef; ! ! import java.io.IOException; ! ! abstract class RrdToolCmd { ! ! private RrdCmdScanner cmdScanner; ! ! abstract String getCmdType(); ! abstract Object execute() throws RrdException, IOException; ! ! Object executeCommand(String command) throws RrdException, IOException { ! cmdScanner = new RrdCmdScanner(command); ! return execute(); ! } ! ! String getOptionValue(String shortForm, String longForm) throws RrdException { ! return cmdScanner.getOptionValue(shortForm, longForm); ! } ! ! String getOptionValue(String shortForm, String longForm, String defaultValue) throws RrdException { ! return cmdScanner.getOptionValue(shortForm, longForm, defaultValue); ! } ! ! boolean getBooleanOption(String shortForm, String longForm) { ! return cmdScanner.getBooleanOption(shortForm, longForm); ! } ! ! String[] getRemainingWords() { ! return cmdScanner.getRemainingWords(); ! } ! ! static boolean rrdDbPoolUsed = true; ! static boolean standardOutUsed = true; ! ! static boolean isRrdDbPoolUsed() { ! return rrdDbPoolUsed; ! } ! ! static void setRrdDbPoolUsed(boolean rrdDbPoolUsed) { ! RrdToolCmd.rrdDbPoolUsed = rrdDbPoolUsed; ! } ! ! static boolean isStandardOutUsed() { ! return standardOutUsed; ! } ! ! static void setStandardOutUsed(boolean standardOutUsed) { ! RrdToolCmd.standardOutUsed = standardOutUsed; ! } ! ! static long parseLong(String value) throws RrdException { ! try { ! return Long.parseLong(value); ! } ! catch(NumberFormatException nfe) { ! throw new RrdException(nfe); ! } ! } ! ! static int parseInt(String value) throws RrdException { ! try { ! return Integer.parseInt(value); ! } ! catch(NumberFormatException nfe) { ! throw new RrdException(nfe); ! } ! } ! ! static double parseDouble(String value) throws RrdException { ! if(value.equals("U")) { ! return Double.NaN; ! } ! try { ! return Double.parseDouble(value); ! } ! catch(NumberFormatException nfe) { ! throw new RrdException(nfe); ! } ! } ! ! static void print(String s) { ! if(standardOutUsed) { ! System.out.print(s); ! } ! } ! ! static void println(String s) { ! if(standardOutUsed) { ! System.out.println(s); ! } ! } ! ! static RrdDb getRrdDbReference(String path) throws IOException, RrdException { ! if(rrdDbPoolUsed) { ! return RrdDbPool.getInstance().requestRrdDb(path); ! } ! else { ! return new RrdDb(path); ! } ! } ! ! static RrdDb getRrdDbReference(String path, String xmlPath) throws IOException, RrdException { ! if(rrdDbPoolUsed) { ! return RrdDbPool.getInstance().requestRrdDb(path, xmlPath); ! } ! else { ! return new RrdDb(path, xmlPath); ! } ! } ! ! static RrdDb getRrdDbReference(RrdDef rrdDef) throws IOException, RrdException { ! if(rrdDbPoolUsed) { ! return RrdDbPool.getInstance().requestRrdDb(rrdDef); ! } ! else { ! return new RrdDb(rrdDef); ! } ! } ! ! static void releaseRrdDbReference(RrdDb rrdDb) throws IOException, RrdException { ! if(rrdDbPoolUsed) { ! RrdDbPool.getInstance().release(rrdDb); ! } ! else { ! rrdDb.close(); ! } ! } ! } --- 1,164 ---- ! /* ============================================================ ! * JRobin : Pure java implementation of RRDTool's functionality ! * ============================================================ ! * ! * Project Info: http://www.jrobin.org ! * Project Lead: Sasa Markovic (sa...@jr...); ! * ! * (C) Copyright 2003-2005, by Sasa Markovic. ! * ! * Developers: Sasa Markovic (sa...@jr...) ! * ! * ! * This library is free software; you can redistribute it and/or modify it under the terms ! * of the GNU Lesser General Public License as published by the Free Software Foundation; ! * either version 2.1 of the License, or (at your option) any later version. ! * ! * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; ! * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. ! * See the GNU Lesser General Public License for more details. ! * ! * You should have received a copy of the GNU Lesser General Public License along with this ! * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, ! * Boston, MA 02111-1307, USA. ! */ ! ! package org.jrobin.cmd; ! ! import org.jrobin.core.RrdDb; ! i... [truncated message content] |
From: Tarus B. <ta...@us...> - 2006-12-21 18:03:14
|
Update of /cvsroot/jrobin/src/org/jrobin/convertor In directory sc8-pr-cvs6.sourceforge.net:/tmp/cvs-serv9082/org/jrobin/convertor Modified Files: Convertor.java Log Message: Adding the new 1.5.4 code Index: Convertor.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/convertor/Convertor.java,v retrieving revision 1.6 retrieving revision 1.7 diff -C2 -d -r1.6 -r1.7 *** Convertor.java 9 Nov 2004 12:33:13 -0000 1.6 --- Convertor.java 21 Dec 2006 18:02:41 -0000 1.7 *************** *** 1,115 **** ! /* ============================================================ ! * JRobin : Pure java implementation of RRDTool's functionality ! * ============================================================ ! * ! * Project Info: http://www.jrobin.org ! * Project Lead: Sasa Markovic (sa...@jr...); ! * ! * (C) Copyright 2003, by Sasa Markovic. ! * ! * Developers: Sasa Markovic (sa...@jr...) ! * Arne Vandamme (cob...@jr...) ! * ! * This library is free software; you can redistribute it and/or modify it under the terms ! * of the GNU Lesser General Public License as published by the Free Software Foundation; ! * either version 2.1 of the License, or (at your option) any later version. ! * ! * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; ! * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. ! * See the GNU Lesser General Public License for more details. ! * ! * You should have received a copy of the GNU Lesser General Public License along with this ! * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, ! * Boston, MA 02111-1307, USA. ! */ ! ! package org.jrobin.convertor; ! ! import org.jrobin.core.RrdDb; ! import org.jrobin.core.RrdException; ! ! import java.io.*; ! import java.text.DecimalFormat; ! import java.util.Date; ! ! class Convertor { ! private static final String FACTORY_NAME = "FILE"; ! private static final String SUFFIX = ".jrb"; ! private static final DecimalFormat secondsFormatter = new DecimalFormat("##0.000"); ! private static final DecimalFormat countFormatter = new DecimalFormat("0000"); ! ! private String[] files; ! private int totalCount, badCount, goodCount; ! ! private Convertor(String[] files) { ! try { ! RrdDb.setDefaultFactory(FACTORY_NAME); ! } ! catch (RrdException e) { ! e.printStackTrace(); ! System.exit(-1); ! } ! this.files = files; ! } ! ! private void convertAll() { ! Date t1 = new Date(); ! final String ruler = "======================================================================="; ! println(ruler); ! println("Converting RRDTool files to JRobin native format."); ! println("Original RRDTool files will not be modified in any way"); ! println("JRobin files created during the process will have a " + SUFFIX + " suffix"); ! println(ruler); ! for(int i = 0; i < files.length; i++) { ! convertFile(files[i]); ! } ! println(ruler); ! println("Finished: " + totalCount + " total, " + ! goodCount + " OK, " + badCount + " failed"); ! Date t2 = new Date(); ! double secs = (t2.getTime() - t1.getTime()) / 1000.0; ! println("Conversion took " + secondsFormatter.format(secs) + " sec"); ! if(totalCount > 0) { ! double avgSec = secs / totalCount; ! println("Average per-file conversion time: " + secondsFormatter.format(avgSec) + " sec"); ! } ! } ! ! private void convertFile(String path) { ! long start = System.currentTimeMillis(); ! totalCount++; ! try { ! File rrdFile = new File(path); ! print(countFormatter.format(totalCount) + "/" + countFormatter.format(files.length) + ! " " + rrdFile.getName() + " "); ! String sourcePath = rrdFile.getCanonicalPath(); ! String destPath = sourcePath + SUFFIX; ! RrdDb rrd = new RrdDb(destPath, RrdDb.PREFIX_RRDTool + sourcePath); ! rrd.close(); ! goodCount++; ! double seconds = (System.currentTimeMillis() - start) / 1000.0; ! println("[OK, " + secondsFormatter.format(seconds) + " sec]"); ! } catch (Exception e) { ! badCount++; ! println("[" + e + "]"); ! } ! } ! ! private final static void println(String msg) { ! System.out.println(msg); ! } ! ! private final static void print(String msg) { ! System.out.print(msg); ! } ! ! public static void main(String[] args) { ! if(args.length == 0) { ! println("Usage : java -jar convertor.jar <RRD file pattern> ..."); ! println("Example: java -jar convertor.jar files/*.rrd"); ! System.exit(1); ! } ! Convertor c = new Convertor(args); ! c.convertAll(); ! } ! } --- 1,133 ---- ! /* ============================================================ ! * JRobin : Pure java implementation of RRDTool's functionality ! * ============================================================ ! * ! * Project Info: http://www.jrobin.org ! * Project Lead: Sasa Markovic (sa...@jr...); ! * ! * (C) Copyright 2003, by Sasa Markovic. ! * ! * Developers: Sasa Markovic (sa...@jr...) ! * ! * ! * 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.convertor; ! ! import org.jrobin.core.RrdDb; ! import org.jrobin.core.RrdException; ! ! import java.io.*; ! import java.text.DecimalFormat; ! import java.util.Date; ! ! /** ! * Simple utility class to convert RRD files created with RRDTool 1.0.x to ! * JRobin's native RRD format. Conversion process is quite fast. ! */ ! public class Convertor { ! private static final String FACTORY_NAME = "FILE"; ! private static final String SUFFIX = ".jrb"; ! private static final DecimalFormat secondsFormatter = new DecimalFormat("##0.000"); ! private static final DecimalFormat countFormatter = new DecimalFormat("0000"); ! ! private String[] files; ! private int totalCount, badCount, goodCount; ! ! private Convertor(String[] files) { ! try { ! RrdDb.setDefaultFactory(FACTORY_NAME); ! } ! catch (RrdException e) { ! e.printStackTrace(); ! System.exit(-1); ! } ! this.files = files; ! } ! ! private void convertAll() { ! Date t1 = new Date(); ! final String ruler = "======================================================================="; ! println(ruler); ! println("Converting RRDTool files to JRobin native format."); ! println("Original RRDTool files will not be modified in any way"); ! println("JRobin files created during the process will have a " + SUFFIX + " suffix"); ! println(ruler); ! for (String file : files) { ! convertFile(file); ! } ! println(ruler); ! println("Finished: " + totalCount + " total, " + ! goodCount + " OK, " + badCount + " failed"); ! Date t2 = new Date(); ! double secs = (t2.getTime() - t1.getTime()) / 1000.0; ! println("Conversion took " + secondsFormatter.format(secs) + " sec"); ! if (totalCount > 0) { ! double avgSec = secs / totalCount; ! println("Average per-file conversion time: " + secondsFormatter.format(avgSec) + " sec"); ! } ! } ! ! private void convertFile(String path) { ! long start = System.currentTimeMillis(); ! totalCount++; ! try { ! File rrdFile = new File(path); ! print(countFormatter.format(totalCount) + "/" + countFormatter.format(files.length) + ! " " + rrdFile.getName() + " "); ! String sourcePath = rrdFile.getCanonicalPath(); ! String destPath = sourcePath + SUFFIX; ! RrdDb rrd = new RrdDb(destPath, RrdDb.PREFIX_RRDTool + sourcePath); ! rrd.close(); ! goodCount++; ! double seconds = (System.currentTimeMillis() - start) / 1000.0; ! println("[OK, " + secondsFormatter.format(seconds) + " sec]"); ! } ! catch (Exception e) { ! badCount++; ! println("[" + e + "]"); ! } ! } ! ! private static void println(String msg) { ! System.out.println(msg); ! } ! ! private static void print(String msg) { ! System.out.print(msg); ! } ! ! /** ! * <p>To convert RRD files created with RRDTool use the following syntax:</p> ! * <pre> ! * java -cp jrobin-{version} org.jrobin.convertor.Convert [path to RRD file(s)] ! * <pre> ! * <p>For example:</p> ! * <pre> ! * java -cp jrobin-{version} org.jrobin.convertor.Convert rrdtool/files/*.rrd ! * </pre> ! * <p>...and enjoy the show.</p> ! * ! * @param args ! */ ! public static void main(String[] args) { ! if (args.length == 0) { ! println("Usage : java -jar convertor.jar <RRD file pattern> ..."); ! println("Example: java -jar convertor.jar files/*.rrd"); ! System.exit(1); ! } ! Convertor c = new Convertor(args); ! c.convertAll(); ! } ! } |
From: Tarus B. <ta...@us...> - 2006-12-21 18:02:52
|
Update of /cvsroot/jrobin/src/org/jrobin/demo In directory sc8-pr-cvs6.sourceforge.net:/tmp/cvs-serv9082/org/jrobin/demo Modified Files: Demo.java MinMax.java Test.java Added Files: HeartbeatFix.java Log Message: Adding the new 1.5.4 code Index: Demo.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/demo/Demo.java,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** Demo.java 25 Nov 2004 12:14:54 -0000 1.5 --- Demo.java 21 Dec 2006 18:02:43 -0000 1.6 *************** *** 1,226 **** ! /* ============================================================ ! * 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. ! */ ! ! package org.jrobin.demo; ! ! import org.jrobin.core.*; ! import org.jrobin.graph.RrdGraph; ! import org.jrobin.graph.RrdGraphDef; ! ! import java.awt.*; ! import java.io.BufferedOutputStream; ! import java.io.FileOutputStream; ! import java.io.IOException; ! import java.io.PrintWriter; ! import java.util.Random; ! ! class Demo { ! 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 { ! println("== Starting demo"); ! RrdDb.setLockMode(RrdDb.NO_LOCKS); ! long startMillis = System.currentTimeMillis(); ! if(args.length > 0) { ! println("Setting default backend factory to " + args[0]); ! RrdDb.setDefaultFactory(args[0]); ! } ! long start = START; ! long end = END; ! String rrdPath = Util.getJRobinDemoPath(FILE + ".rrd"); ! String xmlPath = Util.getJRobinDemoPath(FILE + ".xml"); ! String rrdRestoredPath = Util.getJRobinDemoPath(FILE + "_restored.rrd"); ! String pngPath = Util.getJRobinDemoPath(FILE + ".png"); ! String jpegPath = Util.getJRobinDemoPath(FILE + ".jpeg"); ! String gifPath = Util.getJRobinDemoPath(FILE + ".gif"); ! String logPath = Util.getJRobinDemoPath(FILE + ".log"); ! PrintWriter log = new PrintWriter( ! new BufferedOutputStream(new FileOutputStream(logPath, false)) ! ); ! ! // creation ! println("== Creating RRD file " + rrdPath); ! RrdDef rrdDef = new RrdDef(rrdPath, start - 1, 300); ! rrdDef.addDatasource("sun", "GAUGE", 600, 0, Double.NaN); ! rrdDef.addDatasource("shade", "GAUGE", 600, 0, Double.NaN); ! rrdDef.addArchive("AVERAGE", 0.5, 1, 600); ! rrdDef.addArchive("AVERAGE", 0.5, 6, 700); ! rrdDef.addArchive("AVERAGE", 0.5, 24, 775); ! rrdDef.addArchive("AVERAGE", 0.5, 288, 797); ! rrdDef.addArchive("MAX", 0.5, 1, 600); ! rrdDef.addArchive("MAX", 0.5, 6, 700); ! rrdDef.addArchive("MAX", 0.5, 24, 775); ! rrdDef.addArchive("MAX", 0.5, 288, 797); ! println(rrdDef.dump()); ! log.println(rrdDef.dump()); ! println("Estimated file size: " + rrdDef.getEstimatedSize()); ! RrdDb rrdDb = new RrdDb(rrdDef); ! println("== RRD file created."); ! if(rrdDb.getRrdDef().equals(rrdDef)) { ! println("Checking RRD file structure... OK"); ! } ! else { ! println("Invalid RRD file created. This is a serious bug, bailing out"); ! return; ! } ! rrdDb.close(); ! println("== RRD file closed."); ! ! // update database ! GaugeSource sunSource = new GaugeSource(1200, 20); ! GaugeSource shadeSource = new GaugeSource(300, 10); ! println("== Simulating one month of RRD file updates with step not larger than " + ! MAX_STEP + " seconds (* denotes 1000 updates)"); ! long t = start; int n = 0; ! rrdDb = new RrdDb(rrdPath); ! Sample sample = rrdDb.createSample(); ! while(t <= end + 86400L) { ! //rrdDb = new RrdDb(rrdPath); ! //Sample sample = rrdDb.createSample(); ! sample.setTime(t); ! sample.setValue("sun", sunSource.getValue()); ! sample.setValue("shade", shadeSource.getValue()); ! log.println(sample.dump()); ! sample.update(); ! t += RANDOM.nextDouble() * MAX_STEP + 1; ! if(((++n) % 1000) == 0) { ! System.out.print("*"); ! }; ! //rrdDb.close(); ! } ! println(""); ! println("== Finished. RRD file updated " + n + " times"); ! println("== Last update time was: " + rrdDb.getLastUpdateTime()); ! rrdDb.close(); ! ! // test read-only access! ! rrdDb = new RrdDb(rrdPath, true); ! println("File reopen in read-only mode"); ! ! // fetch data ! println("== Fetching data for the whole month"); ! FetchRequest request = rrdDb.createFetchRequest("AVERAGE", start, end); ! println(request.dump()); ! log.println(request.dump()); ! FetchData fetchData = request.fetchData(); ! println("== Data fetched. " + fetchData.getRowCount() + " points obtained"); ! println(fetchData.toString()); ! println("== Dumping fetched data to XML format"); ! println(fetchData.exportXml()); ! println("== Fetch completed"); ! ! // dump to XML file ! println("== Dumping RRD file to XML file " + xmlPath + " (can be restored with RRDTool)"); ! rrdDb.exportXml(xmlPath); ! println("== Creating RRD file " + rrdRestoredPath + " from XML file " + xmlPath); ! RrdDb rrdRestoredDb = new RrdDb(rrdRestoredPath, xmlPath); ! ! // close files ! println("== Closing both RRD files"); ! rrdDb.close(); ! println("== First file closed"); ! rrdRestoredDb.close(); ! println("== Second file closed"); ! ! // create graph ! println("== Creating graph from the second file"); ! RrdGraphDef gDef = new RrdGraphDef(); ! gDef.setTimePeriod(start, end); ! gDef.setTitle("Temperatures in May 2003"); ! gDef.setVerticalLabel("temperature"); ! gDef.datasource("sun", rrdRestoredPath, "sun", "AVERAGE"); ! gDef.datasource("shade", rrdRestoredPath, "shade", "AVERAGE"); ! gDef.datasource("median", "sun,shade,+,2,/"); ! gDef.datasource("diff", "sun,shade,-,ABS,-1,*"); ! gDef.datasource("sine", "TIME," + start + ",-," + (end - start) + ! ",/,2,PI,*,*,SIN,1000,*"); ! gDef.line("sun", Color.GREEN, "sun temp"); ! gDef.line("shade", Color.BLUE, "shade temp"); ! gDef.line("median", Color.MAGENTA, "median value@L"); ! gDef.area("diff", Color.YELLOW, "difference@r"); ! gDef.line("diff", Color.RED, null); ! gDef.line("sine", Color.CYAN, "sine function demo@L"); ! gDef.gprint("sun", "MAX", "maxSun = @3@s"); ! gDef.gprint("sun", "AVERAGE", "avgSun = @3@S@r"); ! gDef.gprint("shade", "MAX", "maxShade = @3@S"); ! gDef.gprint("shade", "AVERAGE", "avgShade = @3@S@r"); ! // create graph finally ! RrdGraph graph = new RrdGraph(gDef); ! println("== Graph created"); ! graph.saveAsPNG(pngPath, 400, 250); ! println("== Graph saved as a PNG file " + pngPath); ! graph.saveAsJPEG(jpegPath, 400, 250, 0.5F); ! println("== Graph saved as a JPEG file " + jpegPath); ! graph.saveAsGIF(gifPath, 400, 250); ! println("== Graph saved as a GIF file " + gifPath); ! ! // demo ends ! log.close(); ! println("== Demo completed in " + ! ((System.currentTimeMillis() - startMillis) / 1000.0) + " sec"); ! } ! ! static void println(String msg) { ! //System.out.println(msg + " " + Util.getLapTime()); ! System.out.println(msg); ! } ! ! static void print(String msg) { ! System.out.print(msg); ! } ! ! static class GaugeSource { ! private double value; ! private double step; ! ! GaugeSource(double value, double step) { ! this.value = value; ! this.step = step; ! } ! ! long getValue() { ! double oldValue = value; ! double increment = RANDOM.nextDouble() * step; ! if(RANDOM.nextDouble() > 0.5) { ! increment *= -1; ! } ! value += increment; ! if(value <= 0) { ! value = 0; ! } ! return Math.round(oldValue); ! } ! } ! } ! ! ! ! --- 1,251 ---- ! /* ============================================================ ! * JRobin : Pure java implementation of RRDTool's functionality ! * ============================================================ ! * ! * Project Info: http://www.jrobin.org ! * Project Lead: Sasa Markovic (sa...@jr...); ! * ! * (C) Copyright 2003-2005, 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...) ! * ! * ! * 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.demo; ! ! import org.jrobin.core.*; ! import org.jrobin.graph.RrdGraph; ! import org.jrobin.graph.RrdGraphDef; ! ! import java.awt.*; ! import java.io.BufferedOutputStream; ! import java.io.FileOutputStream; ! import java.io.IOException; ! import java.io.PrintWriter; ! import java.util.Random; ! ! /** ! * Simple demo just to check that everything is OK with this library. Creates two files in your ! * $HOME/jrobin-demo directory: demo.rrd and demo.png. ! */ ! public class Demo { ! 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; ! ! static final int IMG_WIDTH = 500; ! static final int IMG_HEIGHT = 300; ! ! /** ! * <p>To start the demo, use the following command:</p> ! * <pre> ! * java -cp jrobin-{version}.jar org.jrobin.demo.Demo ! * </pre> ! * ! * @param args the name of the backend factory to use (optional) ! * @throws RrdException Thrown in case of JRobin specific error ! * @throws IOException Thrown ! */ ! public static void main(String[] args) throws RrdException, IOException { ! println("== Starting demo"); ! long startMillis = System.currentTimeMillis(); ! if (args.length > 0) { ! println("Setting default backend factory to " + args[0]); ! RrdDb.setDefaultFactory(args[0]); ! } ! long start = START; ! long end = END; ! String rrdPath = Util.getJRobinDemoPath(FILE + ".rrd"); ! String xmlPath = Util.getJRobinDemoPath(FILE + ".xml"); ! String rrdRestoredPath = Util.getJRobinDemoPath(FILE + "_restored.rrd"); ! String imgPath = Util.getJRobinDemoPath(FILE + ".png"); ! String logPath = Util.getJRobinDemoPath(FILE + ".log"); ! PrintWriter log = new PrintWriter(new BufferedOutputStream(new FileOutputStream(logPath, false))); ! // creation ! println("== Creating RRD file " + rrdPath); ! RrdDef rrdDef = new RrdDef(rrdPath, start - 1, 300); ! rrdDef.addDatasource("sun", "GAUGE", 600, 0, Double.NaN); ! rrdDef.addDatasource("shade", "GAUGE", 600, 0, Double.NaN); ! rrdDef.addArchive("AVERAGE", 0.5, 1, 600); ! rrdDef.addArchive("AVERAGE", 0.5, 6, 700); ! rrdDef.addArchive("AVERAGE", 0.5, 24, 775); ! rrdDef.addArchive("AVERAGE", 0.5, 288, 797); ! rrdDef.addArchive("MAX", 0.5, 1, 600); ! rrdDef.addArchive("MAX", 0.5, 6, 700); ! rrdDef.addArchive("MAX", 0.5, 24, 775); ! rrdDef.addArchive("MAX", 0.5, 288, 797); ! println(rrdDef.dump()); ! log.println(rrdDef.dump()); ! println("Estimated file size: " + rrdDef.getEstimatedSize()); ! RrdDb rrdDb = new RrdDb(rrdDef); ! println("== RRD file created."); ! if (rrdDb.getRrdDef().equals(rrdDef)) { ! println("Checking RRD file structure... OK"); ! } ! else { ! println("Invalid RRD file created. This is a serious bug, bailing out"); ! return; ! } ! rrdDb.close(); ! println("== RRD file closed."); ! ! // update database ! GaugeSource sunSource = new GaugeSource(1200, 20); ! GaugeSource shadeSource = new GaugeSource(300, 10); ! println("== Simulating one month of RRD file updates with step not larger than " + ! MAX_STEP + " seconds (* denotes 1000 updates)"); ! long t = start; ! int n = 0; ! //rrdDb = new RrdDb(rrdPath); ! //Sample sample = rrdDb.createSample(); ! while (t <= end + 86400L) { ! rrdDb = new RrdDb(rrdPath); ! rrdDb.setInfo("T=" + t); ! Sample sample = rrdDb.createSample(); ! sample.setTime(t); ! sample.setValue("sun", sunSource.getValue()); ! sample.setValue("shade", shadeSource.getValue()); ! log.println(sample.dump()); ! sample.update(); ! t += RANDOM.nextDouble() * MAX_STEP + 1; ! if (((++n) % 1000) == 0) { ! System.out.print("*"); ! } ! rrdDb.close(); ! } ! println(""); ! println("== Finished. RRD file updated " + n + " times"); ! //rrdDb.close(); ! ! // test read-only access! ! rrdDb = new RrdDb(rrdPath, true); ! println("File reopen in read-only mode"); ! println("== Last update time was: " + rrdDb.getLastUpdateTime()); ! println("== Last info was: " + rrdDb.getInfo()); ! ! // fetch data ! println("== Fetching data for the whole month"); ! FetchRequest request = rrdDb.createFetchRequest("AVERAGE", start, end); ! println(request.dump()); ! log.println(request.dump()); ! FetchData fetchData = request.fetchData(); ! println("== Data fetched. " + fetchData.getRowCount() + " points obtained"); ! println(fetchData.toString()); ! println("== Dumping fetched data to XML format"); ! println(fetchData.exportXml()); ! println("== Fetch completed"); ! ! // dump to XML file ! println("== Dumping RRD file to XML file " + xmlPath + " (can be restored with RRDTool)"); ! rrdDb.exportXml(xmlPath); ! println("== Creating RRD file " + rrdRestoredPath + " from XML file " + xmlPath); ! RrdDb rrdRestoredDb = new RrdDb(rrdRestoredPath, xmlPath); ! ! // close files ! println("== Closing both RRD files"); ! rrdDb.close(); ! println("== First file closed"); ! rrdRestoredDb.close(); ! println("== Second file closed"); ! ! // create graph ! println("Creating graph " + Util.getLapTime()); ! println("== Creating graph from the second file"); ! RrdGraphDef gDef = new RrdGraphDef(); ! gDef.setWidth(IMG_WIDTH); ! gDef.setHeight(IMG_HEIGHT); ! gDef.setFilename(imgPath); ! gDef.setStartTime(start); ! gDef.setEndTime(end); ! gDef.setTitle("Temperatures in May 2003"); ! gDef.setVerticalLabel("temperature"); ! gDef.datasource("sun", rrdRestoredPath, "sun", "AVERAGE"); ! gDef.datasource("shade", rrdRestoredPath, "shade", "AVERAGE"); ! gDef.datasource("median", "sun,shade,+,2,/"); ! gDef.datasource("diff", "sun,shade,-,ABS,-1,*"); ! gDef.datasource("sine", "TIME," + start + ",-," + (end - start) + ! ",/,2,PI,*,*,SIN,1000,*"); ! gDef.line("sun", Color.GREEN, "sun temp"); ! gDef.line("shade", Color.BLUE, "shade temp"); ! gDef.line("median", Color.MAGENTA, "median value"); ! gDef.area("diff", Color.YELLOW, "difference\\r"); ! gDef.line("diff", Color.RED, null); ! gDef.line("sine", Color.CYAN, "sine function demo\\r"); ! gDef.hrule(2568, Color.GREEN, "hrule"); ! gDef.vrule((start + 2 * end) / 3, Color.MAGENTA, "vrule\\r"); ! gDef.gprint("sun", "MAX", "maxSun = %.3f%s"); ! gDef.gprint("sun", "AVERAGE", "avgSun = %.3f%S\\r"); ! gDef.gprint("shade", "MAX", "maxShade = %.3f%S"); ! gDef.gprint("shade", "AVERAGE", "avgShade = %.3f%S\\r"); ! gDef.print("sun", "MAX", "maxSun = %.3f%s"); ! gDef.print("sun", "AVERAGE", "avgSun = %.3f%S\\r"); ! gDef.print("shade", "MAX", "maxShade = %.3f%S"); ! gDef.print("shade", "AVERAGE", "avgShade = %.3f%S\\r"); ! gDef.setImageInfo("<img src='%s' width='%d' height = '%d'>"); ! gDef.setPoolUsed(false); ! gDef.setImageFormat("png"); ! // create graph finally ! RrdGraph graph = new RrdGraph(gDef); ! println(graph.getRrdGraphInfo().dump()); ! println("== Graph created " + Util.getLapTime()); ! // locks info ! println("== Locks info =="); ! println(RrdSafeFileBackend.getLockInfo()); ! // demo ends ! log.close(); ! println("== Demo completed in " + ! ((System.currentTimeMillis() - startMillis) / 1000.0) + " sec"); ! } ! ! static void println(String msg) { ! //System.out.println(msg + " " + Util.getLapTime()); ! System.out.println(msg); ! } ! ! static void print(String msg) { ! System.out.print(msg); ! } ! ! static class GaugeSource { ! private double value; ! private double step; ! ! GaugeSource(double value, double step) { ! this.value = value; ! this.step = step; ! } ! ! long getValue() { ! double oldValue = value; ! double increment = RANDOM.nextDouble() * step; ! if (RANDOM.nextDouble() > 0.5) { ! increment *= -1; ! } ! value += increment; ! if (value <= 0) { ! value = 0; ! } ! return Math.round(oldValue); ! } ! } ! } ! ! ! ! Index: Test.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/demo/Test.java,v retrieving revision 1.1.1.1 retrieving revision 1.2 diff -C2 -d -r1.1.1.1 -r1.2 *** Test.java 6 Sep 2005 20:40:55 -0000 1.1.1.1 --- Test.java 21 Dec 2006 18:02:43 -0000 1.2 *************** *** 1,15 **** package org.jrobin.demo; ! import org.jrobin.core.RrdToolkit; ! import org.jrobin.core.RrdException; ! import java.io.IOException; class Test { ! public static void main(String[] args) throws IOException, RrdException { ! String dir = "."; ! String[] list = RrdToolkit.getCanonicalPaths(dir, ".rrd", false); ! for (String path : list) { ! System.out.println(path); } } --- 1,28 ---- package org.jrobin.demo; ! import java.io.FileReader; ! import java.io.BufferedReader; import java.io.IOException; + class Test { ! public static final String LOADAVG_FILE = "/proc/loadavg"; ! ! public static void main(String[] args) throws IOException { ! BufferedReader r = new BufferedReader(new FileReader(LOADAVG_FILE)); ! try { ! String line = r.readLine(); ! if (line != null) { ! String[] loads = line.split("\\s+"); ! if (loads.length >= 3) { ! String load = loads[0] + " " + loads[1] + " " + loads[2]; ! System.out.println("LOAD = " + load); ! return; ! } ! System.out.println("Unexpected error while parsing file " + LOADAVG_FILE); ! } ! } ! finally { ! r.close(); } } --- NEW FILE: HeartbeatFix.java --- package org.jrobin.demo; import org.jrobin.core.RrdToolkit; import org.jrobin.core.RrdException; import org.jrobin.core.RrdDb; import java.io.FileFilter; import java.io.File; import java.io.IOException; public class HeartbeatFix { public static void main(String[] args) throws IOException, RrdException { if (args.length != 2) { System.err.println("SYNTAX: HeartbeatFix <rrd directory> <heartbeat>"); System.exit(-1); } File directory = new File(args[0]); long heartbeat = Long.parseLong(args[1]); File[] files = directory.listFiles(new FileFilter() { public boolean accept(File pathname) { return pathname.isFile() && pathname.getName().endsWith(".rrd.jrb"); } }); System.out.println(files.length + " files found"); for (int i = 0; i < files.length; i++) { String path = files[i].getAbsolutePath(); System.out.print((i + 1) + ": " + path + ": "); // fix heartbeat RrdToolkit.setDsHeartbeat(files[i].getAbsolutePath(), 0, heartbeat); RrdToolkit.setDsHeartbeat(files[i].getAbsolutePath(), 1, heartbeat); System.out.print("fixed"); // check consistency of the file RrdDb rrd = new RrdDb(path); if (rrd.getRrdDef().getEstimatedSize() == files[i].length() && rrd.getDatasource(0).getHeartbeat() == heartbeat && rrd.getDatasource(1).getHeartbeat() == heartbeat) { System.out.println(", verified"); } else { System.out.println(", ********** ERROR **********"); } rrd.close(); } System.out.println("FINISHED!"); } } Index: MinMax.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/demo/MinMax.java,v retrieving revision 1.1.1.1 retrieving revision 1.2 diff -C2 -d -r1.1.1.1 -r1.2 *** MinMax.java 6 Sep 2005 20:40:55 -0000 1.1.1.1 --- MinMax.java 21 Dec 2006 18:02:43 -0000 1.2 *************** *** 3,42 **** import org.jrobin.core.*; import org.jrobin.graph.*; import java.io.*; import java.awt.*; class MinMax { ! public static void main(String[] args) throws RrdException, IOException { ! long start = Util.getTime(), end = start + 300 * 300; ! String rrdFile = Util.getJRobinDemoPath("minmax.rrd"); String pngFile = Util.getJRobinDemoPath("minmax.png"); ! // create ! RrdDef rrdDef = new RrdDef(rrdFile, start - 1, 300); ! rrdDef.addDatasource("a", "GAUGE", 600, Double.NaN, Double.NaN); ! rrdDef.addArchive("AVERAGE", 0.5, 1, 300); ! rrdDef.addArchive("MIN", 0.5, 12, 300); ! rrdDef.addArchive("MAX", 0.5, 12, 300); ! RrdDb rrdDb = new RrdDb(rrdDef); ! // update ! for(long t = start; t < end; t += 300) { ! Sample sample = rrdDb.createSample(t); ! sample.setValue("a", Math.sin(t / 3000.0) * 50 + 50); ! sample.update(); ! } ! // graph ! RrdGraphDef gDef = new RrdGraphDef(); gDef.setFilename(pngFile); gDef.setWidth(450); gDef.setHeight(250); gDef.setImageFormat("png"); ! gDef.setTimeSpan(start, start + 86400); ! gDef.setTitle("RRDTool's MINMAX.pl demo"); ! gDef.datasource("a", rrdFile, "a", "AVERAGE"); ! gDef.datasource("b", rrdFile, "a", "MIN"); ! gDef.datasource("c", rrdFile, "a", "MAX"); ! gDef.area("a", Color.decode("0xb6e4"), "real"); ! gDef.line("b", Color.decode("0x22e9"), "min"); ! gDef.line("c", Color.decode("0xee22"), "max"); ! new RrdGraph(gDef); ! } } \ No newline at end of file --- 3,43 ---- import org.jrobin.core.*; import org.jrobin.graph.*; + import java.io.*; import java.awt.*; class MinMax { ! public static void main(String[] args) throws RrdException, IOException { ! long start = Util.getTime(), end = start + 300 * 300; ! String rrdFile = Util.getJRobinDemoPath("minmax.rrd"); String pngFile = Util.getJRobinDemoPath("minmax.png"); ! // create ! RrdDef rrdDef = new RrdDef(rrdFile, start - 1, 300); ! rrdDef.addDatasource("a", "GAUGE", 600, Double.NaN, Double.NaN); ! rrdDef.addArchive("AVERAGE", 0.5, 1, 300); ! rrdDef.addArchive("MIN", 0.5, 12, 300); ! rrdDef.addArchive("MAX", 0.5, 12, 300); ! RrdDb rrdDb = new RrdDb(rrdDef); ! // update ! for (long t = start; t < end; t += 300) { ! Sample sample = rrdDb.createSample(t); ! sample.setValue("a", Math.sin(t / 3000.0) * 50 + 50); ! sample.update(); ! } ! // graph ! RrdGraphDef gDef = new RrdGraphDef(); gDef.setFilename(pngFile); gDef.setWidth(450); gDef.setHeight(250); gDef.setImageFormat("png"); ! gDef.setTimeSpan(start, start + 86400); ! gDef.setTitle("RRDTool's MINMAX.pl demo"); ! gDef.datasource("a", rrdFile, "a", "AVERAGE"); ! gDef.datasource("b", rrdFile, "a", "MIN"); ! gDef.datasource("c", rrdFile, "a", "MAX"); ! gDef.area("a", Color.decode("0xb6e4"), "real"); ! gDef.line("b", Color.decode("0x22e9"), "min"); ! gDef.line("c", Color.decode("0xee22"), "max"); ! new RrdGraph(gDef); ! } } \ No newline at end of file |
Update of /cvsroot/jrobin/src/org/jrobin/graph In directory sc8-pr-cvs6.sourceforge.net:/tmp/cvs-serv9082/org/jrobin/graph Modified Files: Area.java CommentText.java Def.java GifEncoder.java ImageWorker.java LegendComposer.java Line.java Normalizer.java PathIterator.java PrintText.java RrdGraph.java RrdGraphConstants.java RrdGraphDef.java RrdGraphDefTemplate.java RrdGraphInfo.java Source.java Stack.java TimeAxis.java ValueAxis.java ValueAxisLogarithmic.java ValueAxisMrtg.java ValueScaler.java Added Files: CDef.java PDef.java SDef.java Log Message: Adding the new 1.5.4 code Index: ValueAxis.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/graph/ValueAxis.java,v retrieving revision 1.1.1.1 retrieving revision 1.2 diff -C2 -d -r1.1.1.1 -r1.2 *** ValueAxis.java 6 Sep 2005 20:40:55 -0000 1.1.1.1 --- ValueAxis.java 21 Dec 2006 18:02:44 -0000 1.2 *************** *** 31,47 **** class ValueAxis implements RrdGraphConstants { private static final YLab[] ylab = { ! new YLab(0.1, 1, 2, 5, 10), ! new YLab(0.2, 1, 5, 10, 20), ! new YLab(0.5, 1, 2, 4, 10), ! new YLab(1.0, 1, 2, 5, 10), ! new YLab(2.0, 1, 5, 10, 20), ! new YLab(5.0, 1, 2, 4, 10), ! new YLab(10.0, 1, 2, 5, 10), ! new YLab(20.0, 1, 5, 10, 20), ! new YLab(50.0, 1, 2, 4, 10), ! new YLab(100.0, 1, 2, 5, 10), ! new YLab(200.0, 1, 5, 10, 20), ! new YLab(500.0, 1, 2, 4, 10), ! new YLab(0.0, 0, 0, 0, 0) }; --- 31,47 ---- class ValueAxis implements RrdGraphConstants { private static final YLab[] ylab = { ! new YLab(0.1, 1, 2, 5, 10), ! new YLab(0.2, 1, 5, 10, 20), ! new YLab(0.5, 1, 2, 4, 10), ! new YLab(1.0, 1, 2, 5, 10), ! new YLab(2.0, 1, 5, 10, 20), ! new YLab(5.0, 1, 2, 4, 10), ! new YLab(10.0, 1, 2, 5, 10), ! new YLab(20.0, 1, 5, 10, 20), ! new YLab(50.0, 1, 2, 4, 10), ! new YLab(100.0, 1, 2, 5, 10), ! new YLab(200.0, 1, 5, 10, 20), ! new YLab(500.0, 1, 2, 4, 10), ! new YLab(0.0, 0, 0, 0, 0) }; *************** *** 159,166 **** } else { ! graph_label = Util.sprintf("%4.0f %c", scaledstep * i, im.symbol); } } ! int length = (int)(worker.getStringWidth(graph_label, font)); worker.drawString(graph_label, x0 - length - PADDING_VLABEL, y + labelOffset, font, fontColor); worker.drawLine(x0 - 2, y, x0 + 2, y, mGridColor, TICK_STROKE); --- 159,166 ---- } else { ! graph_label = Util.sprintf("%4.0f %c", scaledstep * i, im.symbol); } } ! int length = (int) (worker.getStringWidth(graph_label, font)); worker.drawString(graph_label, x0 - length - PADDING_VLABEL, y + labelOffset, font, fontColor); worker.drawLine(x0 - 2, y, x0 + 2, y, mGridColor, TICK_STROKE); *************** *** 184,188 **** YLab(double grid, int lfac1, int lfac2, int lfac3, int lfac4) { this.grid = grid; ! lfac = new int[]{lfac1, lfac2, lfac3, lfac4}; } } --- 184,188 ---- YLab(double grid, int lfac1, int lfac2, int lfac3, int lfac4) { this.grid = grid; ! lfac = new int[] {lfac1, lfac2, lfac3, lfac4}; } } --- NEW FILE: SDef.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...) * * * (C) Copyright 2003-2005, 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 org.jrobin.data.DataProcessor; class SDef extends Source { private String defName, consolFun; SDef(String name, String defName, String consolFun) { super(name); this.defName = defName; this.consolFun = consolFun; } void requestData(DataProcessor dproc) { dproc.addDatasource(name, defName, consolFun); } } Index: ImageWorker.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/graph/ImageWorker.java,v retrieving revision 1.1.1.1 retrieving revision 1.2 diff -C2 -d -r1.1.1.1 -r1.2 *** ImageWorker.java 6 Sep 2005 20:40:55 -0000 1.1.1.1 --- ImageWorker.java 21 Dec 2006 18:02:43 -0000 1.2 *************** *** 49,53 **** void resize(int width, int height) { ! if(gd != null) { gd.dispose(); } --- 49,53 ---- void resize(int width, int height) { ! if (gd != null) { gd.dispose(); } *************** *** 87,94 **** gd.setPaint(paint); PathIterator path = new PathIterator(yTop); ! for(int[] pos = path.getNextPath(); pos != null; pos = path.getNextPath()) { int start = pos[0], end = pos[1], n = end - start; int[] xDev = new int[n + 2], yDev = new int[n + 2]; ! for(int i = start; i < end; i++) { xDev[i - start] = (int) x[i]; yDev[i - start] = (int) yTop[i]; --- 87,94 ---- gd.setPaint(paint); PathIterator path = new PathIterator(yTop); ! for (int[] pos = path.getNextPath(); pos != null; pos = path.getNextPath()) { int start = pos[0], end = pos[1], n = end - start; int[] xDev = new int[n + 2], yDev = new int[n + 2]; ! for (int i = start; i < end; i++) { xDev[i - start] = (int) x[i]; yDev[i - start] = (int) yTop[i]; *************** *** 105,112 **** gd.setPaint(paint); PathIterator path = new PathIterator(yTop); ! for(int[] pos = path.getNextPath(); pos != null; pos = path.getNextPath()) { int start = pos[0], end = pos[1], n = end - start; int[] xDev = new int[n * 2], yDev = new int[n * 2]; ! for(int i = start; i < end; i++) { int ix1 = i - start, ix2 = n * 2 - 1 - i + start; xDev[ix1] = xDev[ix2] = (int) x[i]; --- 105,112 ---- gd.setPaint(paint); PathIterator path = new PathIterator(yTop); ! for (int[] pos = path.getNextPath(); pos != null; pos = path.getNextPath()) { int start = pos[0], end = pos[1], n = end - start; int[] xDev = new int[n * 2], yDev = new int[n * 2]; ! for (int i = start; i < end; i++) { int ix1 = i - start, ix2 = n * 2 - 1 - i + start; xDev[ix1] = xDev[ix2] = (int) x[i]; *************** *** 136,143 **** gd.setStroke(stroke); PathIterator path = new PathIterator(y); ! for(int[] pos = path.getNextPath(); pos != null; pos = path.getNextPath()) { int start = pos[0], end = pos[1]; int[] xDev = new int[end - start], yDev = new int[end - start]; ! for(int i = start; i < end; i++) { xDev[i - start] = (int) x[i]; yDev[i - start] = (int) y[i]; --- 136,143 ---- gd.setStroke(stroke); PathIterator path = new PathIterator(y); ! for (int[] pos = path.getNextPath(); pos != null; pos = path.getNextPath()) { int start = pos[0], end = pos[1]; int[] xDev = new int[end - start], yDev = new int[end - start]; ! for (int i = start; i < end; i++) { xDev[i - start] = (int) x[i]; yDev[i - start] = (int) y[i]; *************** *** 164,168 **** double getStringWidth(String text, Font font) { ! return font.getStringBounds(text, 0, text.length(), gd.getFontRenderContext()).getBounds().getWidth(); } --- 164,168 ---- double getStringWidth(String text, Font font) { ! return font.getStringBounds(text, 0, text.length(), gd.getFontRenderContext()).getBounds().getWidth(); } *************** *** 177,188 **** void saveImage(OutputStream stream, String type, float quality) throws IOException { ! if(type.equalsIgnoreCase("png")) { ImageIO.write(img, "png", stream); } ! else if(type.equalsIgnoreCase("gif")) { GifEncoder gifEncoder = new GifEncoder(img); gifEncoder.encode(stream); } ! else if(type.equalsIgnoreCase("jpg") || type.equalsIgnoreCase("jpeg")) { JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(stream); JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(img); --- 177,188 ---- void saveImage(OutputStream stream, String type, float quality) throws IOException { ! if (type.equalsIgnoreCase("png")) { ImageIO.write(img, "png", stream); } ! else if (type.equalsIgnoreCase("gif")) { GifEncoder gifEncoder = new GifEncoder(img); gifEncoder.encode(stream); } ! else if (type.equalsIgnoreCase("jpg") || type.equalsIgnoreCase("jpeg")) { JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(stream); JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(img); --- NEW FILE: CDef.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...) * * * (C) Copyright 2003-2005, 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 org.jrobin.data.DataProcessor; class CDef extends Source { private final String rpnExpression; CDef(String name, String rpnExpression) { super(name); this.rpnExpression = rpnExpression; } void requestData(DataProcessor dproc) { dproc.addDatasource(name, rpnExpression); } } Index: ValueAxisLogarithmic.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/graph/ValueAxisLogarithmic.java,v retrieving revision 1.1.1.1 retrieving revision 1.2 diff -C2 -d -r1.1.1.1 -r1.2 *** ValueAxisLogarithmic.java 6 Sep 2005 20:40:55 -0000 1.1.1.1 --- ValueAxisLogarithmic.java 21 Dec 2006 18:02:44 -0000 1.2 *************** *** 31,42 **** class ValueAxisLogarithmic implements RrdGraphConstants { private static final double[][] yloglab = { ! {1e9, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, ! {1e3, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, ! {1e1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, ! /* { 1e1, 1, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, */ ! {1e1, 1, 2.5, 5, 7.5, 0, 0, 0, 0, 0, 0, 0}, ! {1e1, 1, 2, 4, 6, 8, 0, 0, 0, 0, 0, 0}, ! {1e1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0}, ! {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} }; --- 31,42 ---- class ValueAxisLogarithmic implements RrdGraphConstants { private static final double[][] yloglab = { ! {1e9, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, ! {1e3, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, ! {1e1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, ! /* { 1e1, 1, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, */ ! {1e1, 1, 2.5, 5, 7.5, 0, 0, 0, 0, 0, 0, 0}, ! {1e1, 1, 2, 4, 6, 8, 0, 0, 0, 0, 0, 0}, ! {1e1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0}, ! {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} }; *************** *** 88,92 **** value <= im.maxval; value *= yloglab[minoridx][0]) { ! if (value < im.minval) continue; int i = 0; while (yloglab[minoridx][++i] > 0) { --- 88,94 ---- value <= im.maxval; value *= yloglab[minoridx][0]) { ! if (value < im.minval) { ! continue; ! } int i = 0; while (yloglab[minoridx][++i] > 0) { Index: ValueAxisMrtg.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/graph/ValueAxisMrtg.java,v retrieving revision 1.1.1.1 retrieving revision 1.2 diff -C2 -d -r1.1.1.1 -r1.2 *** ValueAxisMrtg.java 6 Sep 2005 20:40:55 -0000 1.1.1.1 --- ValueAxisMrtg.java 21 Dec 2006 18:02:44 -0000 1.2 *************** *** 58,62 **** } else { ! labfmt = Util.sprintf("%%4.%df", 1 - ((im.scaledstep / im.magfact > 10.0 || Math.ceil(im.scaledstep / im.magfact) == im.scaledstep / im.magfact)? 1: 0)); } if (im.symbol != ' ' || im.unit != null) { --- 58,62 ---- } else { ! labfmt = Util.sprintf("%%4.%df", 1 - ((im.scaledstep / im.magfact > 10.0 || Math.ceil(im.scaledstep / im.magfact) == im.scaledstep / im.magfact) ? 1 : 0)); } if (im.symbol != ' ' || im.unit != null) { *************** *** 73,77 **** if (y >= im.yorigin - im.ysize && y <= im.yorigin) { String graph_label = Util.sprintf(labfmt, im.scaledstep / im.magfact * (i - im.quadrant)); ! int length = (int)(worker.getStringWidth(graph_label, font)); worker.drawString(graph_label, xLeft - length - PADDING_VLABEL, y + labelOffset, font, fontColor); worker.drawLine(xLeft - 2, y, xLeft + 2, y, mGridColor, TICK_STROKE); --- 73,77 ---- if (y >= im.yorigin - im.ysize && y <= im.yorigin) { String graph_label = Util.sprintf(labfmt, im.scaledstep / im.magfact * (i - im.quadrant)); ! int length = (int) (worker.getStringWidth(graph_label, font)); worker.drawString(graph_label, xLeft - length - PADDING_VLABEL, y + labelOffset, font, fontColor); worker.drawLine(xLeft - 2, y, xLeft + 2, y, mGridColor, TICK_STROKE); Index: Def.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/graph/Def.java,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** Def.java 9 Jul 2004 12:22:15 -0000 1.3 --- Def.java 21 Dec 2006 18:02:43 -0000 1.4 *************** *** 1,66 **** ! /* ============================================================ ! * 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; ! ! /** ! * <p>Represents a fetched datasource for a graph. A Def collects all his datavalues from an existing ! * RRD file.</p> ! * ! * @author Arne Vandamme (cob...@jr...) ! */ ! class Def extends Source ! { ! // ================================================================ ! // -- Constructors ! // ================================================================ ! /** ! * Constructs a new Def object holding a number of fetched datapoints for a graph. ! * @param name Name of the datasource in the graph definition. ! * @param numPoints Number of points used as graph resolution (size of the value table). ! */ ! Def( String name, int numPoints, int aggregatePoints ) ! { ! super(name); ! values = new double[ numPoints ]; ! this.aggregatePoints = aggregatePoints; ! } ! ! ! // ================================================================ ! // -- Protected methods ! // ================================================================ ! /** ! * Sets the value of a specific datapoint for this Def. ! * @param pos Position (index in the value table) of the new datapoint. ! * @param timestamp Timestamp of the new datapoint in number of seconds. ! * @param val Double value of the new datapoint. ! */ ! void set( int pos, long timestamp, double val ) ! { ! super.set( pos, timestamp, val ); ! values[pos] = val; ! } ! ! } --- 1,53 ---- ! /* ============================================================ ! * 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...) ! * ! * ! * (C) Copyright 2003-2005, 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 org.jrobin.data.DataProcessor; ! ! class Def extends Source { ! private final String rrdPath, dsName, consolFun, backend; ! ! Def(String name, String rrdPath, String dsName, String consolFun) { ! this(name, rrdPath, dsName, consolFun, null); ! } ! ! Def(String name, String rrdPath, String dsName, String consolFun, String backend) { ! super(name); ! this.rrdPath = rrdPath; ! this.dsName = dsName; ! this.consolFun = consolFun; ! this.backend = backend; ! } ! ! void requestData(DataProcessor dproc) { ! if (backend == null) { ! dproc.addDatasource(name, rrdPath, dsName, consolFun); ! } ! else { ! dproc.addDatasource(name, rrdPath, dsName, consolFun, backend); ! } ! } ! } Index: RrdGraphConstants.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/graph/RrdGraphConstants.java,v retrieving revision 1.1.1.1 retrieving revision 1.2 diff -C2 -d -r1.1.1.1 -r1.2 *** RrdGraphConstants.java 6 Sep 2005 20:40:55 -0000 1.1.1.1 --- RrdGraphConstants.java 21 Dec 2006 18:02:44 -0000 1.2 *************** *** 33,192 **** */ public interface RrdGraphConstants { ! /** Default graph starting time */ String DEFAULT_START = "end-1d"; ! /** Default graph ending time */ String DEFAULT_END = "now"; ! /** Constant to represent second */ int SECOND = Calendar.SECOND; ! /** Constant to represent minute */ int MINUTE = Calendar.MINUTE; ! /** Constant to represent hour */ int HOUR = Calendar.HOUR_OF_DAY; ! /** Constant to represent day */ int DAY = Calendar.DAY_OF_MONTH; ! /** Constant to represent week */ int WEEK = Calendar.WEEK_OF_YEAR; ! /** Constant to represent month */ int MONTH = Calendar.MONTH; ! /** Constant to represent year */ int YEAR = Calendar.YEAR; ! /** Constant to represent Monday */ int MONDAY = Calendar.MONDAY; ! /** Constant to represent Tuesday */ int TUESDAY = Calendar.TUESDAY; ! /** Constant to represent Wednesday */ int WEDNESDAY = Calendar.WEDNESDAY; ! /** Constant to represent Thursday */ int THURSDAY = Calendar.THURSDAY; ! /** Constant to represent Friday */ int FRIDAY = Calendar.FRIDAY; ! /** Constant to represent Saturday */ int SATURDAY = Calendar.SATURDAY; ! /** Constant to represent Sunday */ int SUNDAY = Calendar.SUNDAY; ! /** Index of the canvas color. Used in {@link RrdGraphDef#setColor(int, java.awt.Paint)} */ int COLOR_CANVAS = 0; ! /** Index of the background color. Used in {@link RrdGraphDef#setColor(int, java.awt.Paint)} */ int COLOR_BACK = 1; ! /** Index of the top-left graph shade color. Used in {@link RrdGraphDef#setColor(int, java.awt.Paint)} */ int COLOR_SHADEA = 2; ! /** Index of the bottom-right graph shade color. Used in {@link RrdGraphDef#setColor(int, java.awt.Paint)} */ int COLOR_SHADEB = 3; ! /** Index of the minor grid color. Used in {@link RrdGraphDef#setColor(int, java.awt.Paint)} */ int COLOR_GRID = 4; ! /** Index of the major grid color. Used in {@link RrdGraphDef#setColor(int, java.awt.Paint)} */ int COLOR_MGRID = 5; ! /** Index of the font color. Used in {@link RrdGraphDef#setColor(int, java.awt.Paint)} */ int COLOR_FONT = 6; ! /** Index of the frame color. Used in {@link RrdGraphDef#setColor(int, java.awt.Paint)} */ int COLOR_FRAME = 7; ! /** Index of the arrow color. Used in {@link RrdGraphDef#setColor(int, java.awt.Paint)} */ int COLOR_ARROW = 8; ! /** Allowed color names which can be used in {@link RrdGraphDef#setColor(String, java.awt.Paint)} method */ String[] COLOR_NAMES = { ! "canvas", "back", "shadea", "shadeb", "grid", "mgrid", "font", "frame", "arrow" }; ! /** Default first day of the week (obtained from the default locale) */ int FIRST_DAY_OF_WEEK = Calendar.getInstance(Locale.getDefault()).getFirstDayOfWeek(); ! /** Default graph canvas color */ Color DEFAULT_CANVAS_COLOR = Color.WHITE; ! /** Default graph background color */ Color DEFAULT_BACK_COLOR = new Color(245, 245, 245); ! /** Default top-left graph shade color */ Color DEFAULT_SHADEA_COLOR = new Color(200, 200, 200); ! /** Default bottom-right graph shade color */ Color DEFAULT_SHADEB_COLOR = new Color(150, 150, 150); ! /** Default minor grid color */ Color DEFAULT_GRID_COLOR = new Color(140, 140, 140); ! /** Default major grid color */ Color DEFAULT_MGRID_COLOR = new Color(130, 30, 30); ! /** Default font color */ Color DEFAULT_FONT_COLOR = Color.BLACK; ! /** Default frame color */ Color DEFAULT_FRAME_COLOR = Color.BLACK; ! /** Default arrow color */ Color DEFAULT_ARROW_COLOR = Color.RED; ! /** Constant to represent left alignment marker */ String ALIGN_LEFT_MARKER = "\\l"; ! /** Constant to represent centered alignment marker */ String ALIGN_CENTER_MARKER = "\\c"; ! /** Constant to represent right alignment marker */ String ALIGN_RIGHT_MARKER = "\\r"; ! /** Constant to represent justified alignment marker */ String ALIGN_JUSTIFIED_MARKER = "\\j"; ! /** Constant to represent "glue" marker */ String GLUE_MARKER = "\\g"; ! /** Constant to represent vertical spacing marker */ String VERTICAL_SPACING_MARKER = "\\s"; ! /** Constant to represent no justification markers */ String NO_JUSTIFICATION_MARKER = "\\J"; ! /** Used internally */ String[] MARKERS = { ! ALIGN_LEFT_MARKER, ALIGN_CENTER_MARKER, ALIGN_RIGHT_MARKER, ! ALIGN_JUSTIFIED_MARKER, GLUE_MARKER, VERTICAL_SPACING_MARKER, NO_JUSTIFICATION_MARKER }; ! /** Constant to represent in-memory image name */ String IN_MEMORY_IMAGE = "-"; ! /** Default units length */ int DEFAULT_UNITS_LENGTH = 9; ! /** Default graph width */ int DEFAULT_WIDTH = 400; ! /** Default graph height */ int DEFAULT_HEIGHT = 100; ! /** Default image format */ String DEFAULT_IMAGE_FORMAT = "gif"; ! /** Default image quality, used only for jpeg graphs */ float DEFAULT_IMAGE_QUALITY = 0.8F; // only for jpegs, not used for png/gif ! /** Default value base */ double DEFAULT_BASE = 1000; ! /** Default font name, determined based on the current operating system */ String DEFAULT_FONT_NAME = System.getProperty("os.name").toLowerCase().contains("windows") ? "Lucida Sans Typewriter" : "Monospaced"; ! /** Default graph small font */ Font DEFAULT_SMALL_FONT = new Font(DEFAULT_FONT_NAME, Font.PLAIN, 10); ! /** Default graph large font */ Font DEFAULT_LARGE_FONT = new Font(DEFAULT_FONT_NAME, Font.BOLD, 12); ! /** Used internally */ double LEGEND_LEADING = 1.2; // chars ! /** Used internally */ double LEGEND_LEADING_SMALL = 0.7; // chars ! /** Used internally */ double LEGEND_BOX_SPACE = 1.2; // chars ! /** Used internally */ double LEGEND_BOX = 0.9; // chars ! /** Used internally */ int LEGEND_INTERSPACING = 2; // chars ! /** Used internally */ int PADDING_LEFT = 10; // pix ! /** Used internally */ int PADDING_TOP = 12; // pix ! /** Used internally */ int PADDING_TITLE = 6; // pix ! /** Used internally */ int PADDING_RIGHT = 16; // pix ! /** Used internally */ int PADDING_PLOT = 2; //chars ! /** Used internally */ int PADDING_LEGEND = 2; // chars ! /** Used internally */ int PADDING_BOTTOM = 6; // pix ! /** Used internally */ int PADDING_VLABEL = 7; // pix ! /** Stroke used to draw grid */ Stroke GRID_STROKE = new BasicStroke(1, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 1, new float[] {1, 1}, 0); ! /** Stroke used to draw ticks */ Stroke TICK_STROKE = new BasicStroke(1); } --- 33,330 ---- */ public interface RrdGraphConstants { ! /** ! * Default graph starting time ! */ String DEFAULT_START = "end-1d"; ! /** ! * Default graph ending time ! */ String DEFAULT_END = "now"; ! /** ! * Constant to represent second ! */ int SECOND = Calendar.SECOND; ! /** ! * Constant to represent minute ! */ int MINUTE = Calendar.MINUTE; ! /** ! * Constant to represent hour ! */ int HOUR = Calendar.HOUR_OF_DAY; ! /** ! * Constant to represent day ! */ int DAY = Calendar.DAY_OF_MONTH; ! /** ! * Constant to represent week ! */ int WEEK = Calendar.WEEK_OF_YEAR; ! /** ! * Constant to represent month ! */ int MONTH = Calendar.MONTH; ! /** ! * Constant to represent year ! */ int YEAR = Calendar.YEAR; ! /** ! * Constant to represent Monday ! */ int MONDAY = Calendar.MONDAY; ! /** ! * Constant to represent Tuesday ! */ int TUESDAY = Calendar.TUESDAY; ! /** ! * Constant to represent Wednesday ! */ int WEDNESDAY = Calendar.WEDNESDAY; ! /** ! * Constant to represent Thursday ! */ int THURSDAY = Calendar.THURSDAY; ! /** ! * Constant to represent Friday ! */ int FRIDAY = Calendar.FRIDAY; ! /** ! * Constant to represent Saturday ! */ int SATURDAY = Calendar.SATURDAY; ! /** ! * Constant to represent Sunday ! */ int SUNDAY = Calendar.SUNDAY; ! /** ! * Index of the canvas color. Used in {@link RrdGraphDef#setColor(int, java.awt.Paint)} ! */ int COLOR_CANVAS = 0; ! /** ! * Index of the background color. Used in {@link RrdGraphDef#setColor(int, java.awt.Paint)} ! */ int COLOR_BACK = 1; ! /** ! * Index of the top-left graph shade color. Used in {@link RrdGraphDef#setColor(int, java.awt.Paint)} ! */ int COLOR_SHADEA = 2; ! /** ! * Index of the bottom-right graph shade color. Used in {@link RrdGraphDef#setColor(int, java.awt.Paint)} ! */ int COLOR_SHADEB = 3; ! /** ! * Index of the minor grid color. Used in {@link RrdGraphDef#setColor(int, java.awt.Paint)} ! */ int COLOR_GRID = 4; ! /** ! * Index of the major grid color. Used in {@link RrdGraphDef#setColor(int, java.awt.Paint)} ! */ int COLOR_MGRID = 5; ! /** ! * Index of the font color. Used in {@link RrdGraphDef#setColor(int, java.awt.Paint)} ! */ int COLOR_FONT = 6; ! /** ! * Index of the frame color. Used in {@link RrdGraphDef#setColor(int, java.awt.Paint)} ! */ int COLOR_FRAME = 7; ! /** ! * Index of the arrow color. Used in {@link RrdGraphDef#setColor(int, java.awt.Paint)} ! */ int COLOR_ARROW = 8; ! /** ! * Allowed color names which can be used in {@link RrdGraphDef#setColor(String, java.awt.Paint)} method ! */ String[] COLOR_NAMES = { ! "canvas", "back", "shadea", "shadeb", "grid", "mgrid", "font", "frame", "arrow" }; ! /** ! * Default first day of the week (obtained from the default locale) ! */ int FIRST_DAY_OF_WEEK = Calendar.getInstance(Locale.getDefault()).getFirstDayOfWeek(); ! /** ! * Default graph canvas color ! */ Color DEFAULT_CANVAS_COLOR = Color.WHITE; ! /** ! * Default graph background color ! */ Color DEFAULT_BACK_COLOR = new Color(245, 245, 245); ! /** ! * Default top-left graph shade color ! */ Color DEFAULT_SHADEA_COLOR = new Color(200, 200, 200); ! /** ! * Default bottom-right graph shade color ! */ Color DEFAULT_SHADEB_COLOR = new Color(150, 150, 150); ! /** ! * Default minor grid color ! */ Color DEFAULT_GRID_COLOR = new Color(140, 140, 140); ! /** ! * Default major grid color ! */ Color DEFAULT_MGRID_COLOR = new Color(130, 30, 30); ! /** ! * Default font color ! */ Color DEFAULT_FONT_COLOR = Color.BLACK; ! /** ! * Default frame color ! */ Color DEFAULT_FRAME_COLOR = Color.BLACK; ! /** ! * Default arrow color ! */ Color DEFAULT_ARROW_COLOR = Color.RED; ! /** ! * Constant to represent left alignment marker ! */ String ALIGN_LEFT_MARKER = "\\l"; ! /** ! * Constant to represent centered alignment marker ! */ String ALIGN_CENTER_MARKER = "\\c"; ! /** ! * Constant to represent right alignment marker ! */ String ALIGN_RIGHT_MARKER = "\\r"; ! /** ! * Constant to represent justified alignment marker ! */ String ALIGN_JUSTIFIED_MARKER = "\\j"; ! /** ! * Constant to represent "glue" marker ! */ String GLUE_MARKER = "\\g"; ! /** ! * Constant to represent vertical spacing marker ! */ String VERTICAL_SPACING_MARKER = "\\s"; ! /** ! * Constant to represent no justification markers ! */ String NO_JUSTIFICATION_MARKER = "\\J"; ! /** ! * Used internally ! */ String[] MARKERS = { ! ALIGN_LEFT_MARKER, ALIGN_CENTER_MARKER, ALIGN_RIGHT_MARKER, ! ALIGN_JUSTIFIED_MARKER, GLUE_MARKER, VERTICAL_SPACING_MARKER, NO_JUSTIFICATION_MARKER }; ! /** ! * Constant to represent in-memory image name ! */ String IN_MEMORY_IMAGE = "-"; ! /** ! * Default units length ! */ int DEFAULT_UNITS_LENGTH = 9; ! /** ! * Default graph width ! */ int DEFAULT_WIDTH = 400; ! /** ! * Default graph height ! */ int DEFAULT_HEIGHT = 100; ! /** ! * Default image format ! */ String DEFAULT_IMAGE_FORMAT = "gif"; ! /** ! * Default image quality, used only for jpeg graphs ! */ float DEFAULT_IMAGE_QUALITY = 0.8F; // only for jpegs, not used for png/gif ! /** ! * Default value base ! */ double DEFAULT_BASE = 1000; ! /** ! * Default font name, determined based on the current operating system ! */ String DEFAULT_FONT_NAME = System.getProperty("os.name").toLowerCase().contains("windows") ? "Lucida Sans Typewriter" : "Monospaced"; ! /** ! * Default graph small font ! */ Font DEFAULT_SMALL_FONT = new Font(DEFAULT_FONT_NAME, Font.PLAIN, 10); ! /** ! * Default graph large font ! */ Font DEFAULT_LARGE_FONT = new Font(DEFAULT_FONT_NAME, Font.BOLD, 12); ! /** ! * Used internally ! */ double LEGEND_LEADING = 1.2; // chars ! /** ! * Used internally ! */ double LEGEND_LEADING_SMALL = 0.7; // chars ! /** ! * Used internally ! */ double LEGEND_BOX_SPACE = 1.2; // chars ! /** ! * Used internally ! */ double LEGEND_BOX = 0.9; // chars ! /** ! * Used internally ! */ int LEGEND_INTERSPACING = 2; // chars ! /** ! * Used internally ! */ int PADDING_LEFT = 10; // pix ! /** ! * Used internally ! */ int PADDING_TOP = 12; // pix ! /** ! * Used internally ! */ int PADDING_TITLE = 6; // pix ! /** ! * Used internally ! */ int PADDING_RIGHT = 16; // pix ! /** ! * Used internally ! */ int PADDING_PLOT = 2; //chars ! /** ! * Used internally ! */ int PADDING_LEGEND = 2; // chars ! /** ! * Used internally ! */ int PADDING_BOTTOM = 6; // pix ! /** ! * Used internally ! */ int PADDING_VLABEL = 7; // pix ! /** ! * Stroke used to draw grid ! */ Stroke GRID_STROKE = new BasicStroke(1, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 1, new float[] {1, 1}, 0); ! /** ! * Stroke used to draw ticks ! */ Stroke TICK_STROKE = new BasicStroke(1); } Index: GifEncoder.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/graph/GifEncoder.java,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** GifEncoder.java 7 Nov 2003 09:53:35 -0000 1.2 --- GifEncoder.java 21 Dec 2006 18:02:43 -0000 1.3 *************** *** 1,692 **** ! /* ============================================================ ! * 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...) ! * [...1399 lines suppressed...] ! return ciPixels; ! } ! } ! ! ! final class Put { ! static void ascii(String s, OutputStream os) throws IOException { ! byte[] bytes = new byte[s.length()]; ! for (int i = 0; i < bytes.length; ++i) { ! bytes[i] = (byte) s.charAt(i); ! } ! os.write(bytes); ! } ! ! static void leShort(int i16, OutputStream os) throws IOException { ! os.write(i16 & 0xff); ! os.write(i16 >> 8 & 0xff); ! } } \ No newline at end of file Index: Source.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/graph/Source.java,v retrieving revision 1.15 retrieving revision 1.16 diff -C2 -d -r1.15 -r1.16 *** Source.java 23 Jan 2005 20:31:26 -0000 1.15 --- Source.java 21 Dec 2006 18:02:44 -0000 1.16 *************** *** 1,261 **** ! /* ============================================================ ! * 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 org.jrobin.core.Util; ! ! /** ! * <p>Class used to represent a number of datapoints for a graph.</p> ! * ! * @author Arne Vandamme (cob...@jr...) ! */ ! class Source ! { ! // ================================================================ ! // -- Members ! // ================================================================ ! protected static final int AGG_MINIMUM = 0; ! protected static final int AGG_MAXIMUM = 1; ! protected static final int AGG_AVERAGE = 2; ! protected static final int AGG_FIRST = 3; ! protected static final int AGG_LAST = 4; ! protected static final int AGG_TOTAL = 5; ! ! protected static final String[] aggregates = { "MINIMUM", "MAXIMUM", "AVERAGE", "FIRST", "LAST", "TOTAL" }; ! private String name; ! ! protected int aggregatePoints; ! protected double[] values; ! ! private double min = Double.NaN; ! private double max = Double.NaN; ! private double totalValue = 0; ! private double nextValue = Double.POSITIVE_INFINITY; ! ! protected long step = 0; ! private long lastPreciseTime = 0; // Last time requested ! private long lastTime = 0; ! private long totalTime = 0; ! ! private long startTime, endTime; ! ! private int stPos = 0; ! private int lastStPos = 0; // Last value position requested ! ! // ================================================================ ! // -- Constructors ! // ================================================================ ! /** ! * Constructs a new Source object holding a number of datapoints for a graph. ! * @param name Name of the datasource in the graph definition. ! */ ! Source( String name ) ! { ! this.name = name; ! } ! ! // ================================================================ ! // -- Protected methods ! // ================================================================ ! /** ! * Stub method, sets the value of a specific datapoint. ! * Forces this point to be used in aggregate function calculating. ! * @param pos Position (index in the value table) of the new datapoint. ! * @param time Timestamp of the new datapoint in number of seconds. ! * @param val Double value of the new datapoint. ! */ ! void set( int pos, long time, double val ) ! { ! // The first sample is before the time range we want, and as such ! // should not be counted for data aggregation ! if ( pos < aggregatePoints ) ! aggregate( time, val ); ! } ! ! void setFetchSettings( long step, long startTime, long endTime ) ! { ! this.step = step; ! this.startTime = startTime; ! this.endTime = endTime; ! } ! ! long getStep() { ! return step; ! } ! ! /** ! * Get the double value of a datapoint. ! * ! * @param pos Index in the value table of the datapoint. ! * @return The double value of the requested datapoint. ! */ ! double get( int pos ) ! { ! if ( pos < 0 ) ! return Double.NaN; ! if ( pos > values.length ) ! return Double.NaN; ! ! double val = values[pos]; ! ! if ( Double.isInfinite(val) ) ! { ! // Return the next value if we fetched it before ! if ( !Double.isInfinite(nextValue) && pos >= lastStPos ) ! return nextValue; ! ! lastStPos = pos; ! ! // Try to fetch the next value ! for ( int i = pos + 1; i < values.length; i++ ) ! { ! if ( !Double.isInfinite(values[i]) ) ! { ! nextValue = values[i]; ! ! return nextValue; ! } ! } ! ! // No more next value ! nextValue = Double.NaN; ! ! return nextValue; ! } ! else ! nextValue = Double.POSITIVE_INFINITY; ! ! lastStPos = pos; ! ! return values[pos]; ! } ! ! double get( long preciseTime, long[] reducedTimestamps ) ! { ! long t = Util.normalize( preciseTime, step ); ! t = ( t < preciseTime ? t + step : t ); ! ! if ( preciseTime < lastPreciseTime ) // Backward fetching is weird, start over, we're prolly in a new iteration ! stPos = 0; ! ! lastPreciseTime = preciseTime; ! ! while ( stPos < reducedTimestamps.length - 1 ) ! { ! if ( reducedTimestamps[ stPos + 1 ] <= t ) ! stPos++; ! else ! return get( stPos ); ! } ! ! if ( t <= reducedTimestamps[stPos] ) ! return get( stPos ); ! ! return Double.NaN; ! } ! ! /** ! * Gets a specific aggregate of this datasource. ! * Requested aggregate can be one of the following: ! * <code>AGG_MINIMUM, AGG_MAXIMUM, AGG_AVERAGE, AGG_FIRST, AGG_TOTAL</code> ! * and <code>AGG_LAST</code>. ! * @param aggType Type of the aggregate requested. ! * @return The double value of the requested aggregate. ! */ ! double getAggregate( int aggType ) ! { ! switch ( aggType ) ! { ! case AGG_MINIMUM: ! return min; ! ! case AGG_MAXIMUM: ! return max; ! ! case AGG_AVERAGE: ! if ( totalTime > 0 ) ! return totalValue / totalTime; ! break; ! ! case AGG_FIRST: ! if ( values != null && values.length > 0) ! return values[ values.length > 1 ? 1 : 0 ]; ! break; ! ! case AGG_LAST: ! if ( values != null && values.length > 0) ! return values[values.length - 1]; ! break; ! ! case AGG_TOTAL: ! return totalValue; ! } ! ! return Double.NaN; ! } ! ! String getName() { ! return name; ! } ! ! double[] getValues() { ! return values; ! } ! ! long getSampleCount() { ! return ( values != null ? values.length : 0 ); ! } ! ! ! // ================================================================ ! // -- Private methods ! // ================================================================ ! /** ! * Adds a datapoint to the aggregate function calculation. ! * @param time Timestamp in seconds of the datapoint. ! * @param value Double value of the datapoint. ! */ ! private void aggregate( long time, double value ) ! { ! if ( Double.isInfinite(value) ) ! return; ! ! if ( time > endTime ) ! time = endTime; ! ! if ( lastTime > 0 && !Double.isNaN(value) && value != Util.MIN_DOUBLE && value != Util.MAX_DOUBLE ) ! { ! min = Util.min( min, value ); ! max = Util.max( max, value ); ! ! long timeDelta = time - lastTime; ! ! totalValue += timeDelta * value; ! totalTime += timeDelta; ! } ! ! lastTime = ( time < startTime ? startTime : time ); ! } ! } --- 1,37 ---- ! /* ============================================================ ! * 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...) ! * ! * ! * (C) Copyright 2003-2005, 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 org.jrobin.data.DataProcessor; ! ! abstract class Source { ! final String name; ! ! Source(String name) { ! this.name = name; ! } ! ! abstract void requestData(DataProcessor dproc); ! } Index: TimeAxis.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/graph/TimeAxis.java,v retrieving revision 1.1.1.1 retrieving revision 1.2 diff -C2 -d -r1.1.1.1 -r1.2 *** TimeAxis.java 6 Sep 2005 20:40:55 -0000 1.1.1.1 --- TimeAxis.java 21 Dec 2006 18:02:44 -0000 1.2 *************** *** 33,51 **** class TimeAxis implements RrdGraphConstants { private static final TimeAxisSetting[] tickSettings = { ! new TimeAxisSetting(0, SECOND, 30, MINUTE, 5, MINUTE, 5, 0, "HH:mm"), ! new TimeAxisSetting(2, MINUTE, 1, MINUTE, 5, MINUTE, 5, 0, "HH:mm"), ! new TimeAxisSetting(5, MINUTE, 2, MINUTE, 10, MINUTE, 10, 0, "HH:mm"), ! new TimeAxisSetting(10, MINUTE, 5, MINUTE, 20, MINUTE, 20, 0, "HH:mm"), ! new TimeAxisSetting(30, MINUTE, 10, HOUR, 1, HOUR, 1, 0, "HH:mm"), ! new TimeAxisSetting(60, MINUTE, 30, HOUR, 2, HOUR, 2, 0, "HH:mm"), ! new TimeAxisSetting(180, HOUR, 1, HOUR, 6, HOUR, 6, 0, "HH:mm"), ! new TimeAxisSetting(600, HOUR, 6, DAY, 1, DAY, 1, 24 * 3600, "EEE"), ! new TimeAxisSetting(1800, HOUR, 12, DAY, 1, DAY, 2, 24 * 3600, "EEE"), ! new TimeAxisSetting(3600, DAY, 1, WEEK, 1, WEEK, 1, 7 * 24 * 3600, "'Week 'w"), ! new TimeAxisSetting(3 * 3600, WEEK, 1, MONTH, 1, WEEK, 2, 7 * 24 * 3600, "'Week 'w"), ! new TimeAxisSetting(6 * 3600, MONTH, 1, MONTH, 1, MONTH, 1, 30 * 24 * 3600, "MMM"), ! new TimeAxisSetting(48 * 3600, MONTH, 1, MONTH, 3, MONTH, 3, 30 * 24 * 3600, "MMM"), ! new TimeAxisSetting(10 * 24 * 3600, YEAR, 1, YEAR, 1, YEAR, 1, 365 * 24 * 3600, "yy"), ! new TimeAxisSetting(-1, MONTH, 0, MONTH, 0, MONTH, 0, 0, "") }; --- 33,51 ---- class TimeAxis implements RrdGraphConstants { private static final TimeAxisSetting[] tickSettings = { ! new TimeAxisSetting(0, SECOND, 30, MINUTE, 5, MINUTE, 5, 0, "HH:mm"), ! new TimeAxisSetting(2, MINUTE, 1, MINUTE, 5, MINUTE, 5, 0, "HH:mm"), ! new TimeAxisSetting(5, MINUTE, 2, MINUTE, 10, MINUTE, 10, 0, "HH:mm"), ! new TimeAxisSetting(10, MINUTE, 5, MINUTE, 20, MINUTE, 20, 0, "HH:mm"), ! new TimeAxisSetting(30, MINUTE, 10, HOUR, 1, HOUR, 1, 0, "HH:mm"), ! new TimeAxisSetting(60, MINUTE, 30, HOUR, 2, HOUR, 2, 0, "HH:mm"), ! new TimeAxisSetting(180, HOUR, 1, HOUR, 6, HOUR, 6, 0, "HH:mm"), ! new TimeAxisSetting(600, HOUR, 6, DAY, 1, DAY, 1, 24 * 3600, "EEE"), ! new TimeAxisSetting(1800, HOUR, 12, DAY, 1, DAY, 2, 24 * 3600, "EEE"), ! new TimeAxisSetting(3600, DAY, 1, WEEK, 1, WEEK, 1, 7 * 24 * 3600, "'Week 'w"), ! new TimeAxisSetting(3 * 3600, WEEK, 1, MONTH, 1, WEEK, 2, 7 * 24 * 3600, "'Week 'w"), ! new TimeAxisSetting(6 * 3600, MONTH, 1, MONTH, 1, MONTH, 1, 30 * 24 * 3600, "MMM"), ! new TimeAxisSetting(48 * 3600, MONTH, 1, MONTH, 3, MONTH, 3, 30 * 24 * 3600, "MMM"), ! new TimeAxisSetting(10 * 24 * 3600, YEAR, 1, YEAR, 1, YEAR, 1, 365 * 24 * 3600, "yy"), ! new TimeAxisSetting(-1, MONTH, 0, MONTH, 0, MONTH, 0, 0, "") }; *************** *** 57,61 **** TimeAxis(RrdGraph rrdGraph) { this.rrdGraph = rrdGraph; ! this.secPerPix = (rrdGraph.im.end - rrdGraph.im.start) / rrdGraph.im.xsize; this.calendar = Calendar.getInstance(Locale.getDefault()); this.calendar.setFirstDayOfWeek(rrdGraph.gdef.firstDayOfWeek); --- 57,63 ---- TimeAxis(RrdGraph rrdGraph) { this.rrdGraph = rrdGraph; ! if (rrdGraph.im.xsize > 0) { ! this.secPerPix = (rrdGraph.im.end - rrdGraph.im.start) / rrdGraph.im.xsize; ! } this.calendar = Calendar.getInstance(Locale.getDefault()); this.calendar.setFirstDayOfWeek(rrdGraph.gdef.firstDayOfWeek); *************** *** 64,67 **** --- 66,72 ---- void draw() { chooseTickSettings(); + if (tickSetting == null) { + return; + } drawMinor(); drawMajor(); *************** *** 123,127 **** private static String formatLabel(String format, Date date) { ! if(format.contains("%")) { // strftime like format string return String.format(format, date); --- 128,132 ---- private static String formatLabel(String format, Date date) { ! if (format.contains("%")) { // strftime like format string return String.format(format, date); Index: Stack.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/graph/Stack.java,v retrieving revision 1.6 retrieving revision 1.7 diff -C2 -d -r1.6 -r1.7 *** Stack.java 6 Apr 2005 20:10:10 -0000 1.6 --- Stack.java 21 Dec 2006 18:02:44 -0000 1.7 *************** *** 1,96 **** ! /* ============================================================ ! * 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.awt.Color; ! ! import org.jrobin.core.RrdException; ! import org.jrobin.core.XmlWriter; ! ! /** ! * <p>Class used to represent a stacked datasource plotted in a graph. The datasource ! * will be drawn as a line or an area, depending on PlotDef on which it is stacked.</p> ! * ! * @author Arne Vandamme (cob...@jr...) ! */ ! class Stack extends PlotDef ! { ! // ================================================================ ! // -- Constructors ! // ================================================================ ! /** ! * Constructs a <code>Stack</code> PlotDef object based on a datasource name and a graph color. ! * @param sourceName Name of the graph definition <code>Source</code> containing the datapoints. ! * @param color Color of the resulting area or line, if no color is specified, the PlotDef will not be drawn. ! */ ! Stack( String sourceName, Color color ) ! { ! super( sourceName, color ); ! this.plotType = PlotDef.PLOT_STACK; ! } ! ! ! // ================================================================ ! // -- Protected methods ! // ================================================================ ! /** ! * Draws the actual PlotDef on the chart, depending on the type of the previous PlotDef, ! * the Stack will be drawn as a <code>Line</code> or an <code>Area</code>. ! * @param g ChartGraphics object representing the graphing area. ! * @param xValues List of relative chart area X positions corresponding to the datapoints. ! * @param stackValues Datapoint values of previous PlotDefs, used to stack on if necessary. ! * @param lastPlotType Type of the previous PlotDef, used to determine PlotDef type of a stack. ! */ ! void draw( ChartGraphics g, int[] xValues, double[] stackValues, int lastPlotType ) throws RrdException ! { ! PlotDef stack = null; ! ! try ! { ! if ( lastPlotType == PlotDef.PLOT_LINE ) ! stack = new Line( source, values, color, true, visible ); ! else if ( lastPlotType == PlotDef.PLOT_AREA ) ! stack = new Area( source, values, color, true, visible ); ! ! stack.sourceName = sourceName; ! stack.processor = processor; ! ! stack.draw( g, xValues, stackValues, lastPlotType ); ! } ! catch (Exception e) ! { ! throw new RrdException( "Could not stack source: " + sourceName ); ! } ! ! } ! ! void exportXmlTemplate( XmlWriter xml, String legend ) { ! xml.startTag("stack"); ! xml.writeTag("datasource", sourceName); ! xml.writeTag("color", color); ! xml.writeTag("legend", legend); ! xml.closeTag(); // stack ! } ! } --- 1,64 ---- ! /* ============================================================ ! * 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...) ! * ! * ! * (C) Copyright 2003-2005, 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 org.jrobin.core.RrdException; ! import org.jrobin.data.DataProcessor; ! ! import java.awt.*; ! ! class Stack extends SourcedPlotElement { ! private final SourcedPlotElement parent; ! ! Stack(SourcedPlotElement parent, String srcName, Paint color) { ! super(srcName, color); ! this.parent = parent; ! } ! ! void assignValues(DataProcessor dproc) throws RrdException { ! double[] parentValues = parent.getValues(); ! double[] procValues = dproc.getValues(srcName); ! values = new double[procValues.length]; ! for (int i = 0; i < values.length; i++) { ! values[i] = parentValues[i] + procValues[i]; ! } ! } ! ! float getParentLineWidth() { ! if (parent instanceof Line) { ! return ((Line) parent).width; ! } ! else if (parent instanceof Area) { ! return -1F; ! } ! else /* if(parent instanceof Stack) */ { ! return ((Stack) parent).getParentLineWidth(); ! } ! } ! ! Paint getParentColor() { ! return parent.color; ! } ! } Index: PrintText.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/graph/PrintText.java,v retrieving revision 1.1.1.1 retrieving revision 1.2 diff -C2 -d -r1.1.1.1 -r1.2 *** PrintText.java 6 Sep 2005 20:40:55 -0000 1.1.1.1 --- PrintText.java 21 Dec 2006 18:02:44 -0000 1.2 *************** *** 55,59 **** double value = dproc.getAggregate(srcName, consolFun); Matcher matcher = UNIT_PATTERN.matcher(resolvedText); ! if(matcher.find()) { // unit specified ValueScaler.Scaled scaled = valueScaler.scale(value, matcher.group(2).equals("s")); --- 55,59 ---- double value = dproc.getAggregate(srcName, consolFun); Matcher matcher = UNIT_PATTERN.matcher(resolvedText); ! if (matcher.find()) { // unit specified ValueScaler.Scaled scaled = valueScaler.scale(value, matcher.group(2).equals("s")); Index: RrdGraphInfo.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/graph/RrdGraphInfo.java,v retrieving revision 1.1.1.1 retrieving revision 1.2 diff -C2 -d -r1.1.1.1 -r1.2 *** RrdGraphInfo.java 6 Sep 2005 20:40:55 -0000 1.1.1.1 --- RrdGraphInfo.java 21 Dec 2006 18:02:44 -0000 1.2 *************** *** 49,52 **** --- 49,53 ---- /** * Returns filename of the graph + * * @return filename of the graph. '-' denotes in-memory graph (no file created) */ *************** *** 57,60 **** --- 58,62 ---- /** * Returns total graph width + * * @return total graph width */ *************** *** 65,68 **** --- 67,71 ---- /** * Returns total graph height + * * @return total graph height */ *************** *** 73,76 **** --- 76,80 ---- /** * Returns graph bytes + * * @return Graph bytes */ *************** *** 81,84 **** --- 85,89 ---- /** * Returns PRINT lines requested by {@link RrdGraphDef#print(String, String, String)} method. + * * @return An array of formatted PRINT lines */ *************** *** 89,92 **** --- 94,98 ---- /** * Returns image information requested by {@link RrdGraphDef#setImageInfo(String)} method + * * @return Image information */ *************** *** 97,100 **** --- 103,107 ---- /** * Returns the number of bytes in the graph file + * * @return Length of the graph file */ *************** *** 105,116 **** /** * Dumps complete graph information. Useful for debugging purposes. * @return String containing complete graph information */ public String dump() { StringBuffer b = new StringBuffer(); ! b.append("filename = \"" + getFilename() + "\"\n"); ! b.append("width = " + getWidth() + ", height = " + getHeight() + "\n"); ! b.append("byteCount = " + getByteCount() + "\n"); ! b.append("imginfo = \"" + getImgInfo() + "\"\n"); String[] plines = getPrintLines(); if (plines.length == 0) { --- 112,124 ---- /** * Dumps complete graph information. Useful for debugging purposes. + * * @return String containing complete graph information */ public String dump() { StringBuffer b = new StringBuffer(); ! b.append("filename = \"").append(getFilename()).append("\"\n"); ! b.append("width = ").append(getWidth()).append(", height = ").append(getHeight()).append("\n"); ! b.append("byteCount = ").append(getByteCount()).append("\n"); ! b.append("imginfo = \"").append(getImgInfo()).append("\"\n"); String[] plines = getPrintLines(); if (plines.length == 0) { *************** *** 119,123 **** else { for (int i = 0; i < plines.length; i++) { ! b.append("print[" + i + "] = \"" + plines[i] + "\"\n"); } } --- 127,131 ---- else { for (int i = 0; i < plines.length; i++) { ! b.append("print[").append(i).append("] = \"").append(plines[i]).append("\"\n"); } } Index: ValueScaler.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/graph/ValueScaler.java,v retrieving revision 1.1.1.1 retrieving revision 1.2 diff -C2 -d -r1.1.1.1 -r1.2 *** ValueScaler.java 6 Sep 2005 20:40:55 -0000 1.1.1.1 --- ValueScaler.java 21 Dec 2006 18:02:44 -0000 1.2 *************** *** 28,32 **** static final String UNIT_UNKNOWN = "?"; static final String UNIT_SYMBOLS[] = { ! "a", "f", "p", "n", "u", "m", " ", "k", "M", "G", "T", "P", "E" }; static final int SYMB_CENTER = 6; --- 28,32 ---- static final String UNIT_UNKNOWN = "?"; static final String UNIT_SYMBOLS[] = { ! "a", "f", "p", "n", "u", "m", " ", "k", "M", "G", "T", "P", "E" }; static final int SYMB_CENTER = 6; *************** *** 42,49 **** Scaled scale(double value, boolean mustRescale) { Scaled scaled; ! if(mustRescale) { scaled = rescale(value); } ! else if(magfact >= 0) { // already scaled, need not rescale scaled = new Scaled(value / magfact, unit); --- 42,49 ---- Scaled scale(double value, boolean mustRescale) { Scaled scaled; ! if (mustRescale) { scaled = rescale(value); } ! else if (magfact >= 0) { // already scaled, need not rescale scaled = new Scaled(value / magfact, unit); *************** *** 53,57 **** scaled = rescale(value); // if zero, scale again on the next try ! if(scaled.value == 0.0 || Double.isNaN(scaled.value)) { magfact = -1.0; } --- 53,57 ---- scaled = rescale(value); // if zero, scale again on the next try ! if (scaled.value == 0.0 || Double.isNaN(scaled.value)) { magfact = -1.0; } Index: RrdGraphDefTemplate.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/graph/RrdGraphDefTemplate.java,v retrieving revision 1.12 retrieving revision 1.13 diff -C2 -d -r1.12 -r1.13 *** RrdGraphDefTemplate.java 6 Apr 2005 20:10:10 -0000 1.12 --- RrdGraphDefTemplate.java 21 Dec 2006 18:02:44 -0000 1.13 *************** *** 1,906 **** ! /* ============================================================ ! * JRobin : Pure java implementation of RRDTool's functionality ! * ============================================================ ! * ! * Project Info: http://www.jrobin.org ! * Project Lead: Sasa Markovic (sa...@jr...); ! * ! * (C) Copyright 2003, by Sasa Markovic. ! * ! * Developers: Sasa Markovic (sa...@jr...) [...1862 lines s... [truncated message content] |
From: Tarus B. <ta...@us...> - 2006-12-21 18:02:49
|
Update of /cvsroot/jrobin/src/org/jrobin/inspector In directory sc8-pr-cvs6.sourceforge.net:/tmp/cvs-serv9082/org/jrobin/inspector Modified Files: ArchiveTableModel.java DataTableModel.java DatasourceTableModel.java EditArchiveDialog.java EditDatasourceDialog.java GraphFrame.java HeaderTableModel.java InspectorModel.java MainTreeModel.java RrdInspector.java RrdNode.java Util.java Log Message: Adding the new 1.5.4 code Index: DataTableModel.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/inspector/DataTableModel.java,v retrieving revision 1.7 retrieving revision 1.8 diff -C2 -d -r1.7 -r1.8 *** DataTableModel.java 27 Aug 2004 09:42:43 -0000 1.7 --- DataTableModel.java 21 Dec 2006 18:02:44 -0000 1.8 *************** *** 1,132 **** ! /* ============================================================ ! * JRobin : Pure java implementation of RRDTool's functionality ! * ============================================================ ! * ! * Project Info: http://www.jrobin.org ! * Project Lead: Sasa Markovic (sa...@jr...); ! * ! * (C) Copyright 2003, by Sasa Markovic. ! * ! * Developers: Sasa Markovic (sa...@jr...) ! * Arne Vandamme (cob...@jr...) ! * ! * This library is free software; you can redistribute it and/or modify it under the terms ! * of the GNU Lesser General Public License as published by the Free Software Foundation; ! * either version 2.1 of the License, or (at your option) any later version. ! * ! * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; ! * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. ! * See the GNU Lesser General Public License for more details. ! * ! * You should have received a copy of the GNU Lesser General Public License along with this ! * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, ! * Boston, MA 02111-1307, USA. ! */ ! ! package org.jrobin.inspector; ! ! import org.jrobin.core.*; ! ! import javax.swing.table.AbstractTableModel; ! import java.io.File; ! import java.io.IOException; ! import java.util.Date; ! ! class DataTableModel extends AbstractTableModel { ! private static final String[] COLUMN_NAMES = {"timestamp", "date", "value"}; ! ! private File file; ! private Object[][] values; ! private int dsIndex = -1, arcIndex = -1; ! ! public int getRowCount() { ! if(values == null) { ! return 0; ! } ! else { ! return values.length; ! } ! } ! ! public int getColumnCount() { ! return COLUMN_NAMES.length; ! } ! ! public Object getValueAt(int rowIndex, int columnIndex) { ! if(values == null) { ! return "--"; ! } ! return values[rowIndex][columnIndex]; ! } ! ! public String getColumnName(int column) { ! return COLUMN_NAMES[column]; ! } ! ! public boolean isCellEditable(int rowIndex, int columnIndex) { ! return columnIndex == 2; ! } ! ! public void setValueAt(Object aValue, int rowIndex, int columnIndex) { ! assert columnIndex == 2: "Column " + columnIndex + " is not editable!"; ! double value; ! try { ! value = Double.parseDouble(aValue.toString()); ! } ! catch (NumberFormatException nfe) { ! value = Double.NaN; ! } ! if(dsIndex >= 0 && arcIndex >= 0 && file != null) { ! try { ! RrdDb rrd = new RrdDb(file.getAbsolutePath()); ! Robin robin = rrd.getArchive(arcIndex).getRobin(dsIndex); ! robin.setValue(rowIndex, value); ! values[rowIndex][2] = InspectorModel.formatDouble(robin.getValue(rowIndex)); ! rrd.close(); ! } ! catch(Exception e) { ! Util.error(null, e); ! } ! } ! } ! ! void setFile(File newFile) { ! file = newFile; ! setIndex(-1, -1); ! } ! ! void setIndex(int newDsIndex, int newArcIndex) { ! if (dsIndex != newDsIndex || arcIndex != newArcIndex) { ! dsIndex = newDsIndex; ! arcIndex = newArcIndex; ! values = null; ! if(dsIndex >= 0 && arcIndex >= 0) { ! try { ! RrdDb rrd = new RrdDb(file.getAbsolutePath(), true); ! Archive arc = rrd.getArchive(arcIndex); ! Robin robin = arc.getRobin(dsIndex); ! long start = arc.getStartTime(); ! long step = arc.getArcStep(); ! double robinValues[] = robin.getValues(); ! values = new Object[robinValues.length][]; ! for(int i = 0; i < robinValues.length; i++) { ! long timestamp = start + i * step; ! String date = new Date(timestamp * 1000L).toString(); ! String value = InspectorModel.formatDouble(robinValues[i]); ! values[i] = new Object[] { ! "" + timestamp, date, value ! }; ! } ! rrd.close(); ! } ! catch (IOException e) { ! Util.error(null, e); ! } ! catch (RrdException e) { ! Util.error(null, e); ! } ! } ! fireTableDataChanged(); ! } ! } ! } --- 1,140 ---- ! /* ============================================================ ! * JRobin : Pure java implementation of RRDTool's functionality ! * ============================================================ ! * ! * Project Info: http://www.jrobin.org ! * Project Lead: Sasa Markovic (sa...@jr...); ! * ! * (C) Copyright 2003, by Sasa Markovic. ! * ! * Developers: Sasa Markovic (sa...@jr...) ! * ! * ! * 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.inspector; ! ! import org.jrobin.core.*; ! ! import javax.swing.table.AbstractTableModel; ! import java.io.File; ! import java.io.IOException; ! import java.util.Date; ! ! class DataTableModel extends AbstractTableModel { ! private static final String[] COLUMN_NAMES = {"timestamp", "date", "value"}; ! ! private File file; ! private Object[][] values; ! private int dsIndex = -1, arcIndex = -1; ! ! public int getRowCount() { ! if (values == null) { ! return 0; ! } ! else { ! return values.length; ! } ! } ! ! public int getColumnCount() { ! return COLUMN_NAMES.length; ! } ! ! public Object getValueAt(int rowIndex, int columnIndex) { ! if (values == null) { ! return "--"; ! } ! return values[rowIndex][columnIndex]; ! } ! ! public String getColumnName(int column) { ! return COLUMN_NAMES[column]; ! } ! ! public boolean isCellEditable(int rowIndex, int columnIndex) { ! return columnIndex == 2; ! } ! ! public void setValueAt(Object aValue, int rowIndex, int columnIndex) { ! assert columnIndex == 2: "Column " + columnIndex + " is not editable!"; ! double value; ! try { ! value = Double.parseDouble(aValue.toString()); ! } ! catch (NumberFormatException nfe) { ! value = Double.NaN; ! } ! if (dsIndex >= 0 && arcIndex >= 0 && file != null) { ! try { ! RrdDb rrd = new RrdDb(file.getAbsolutePath()); ! try { ! Robin robin = rrd.getArchive(arcIndex).getRobin(dsIndex); ! robin.setValue(rowIndex, value); ! values[rowIndex][2] = InspectorModel.formatDouble(robin.getValue(rowIndex)); ! } ! finally { ! rrd.close(); ! } ! } ! catch (Exception e) { ! Util.error(null, e); ! } ! } ! } ! ! void setFile(File newFile) { ! file = newFile; ! setIndex(-1, -1); ! } ! ! void setIndex(int newDsIndex, int newArcIndex) { ! if (dsIndex != newDsIndex || arcIndex != newArcIndex) { ! dsIndex = newDsIndex; ! arcIndex = newArcIndex; ! values = null; ! if (dsIndex >= 0 && arcIndex >= 0) { ! try { ! RrdDb rrd = new RrdDb(file.getAbsolutePath(), true); ! try { ! Archive arc = rrd.getArchive(arcIndex); ! Robin robin = arc.getRobin(dsIndex); ! long start = arc.getStartTime(); ! long step = arc.getArcStep(); ! double robinValues[] = robin.getValues(); ! values = new Object[robinValues.length][]; ! for (int i = 0; i < robinValues.length; i++) { ! long timestamp = start + i * step; ! String date = new Date(timestamp * 1000L).toString(); ! String value = InspectorModel.formatDouble(robinValues[i]); ! values[i] = new Object[] { ! "" + timestamp, date, value ! }; ! } ! } ! finally { ! rrd.close(); ! } ! } ! catch (IOException e) { ! Util.error(null, e); ! } ! catch (RrdException e) { ! Util.error(null, e); ! } ! } ! fireTableDataChanged(); ! } ! } ! } Index: MainTreeModel.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/inspector/MainTreeModel.java,v retrieving revision 1.7 retrieving revision 1.8 diff -C2 -d -r1.7 -r1.8 *** MainTreeModel.java 27 Aug 2004 09:42:43 -0000 1.7 --- MainTreeModel.java 21 Dec 2006 18:02:45 -0000 1.8 *************** *** 1,75 **** ! /* ============================================================ ! * JRobin : Pure java implementation of RRDTool's functionality ! * ============================================================ ! * ! * Project Info: http://www.jrobin.org ! * Project Lead: Sasa Markovic (sa...@jr...); ! * ! * (C) Copyright 2003, by Sasa Markovic. ! * ! * Developers: Sasa Markovic (sa...@jr...) ! * Arne Vandamme (cob...@jr...) ! * ! * This library is free software; you can redistribute it and/or modify it under the terms ! * of the GNU Lesser General Public License as published by the Free Software Foundation; ! * either version 2.1 of the License, or (at your option) any later version. ! * ! * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; ! * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. ! * See the GNU Lesser General Public License for more details. ! * ! * You should have received a copy of the GNU Lesser General Public License along with this ! * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, ! * Boston, MA 02111-1307, USA. ! */ ! ! package org.jrobin.inspector; ! ! import org.jrobin.core.RrdDb; ! import org.jrobin.core.RrdException; ! ! import javax.swing.tree.DefaultTreeModel; ! import javax.swing.tree.DefaultMutableTreeNode; ! import java.io.IOException; ! import java.io.File; ! ! class MainTreeModel extends DefaultTreeModel { ! private static final DefaultMutableTreeNode INVALID_NODE = ! new DefaultMutableTreeNode("No valid RRD file specified"); ! ! private File file; ! ! MainTreeModel() { ! super(INVALID_NODE); ! } ! ! boolean setFile(File newFile) { ! try { ! file = newFile; ! RrdDb rrd = new RrdDb(file.getAbsolutePath(), true); ! DefaultMutableTreeNode root = new DefaultMutableTreeNode(new RrdNode(rrd)); ! int dsCount = rrd.getRrdDef().getDsCount(); ! int arcCount = rrd.getRrdDef().getArcCount(); ! for (int dsIndex = 0; dsIndex < dsCount; dsIndex++) { ! DefaultMutableTreeNode dsNode = ! new DefaultMutableTreeNode(new RrdNode(rrd, dsIndex)); ! for (int arcIndex = 0; arcIndex < arcCount; arcIndex++) { ! DefaultMutableTreeNode arcNode = ! new DefaultMutableTreeNode(new RrdNode(rrd, dsIndex, arcIndex)); ! dsNode.add(arcNode); ! } ! root.add(dsNode); ! } ! rrd.close(); ! setRoot(root); ! return true; ! } catch (IOException e) { ! setRoot(INVALID_NODE); ! Util.error(null, e); ! } catch (RrdException e) { ! setRoot(INVALID_NODE); ! Util.error(null, e); ! } ! return false; ! } ! } --- 1,78 ---- ! /* ============================================================ ! * JRobin : Pure java implementation of RRDTool's functionality ! * ============================================================ ! * ! * Project Info: http://www.jrobin.org ! * Project Lead: Sasa Markovic (sa...@jr...); ! * ! * (C) Copyright 2003, by Sasa Markovic. ! * ! * Developers: Sasa Markovic (sa...@jr...) ! * ! * ! * 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.inspector; ! ! import org.jrobin.core.RrdDb; ! import org.jrobin.core.RrdException; ! ! import javax.swing.tree.DefaultTreeModel; ! import javax.swing.tree.DefaultMutableTreeNode; ! import java.io.IOException; ! import java.io.File; ! ! class MainTreeModel extends DefaultTreeModel { ! private static final DefaultMutableTreeNode INVALID_NODE = ! new DefaultMutableTreeNode("No valid RRD file specified"); ! ! MainTreeModel() { ! super(INVALID_NODE); ! } ! ! boolean setFile(File file) { ! try { ! RrdDb rrd = new RrdDb(file.getAbsolutePath(), true); ! try { ! DefaultMutableTreeNode root = new DefaultMutableTreeNode(new RrdNode(rrd)); ! int dsCount = rrd.getRrdDef().getDsCount(); ! int arcCount = rrd.getRrdDef().getArcCount(); ! for (int dsIndex = 0; dsIndex < dsCount; dsIndex++) { ! DefaultMutableTreeNode dsNode = ! new DefaultMutableTreeNode(new RrdNode(rrd, dsIndex)); ! for (int arcIndex = 0; arcIndex < arcCount; arcIndex++) { ! DefaultMutableTreeNode arcNode = ! new DefaultMutableTreeNode(new RrdNode(rrd, dsIndex, arcIndex)); ! dsNode.add(arcNode); ! } ! root.add(dsNode); ! } ! setRoot(root); ! } ! finally { ! rrd.close(); ! } ! return true; ! } ! catch (IOException e) { ! setRoot(INVALID_NODE); ! Util.error(null, e); ! } ! catch (RrdException e) { ! setRoot(INVALID_NODE); ! Util.error(null, e); ! } ! return false; ! } ! } Index: DatasourceTableModel.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/inspector/DatasourceTableModel.java,v retrieving revision 1.7 retrieving revision 1.8 diff -C2 -d -r1.7 -r1.8 *** DatasourceTableModel.java 27 Aug 2004 09:42:43 -0000 1.7 --- DatasourceTableModel.java 21 Dec 2006 18:02:44 -0000 1.8 *************** *** 1,114 **** ! /* ============================================================ ! * JRobin : Pure java implementation of RRDTool's functionality ! * ============================================================ ! * ! * Project Info: http://www.jrobin.org ! * Project Lead: Sasa Markovic (sa...@jr...); ! * ! * (C) Copyright 2003, by Sasa Markovic. ! * ! * Developers: Sasa Markovic (sa...@jr...) ! * Arne Vandamme (cob...@jr...) ! * ! * This library is free software; you can redistribute it and/or modify it under the terms ! * of the GNU Lesser General Public License as published by the Free Software Foundation; ! * either version 2.1 of the License, or (at your option) any later version. ! * ! * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; ! * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. ! * See the GNU Lesser General Public License for more details. ! * ! * You should have received a copy of the GNU Lesser General Public License along with this ! * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, ! * Boston, MA 02111-1307, USA. ! */ ! package org.jrobin.inspector; ! ! import org.jrobin.core.RrdDb; ! import org.jrobin.core.Datasource; ! import org.jrobin.core.RrdException; ! ! import javax.swing.table.AbstractTableModel; ! import java.io.IOException; ! import java.io.File; ! ! class DatasourceTableModel extends AbstractTableModel { ! private static final Object[] DESCRIPTIONS = { ! "name", "type", "heartbeat", "min value", ! "max value", "last value", "accum. value", "NaN seconds" ! }; ! private static final String[] COLUMN_NAMES = { ! "description", "value" ! }; ! ! private File file; ! private Object[] values; ! private int dsIndex = -1; ! ! public int getRowCount() { ! return DESCRIPTIONS.length; ! } ! ! public int getColumnCount() { ! return COLUMN_NAMES.length; ! } ! ! public Object getValueAt(int rowIndex, int columnIndex) { ! if (columnIndex == 0) { ! return DESCRIPTIONS[rowIndex]; ! } ! else if (columnIndex == 1) { ! if (values != null) { ! return values[rowIndex]; ! } ! else { ! return "--"; ! } ! } ! return null; ! } ! ! public String getColumnName(int column) { ! return COLUMN_NAMES[column]; ! } ! ! public boolean isCellEditable(int rowIndex, int columnIndex) { ! return false; ! } ! ! void setFile(File newFile) { ! file = newFile; ! setIndex(-1); ! } ! ! void setIndex(int newDsIndex) { ! if (dsIndex != newDsIndex) { ! dsIndex = newDsIndex; ! values = null; ! if(dsIndex >= 0) { ! try { ! RrdDb rrd = new RrdDb(file.getAbsolutePath(), true); ! Datasource ds = rrd.getDatasource(dsIndex); ! values = new Object[]{ ! ds.getDsName(), ! ds.getDsType(), ! "" + ds.getHeartbeat(), ! InspectorModel.formatDouble(ds.getMinValue()), ! InspectorModel.formatDouble(ds.getMaxValue()), ! InspectorModel.formatDouble(ds.getLastValue()), ! InspectorModel.formatDouble(ds.getAccumValue()), ! "" + ds.getNanSeconds() ! }; ! rrd.close(); ! } ! catch (IOException e) { ! Util.error(null, e); ! } ! catch (RrdException e) { ! Util.error(null, e); ! } ! } ! fireTableDataChanged(); ! } ! } } \ No newline at end of file --- 1,118 ---- ! /* ============================================================ ! * JRobin : Pure java implementation of RRDTool's functionality ! * ============================================================ ! * ! * Project Info: http://www.jrobin.org ! * Project Lead: Sasa Markovic (sa...@jr...); ! * ! * (C) Copyright 2003, by Sasa Markovic. ! * ! * Developers: Sasa Markovic (sa...@jr...) ! * ! * ! * 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.inspector; ! ! import org.jrobin.core.RrdDb; ! import org.jrobin.core.Datasource; ! import org.jrobin.core.RrdException; ! ! import javax.swing.table.AbstractTableModel; ! import java.io.IOException; ! import java.io.File; ! ! class DatasourceTableModel extends AbstractTableModel { ! private static final Object[] DESCRIPTIONS = { ! "name", "type", "heartbeat", "min value", ! "max value", "last value", "accum. value", "NaN seconds" ! }; ! private static final String[] COLUMN_NAMES = { ! "description", "value" ! }; ! ! private File file; ! private Object[] values; ! private int dsIndex = -1; ! ! public int getRowCount() { ! return DESCRIPTIONS.length; ! } ! ! public int getColumnCount() { ! return COLUMN_NAMES.length; ! } ! ! public Object getValueAt(int rowIndex, int columnIndex) { ! if (columnIndex == 0) { ! return DESCRIPTIONS[rowIndex]; ! } ! else if (columnIndex == 1) { ! if (values != null) { ! return values[rowIndex]; ! } ! else { ! return "--"; ! } ! } ! return null; ! } ! ! public String getColumnName(int column) { ! return COLUMN_NAMES[column]; ! } ! ! public boolean isCellEditable(int rowIndex, int columnIndex) { ! return false; ! } ! ! void setFile(File newFile) { ! file = newFile; ! setIndex(-1); ! } ! ! void setIndex(int newDsIndex) { ! if (dsIndex != newDsIndex) { ! dsIndex = newDsIndex; ! values = null; ! if (dsIndex >= 0) { ! try { ! RrdDb rrd = new RrdDb(file.getAbsolutePath(), true); ! try { ! Datasource ds = rrd.getDatasource(dsIndex); ! values = new Object[] { ! ds.getDsName(), ! ds.getDsType(), ! "" + ds.getHeartbeat(), ! InspectorModel.formatDouble(ds.getMinValue()), ! InspectorModel.formatDouble(ds.getMaxValue()), ! InspectorModel.formatDouble(ds.getLastValue()), ! InspectorModel.formatDouble(ds.getAccumValue()), ! "" + ds.getNanSeconds() ! }; ! } ! finally { ! rrd.close(); ! } ! } ! catch (IOException e) { ! Util.error(null, e); ! } ! catch (RrdException e) { ! Util.error(null, e); ! } ! } ! fireTableDataChanged(); ! } ! } } \ No newline at end of file Index: RrdNode.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/inspector/RrdNode.java,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** RrdNode.java 20 May 2004 10:29:33 -0000 1.3 --- RrdNode.java 21 Dec 2006 18:02:45 -0000 1.4 *************** *** 1,70 **** ! /* ============================================================ ! * JRobin : Pure java implementation of RRDTool's functionality ! * ============================================================ ! * ! * Project Info: http://www.jrobin.org ! * Project Lead: Sasa Markovic (sa...@jr...); ! * ! * (C) Copyright 2003, by Sasa Markovic. ! * ! * Developers: Sasa Markovic (sa...@jr...) ! * Arne Vandamme (cob...@jr...) ! * ! * This library is free software; you can redistribute it and/or modify it under the terms ! * of the GNU Lesser General Public License as published by the Free Software Foundation; ! * either version 2.1 of the License, or (at your option) any later version. ! * ! * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; ! * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. ! * See the GNU Lesser General Public License for more details. ! * ! * You should have received a copy of the GNU Lesser General Public License along with this ! * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, ! * Boston, MA 02111-1307, USA. ! */ ! ! package org.jrobin.inspector; ! ! import org.jrobin.core.*; ! ! import java.io.File; ! import java.io.IOException; ! ! class RrdNode { ! private int dsIndex = -1, arcIndex = -1; ! private String label; ! ! RrdNode(RrdDb rrd) { ! // header node ! String path = rrd.getRrdBackend().getPath(); ! label = new File(path).getName(); ! } ! ! RrdNode(RrdDb rrd, int dsIndex) throws IOException, RrdException { ! // datasource node ! this.dsIndex = dsIndex; ! RrdDef def = rrd.getRrdDef(); ! DsDef[] dsDefs = def.getDsDefs(); ! label = dsDefs[dsIndex].dump(); ! } ! ! RrdNode(RrdDb rrd, int dsIndex, int arcIndex) throws IOException, RrdException { ! // archive node ! this.dsIndex = dsIndex; ! this.arcIndex = arcIndex; ! ArcDef[] arcDefs = rrd.getRrdDef().getArcDefs(); ! label = arcDefs[arcIndex].dump(); ! } ! ! int getDsIndex() { ! return dsIndex; ! } ! ! int getArcIndex() { ! return arcIndex; ! } ! ! public String toString() { ! return label; ! } ! } --- 1,70 ---- ! /* ============================================================ ! * JRobin : Pure java implementation of RRDTool's functionality ! * ============================================================ ! * ! * Project Info: http://www.jrobin.org ! * Project Lead: Sasa Markovic (sa...@jr...); ! * ! * (C) Copyright 2003, by Sasa Markovic. ! * ! * Developers: Sasa Markovic (sa...@jr...) ! * ! * ! * 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.inspector; ! ! import org.jrobin.core.*; ! ! import java.io.File; ! import java.io.IOException; ! ! class RrdNode { ! private int dsIndex = -1, arcIndex = -1; ! private String label; ! ! RrdNode(RrdDb rrd) { ! // header node ! String path = rrd.getRrdBackend().getPath(); ! label = new File(path).getName(); ! } ! ! RrdNode(RrdDb rrd, int dsIndex) throws IOException, RrdException { ! // datasource node ! this.dsIndex = dsIndex; ! RrdDef def = rrd.getRrdDef(); ! DsDef[] dsDefs = def.getDsDefs(); ! label = dsDefs[dsIndex].dump(); ! } ! ! RrdNode(RrdDb rrd, int dsIndex, int arcIndex) throws IOException, RrdException { ! // archive node ! this.dsIndex = dsIndex; ! this.arcIndex = arcIndex; ! ArcDef[] arcDefs = rrd.getRrdDef().getArcDefs(); ! label = arcDefs[arcIndex].dump(); ! } ! ! int getDsIndex() { ! return dsIndex; ! } ! ! int getArcIndex() { ! return arcIndex; ! } ! ! public String toString() { ! return label; ! } ! } Index: HeaderTableModel.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/inspector/HeaderTableModel.java,v retrieving revision 1.8 retrieving revision 1.9 diff -C2 -d -r1.8 -r1.9 *** HeaderTableModel.java 27 Aug 2004 09:42:43 -0000 1.8 --- HeaderTableModel.java 21 Dec 2006 18:02:45 -0000 1.9 *************** *** 1,97 **** ! /* ============================================================ ! * JRobin : Pure java implementation of RRDTool's functionality ! * ============================================================ ! * ! * Project Info: http://www.jrobin.org ! * Project Lead: Sasa Markovic (sa...@jr...); ! * ! * (C) Copyright 2003, by Sasa Markovic. ! * ! * Developers: Sasa Markovic (sa...@jr...) ! * Arne Vandamme (cob...@jr...) ! * ! * This library is free software; you can redistribute it and/or modify it under the terms ! * of the GNU Lesser General Public License as published by the Free Software Foundation; ! * either version 2.1 of the License, or (at your option) any later version. ! * ! * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; ! * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. ! * See the GNU Lesser General Public License for more details. ! * ! * You should have received a copy of the GNU Lesser General Public License along with this ! * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, ! * Boston, MA 02111-1307, USA. ! */ ! ! package org.jrobin.inspector; ! ! import org.jrobin.core.RrdDb; ! import org.jrobin.core.Header; ! import org.jrobin.core.RrdException; ! ! import javax.swing.table.AbstractTableModel; ! import java.util.Date; ! import java.io.IOException; ! import java.io.File; ! ! class HeaderTableModel extends AbstractTableModel { ! private static final Object[] DESCRIPTIONS = {"path", "signature", "step", "last timestamp", ! "datasources", "archives", "size"}; ! private static final String[] COLUMN_NAMES = {"description", "value"}; ! ! private File file; ! private Object[] values; ! ! public int getRowCount() { ! return DESCRIPTIONS.length; ! } ! ! public int getColumnCount() { ! return COLUMN_NAMES.length; ! } ! ! public Object getValueAt(int rowIndex, int columnIndex) { ! if (columnIndex == 0) { ! return DESCRIPTIONS[rowIndex]; ! } else if (columnIndex == 1) { ! if (values != null) { ! return values[rowIndex]; ! } else { ! return "--"; ! } ! } ! return null; ! } ! ! public String getColumnName(int column) { ! return COLUMN_NAMES[column]; ! } ! ! ! ! void setFile(File newFile) { ! try { ! file = newFile; ! values = null; ! String path = file.getAbsolutePath(); ! RrdDb rrd = new RrdDb(path, true); ! Header header = rrd.getHeader(); ! String signature = header.getSignature(); ! String step = "" + header.getStep(); ! String lastTimestamp = header.getLastUpdateTime() + " [" + ! new Date(header.getLastUpdateTime() * 1000L) + "]"; ! String datasources = "" + header.getDsCount(); ! String archives = "" + header.getArcCount(); ! String size = rrd.getRrdBackend().getLength() + " bytes"; ! rrd.close(); ! values = new Object[]{ ! path, signature, step, lastTimestamp, datasources, archives, size ! }; ! fireTableDataChanged(); ! } catch (IOException e) { ! Util.error(null, e); ! } catch (RrdException e) { ! Util.error(null, e); ! } ! } } \ No newline at end of file --- 1,104 ---- ! /* ============================================================ ! * JRobin : Pure java implementation of RRDTool's functionality ! * ============================================================ ! * ! * Project Info: http://www.jrobin.org ! * Project Lead: Sasa Markovic (sa...@jr...); ! * ! * (C) Copyright 2003, by Sasa Markovic. ! * ! * Developers: Sasa Markovic (sa...@jr...) ! * ! * ! * 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.inspector; ! ! import org.jrobin.core.RrdDb; ! import org.jrobin.core.Header; ! import org.jrobin.core.RrdException; ! ! import javax.swing.table.AbstractTableModel; ! import java.util.Date; ! import java.io.IOException; ! import java.io.File; ! ! class HeaderTableModel extends AbstractTableModel { ! private static final Object[] DESCRIPTIONS = { ! "path", "signature", "step", "last timestamp", ! "datasources", "archives", "size" ! }; ! private static final String[] COLUMN_NAMES = {"description", "value"}; ! ! private Object[] values; ! ! public int getRowCount() { ! return DESCRIPTIONS.length; ! } ! ! public int getColumnCount() { ! return COLUMN_NAMES.length; ! } ! ! public Object getValueAt(int rowIndex, int columnIndex) { ! if (columnIndex == 0) { ! return DESCRIPTIONS[rowIndex]; ! } ! else if (columnIndex == 1) { ! if (values != null) { ! return values[rowIndex]; ! } ! else { ! return "--"; ! } ! } ! return null; ! } ! ! public String getColumnName(int column) { ! return COLUMN_NAMES[column]; ! } ! ! ! void setFile(File file) { ! try { ! values = null; ! String path = file.getAbsolutePath(); ! RrdDb rrd = new RrdDb(path, true); ! try { ! Header header = rrd.getHeader(); ! String signature = header.getSignature(); ! String step = "" + header.getStep(); ! String lastTimestamp = header.getLastUpdateTime() + " [" + ! new Date(header.getLastUpdateTime() * 1000L) + "]"; ! String datasources = "" + header.getDsCount(); ! String archives = "" + header.getArcCount(); ! String size = rrd.getRrdBackend().getLength() + " bytes"; ! values = new Object[] { ! path, signature, step, lastTimestamp, datasources, archives, size ! }; ! } ! finally { ! rrd.close(); ! } ! fireTableDataChanged(); ! } ! catch (IOException e) { ! Util.error(null, e); ! } ! catch (RrdException e) { ! Util.error(null, e); ! } ! } } \ No newline at end of file Index: GraphFrame.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/inspector/GraphFrame.java,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** GraphFrame.java 18 Sep 2004 12:10:29 -0000 1.2 --- GraphFrame.java 21 Dec 2006 18:02:44 -0000 1.3 *************** *** 1,266 **** ! /* ============================================================ ! * JRobin : Pure java implementation of RRDTool's functionality ! * ============================================================ ! * ! * Project Info: http://www.jrobin.org ! * Project Lead: Sasa Markovic (sa...@jr...); ! * ! * (C) Copyright 2003, by Sasa Markovic. ! * ! * Developers: Sasa Markovic (sa...@jr...) ! * Arne Vandamme (cob...@jr...) ! * ! * This library is free software; you can redistribute it and/or modify it under the terms ! * of the GNU Lesser General Public License as published by the Free Software Foundation; ! * either version 2.1 of the License, or (at your option) any later version. ! * ! * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; ! * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. ! * See the GNU Lesser General Public License for more details. ! * ! * You should have received a copy of the GNU Lesser General Public License along with this ! * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, ! * Boston, MA 02111-1307, USA. ! */ ! package org.jrobin.inspector; ! ! import org.jrobin.core.*; ! import org.jrobin.graph.RrdGraphDef; ! import org.jrobin.graph.RrdGraph; ! import org.jrobin.graph.LinearInterpolator; ! ! import javax.swing.*; ! import javax.swing.filechooser.FileFilter; ! import java.awt.*; ! import java.awt.event.*; ! import java.io.IOException; ! import java.io.File; ! import java.util.Date; ! ! class GraphFrame extends JFrame { ! private static final Color COLOR = Color.RED; ! private static final int WIDTH = 400, HEIGHT = 240; ! ! private Color color = COLOR; ! private GraphPanel graphPanel = new GraphPanel(); ! private JComboBox graphCombo = new JComboBox(); ! private RrdGraph rrdGraph; ! ! private String sourcePath, dsName; ! private int dsIndex, arcIndex; ! private long t1, t2; ! ! GraphFrame(String sourcePath, int dsIndex, int arcIndex) { ! this.sourcePath = sourcePath; ! this.dsIndex = dsIndex; ! this.arcIndex = arcIndex; ! createRrdGraph(); ! fillGraphCombo(); ! constructUI(); ! pack(); ! Util.placeWindow(this); ! setVisible(true); ! } ! ! private void createRrdGraph() { ! try { ! RrdDb rrdDb = new RrdDb(sourcePath, true); ! Datasource ds = rrdDb.getDatasource(dsIndex); ! Archive arc = rrdDb.getArchive(arcIndex); ! Robin robin = arc.getRobin(dsIndex); ! dsName = ds.getDsName(); ! t1 = arc.getStartTime(); ! t2 = arc.getEndTime(); ! long step = arc.getArcStep(); ! int count = robin.getSize(); ! long[] timestamps = new long[count]; ! for(int i = 0; i < count; i++) { ! timestamps[i] = t1 + i * step; ! } ! double[] values = robin.getValues(); ! RrdDef rrdDef = rrdDb.getRrdDef(); ! rrdDb.close(); ! RrdGraphDef rrdGraphDef = new RrdGraphDef(t1, t2); ! rrdGraphDef.setTitle(rrdDef.getDsDefs()[dsIndex].dump() + " " + ! rrdDef.getArcDefs()[arcIndex].dump()); ! LinearInterpolator linearInterpolator = new LinearInterpolator(timestamps, values); ! linearInterpolator.setInterpolationMethod(LinearInterpolator.INTERPOLATE_RIGHT); ! rrdGraphDef.datasource(dsName, linearInterpolator); ! rrdGraphDef.area(dsName, color, dsName + "@r"); ! rrdGraphDef.comment("START: " + new Date(t1 * 1000L) + "@r"); ! rrdGraphDef.comment("END: " + new Date(t2 * 1000L) + "@r"); ! rrdGraph = new RrdGraph(rrdGraphDef); ! rrdGraph.specifyImageSize(true); ! } catch (IOException e) { ! Util.error(this, e); ! } catch (RrdException e) { ! Util.error(this, e); ! } ! } ! ! private void fillGraphCombo() { ! try { ! RrdDb rrdDb = new RrdDb(sourcePath, true); ! RrdDef rrdDef = rrdDb.getRrdDef(); ! final DsDef[] dsDefs = rrdDef.getDsDefs(); ! final ArcDef[] arcDefs = rrdDef.getArcDefs(); ! GraphComboItem[] items = new GraphComboItem[rrdDef.getDsCount() * rrdDef.getArcCount()]; ! int selectedItem = -1; ! for(int i = 0, k = 0; i < rrdDef.getDsCount(); i++) { ! for(int j = 0; j < rrdDef.getArcCount(); k++, j++) { ! String description = dsDefs[i].dump() + " " + arcDefs[j].dump(); ! items[k] = new GraphComboItem(description, i, j); ! if(i == dsIndex && j == arcIndex) { ! selectedItem = k; ! } ! } ! } ! graphCombo.setModel(new DefaultComboBoxModel(items)); ! graphCombo.setSelectedIndex(selectedItem); ! } ! catch (IOException e) { ! Util.error(this, e); ! } ! catch (RrdException e) { ! Util.error(this, e); ! } ! } ! ! private void constructUI() { ! setTitle(new File(sourcePath).getName()); ! JPanel content = (JPanel) getContentPane(); ! content.setLayout(new BorderLayout(3, 3)); ! content.add(graphCombo, BorderLayout.NORTH); ! graphPanel.setPreferredSize(new Dimension(WIDTH, HEIGHT)); ! content.add(graphPanel, BorderLayout.CENTER); ! JPanel southPanel = new JPanel(); ! southPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 0, 0)); ! JButton colorButton = new JButton("Change graph color"); ! southPanel.add(colorButton); ! colorButton.addActionListener(new ActionListener() { ! public void actionPerformed(ActionEvent e) { ! changeColor(); ! } ! }); ! JButton saveButton = new JButton("Save graph"); ! saveButton.addActionListener(new ActionListener() { ! public void actionPerformed(ActionEvent e) { ! saveGraph(); ! } ! }); ! southPanel.add(Box.createHorizontalStrut(3)); ! southPanel.add(saveButton); ! content.add(southPanel, BorderLayout.SOUTH); ! // EVENT HANDLERS ! setDefaultCloseOperation(DISPOSE_ON_CLOSE); ! addWindowListener(new WindowAdapter() { ! public void windowClosing(WindowEvent e) { ! closeWindow(); ! } ! }); ! graphCombo.addItemListener(new ItemListener() { ! public void itemStateChanged(ItemEvent e) { ! if(e.getStateChange() == ItemEvent.SELECTED) { ! GraphComboItem item = (GraphComboItem) e.getItem(); ! dsIndex = item.getDsIndex(); ! arcIndex = item.getArcIndex(); ! createRrdGraph(); ! graphPanel.repaint(); ! } ! } ! }); ! } ! ! private void closeWindow() { ! Util.dismissWindow(this); ! } ! ! private void changeColor() { ! final JColorChooser picker = new JColorChooser(color); ! ActionListener okListener = new ActionListener() { ! public void actionPerformed(ActionEvent e) { ! color = picker.getColor(); ! createRrdGraph(); ! graphPanel.repaint(); ! } ! }; ! JColorChooser.createDialog(this, "Select color", true, picker, okListener, null).show(); ! } ! ! private void saveGraph() { ! JFileChooser chooser = new JFileChooser(); ! FileFilter filter = new FileFilter() { ! public boolean accept(File f) { ! return f.isDirectory()? true: ! f.getAbsolutePath().toLowerCase().endsWith(".png"); ! } ! public String getDescription() { ! return "PNG images"; ! } ! }; ! chooser.setFileFilter(filter); ! int returnVal = chooser.showSaveDialog(this); ! if(returnVal == JFileChooser.APPROVE_OPTION) { ! try { ! File selectedFile = chooser.getSelectedFile(); ! String path = selectedFile.getAbsolutePath(); ! if(!path.toLowerCase().endsWith(".png")) { ! path += ".png"; ! selectedFile = new File(path); ! } ! if(selectedFile.exists()) { ! // ask user to overwrite ! String message = "File [" + selectedFile.getName() + ! "] already exists. Do you want to overwrite it?"; ! int answer = JOptionPane.showConfirmDialog(this, ! message, "File exists", JOptionPane.YES_NO_OPTION); ! if(answer == JOptionPane.NO_OPTION) { ! return; ! } ! } ! rrdGraph.saveAsPNG(selectedFile.getAbsolutePath(), ! graphPanel.getWidth(), graphPanel.getHeight()); ! } catch (IOException e) { ! Util.error(this, "Could not save graph to file:\n" + e); ! } ! catch (RrdException e) { ! Util.error(this, "Could not save graph to file:\n" + e); ! } ! } ! } ! ! class GraphPanel extends JPanel { ! public void paintComponent(Graphics g) { ! try { ! rrdGraph.renderImage((Graphics2D) g, getWidth(), getHeight()); ! } catch (RrdException e) { ! Util.error(this, e); ! } catch (IOException e) { ! Util.error(this, e); ! } ! } ! } ! ! class GraphComboItem { ! private String description; ! private int dsIndex, arcIndex; ! ! GraphComboItem(String description, int dsIndex, int arcIndex) { ! this.description = description; ! this.dsIndex = dsIndex; ! this.arcIndex = arcIndex; ! } ! ! public String toString() { ! return description; ! } ! ! int getDsIndex() { ! return dsIndex; ! } ! ! int getArcIndex() { ! return arcIndex; ! } ! } ! } --- 1,302 ---- ! /* ============================================================ ! * JRobin : Pure java implementation of RRDTool's functionality ! * ============================================================ ! * ! * Project Info: http://www.jrobin.org ! * Project Lead: Sasa Markovic (sa...@jr...); ! * ! * (C) Copyright 2003, by Sasa Markovic. ! * ! * Developers: Sasa Markovic (sa...@jr...) ! * ! * ! * 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.inspector; ! ! import org.jrobin.core.*; ! import org.jrobin.graph.RrdGraphDef; ! import org.jrobin.graph.RrdGraph; ! import org.jrobin.graph.RrdGraphInfo; ! import org.jrobin.data.LinearInterpolator; ! ! import javax.swing.*; ! import javax.swing.filechooser.FileFilter; ! import java.awt.*; ! import java.awt.event.*; ! import java.io.IOException; ! import java.io.File; ! import java.io.RandomAccessFile; ! import java.util.Date; ! ! class GraphFrame extends JFrame { ! private static final Color COLOR = Color.RED; ! private static final int WIDTH = 400, HEIGHT = 240; ! private int deltaWidth = 0, deltaHeight = 0; ! ! private Color color = COLOR; ! private GraphPanel graphPanel = new GraphPanel(); ! private JComboBox graphCombo = new JComboBox(); ! private RrdGraph rrdGraph; ! ! private String sourcePath; ! private int dsIndex, arcIndex; ! ! GraphFrame(String sourcePath, int dsIndex, int arcIndex) { ! this.sourcePath = sourcePath; ! this.dsIndex = dsIndex; ! this.arcIndex = arcIndex; ! fillGraphCombo(); ! constructUI(); ! pack(); ! //createRrdGraph(); ! Util.placeWindow(this); ! setVisible(true); ! } ! ! private void createRrdGraph() { ! //System.out.println("Creating graph..."); ! try { ! RrdDb rrdDb = new RrdDb(sourcePath, true); ! RrdDef rrdDef; ! long[] timestamps; ! double[] values; ! String dsName; ! long t1, t2; ! try { ! Datasource ds = rrdDb.getDatasource(dsIndex); ! Archive arc = rrdDb.getArchive(arcIndex); ! Robin robin = arc.getRobin(dsIndex); ! dsName = ds.getDsName(); ! t1 = arc.getStartTime(); ! t2 = arc.getEndTime(); ! long step = arc.getArcStep(); ! int count = robin.getSize(); ! timestamps = new long[count]; ! for (int i = 0; i < count; i++) { ! timestamps[i] = t1 + i * step; ! } ! values = robin.getValues(); ! rrdDef = rrdDb.getRrdDef(); ! } ! finally { ! rrdDb.close(); ! } ! RrdGraphDef rrdGraphDef = new RrdGraphDef(); ! rrdGraphDef.setTimeSpan(t1, t2); ! rrdGraphDef.setImageFormat("png"); ! rrdGraphDef.setTitle(rrdDef.getDsDefs()[dsIndex].dump() + " " + ! rrdDef.getArcDefs()[arcIndex].dump()); ! LinearInterpolator linearInterpolator = new LinearInterpolator(timestamps, values); ! linearInterpolator.setInterpolationMethod(LinearInterpolator.INTERPOLATE_RIGHT); ! rrdGraphDef.datasource(dsName, linearInterpolator); ! rrdGraphDef.area(dsName, color, dsName + "\\r"); ! rrdGraphDef.comment("START: " + new Date(t1 * 1000L) + "\\r"); ! rrdGraphDef.comment("END: " + new Date(t2 * 1000L) + "\\r"); ! int width = graphPanel.getWidth(), height = graphPanel.getHeight(); ! rrdGraphDef.setWidth(width + deltaWidth); ! rrdGraphDef.setHeight(height + deltaHeight); ! rrdGraph = new RrdGraph(rrdGraphDef); ! if (deltaWidth == 0 && deltaHeight == 0) { ! RrdGraphInfo info = rrdGraph.getRrdGraphInfo(); ! deltaWidth = graphPanel.getWidth() - info.getWidth(); ! deltaHeight = graphPanel.getHeight() - info.getHeight(); ! if (deltaWidth != 0 && deltaHeight != 0) { ! createRrdGraph(); // recursion is divine! ! } ! } ! } ! catch (IOException e) { ! Util.error(this, e); ! } ! catch (RrdException e) { ! Util.error(this, e); ! } ! } ! ! private void fillGraphCombo() { ! try { ! RrdDb rrdDb = new RrdDb(sourcePath, true); ! try { ! RrdDef rrdDef = rrdDb.getRrdDef(); ! final DsDef[] dsDefs = rrdDef.getDsDefs(); ! final ArcDef[] arcDefs = rrdDef.getArcDefs(); ! GraphComboItem[] items = new GraphComboItem[rrdDef.getDsCount() * rrdDef.getArcCount()]; ! int selectedItem = -1; ! for (int i = 0, k = 0; i < rrdDef.getDsCount(); i++) { ! for (int j = 0; j < rrdDef.getArcCount(); k++, j++) { ! String description = dsDefs[i].dump() + " " + arcDefs[j].dump(); ! items[k] = new GraphComboItem(description, i, j); ! if (i == dsIndex && j == arcIndex) { ! selectedItem = k; ! } ! } ! } ! graphCombo.setModel(new DefaultComboBoxModel(items)); ! graphCombo.setSelectedIndex(selectedItem); ! } ! finally { ! rrdDb.close(); ! } ! } ! catch (IOException e) { ! Util.error(this, e); ! } ! catch (RrdException e) { ! Util.error(this, e); ! } ! } ! ! private void constructUI() { ! setTitle(new File(sourcePath).getName()); ! JPanel content = (JPanel) getContentPane(); ! content.setLayout(new BorderLayout(0, 0)); ! content.add(graphCombo, BorderLayout.NORTH); ! graphPanel.setPreferredSize(new Dimension(WIDTH, HEIGHT)); ! content.add(graphPanel, BorderLayout.CENTER); ! JPanel southPanel = new JPanel(); ! southPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 0, 0)); ! JButton colorButton = new JButton("Change graph color"); ! southPanel.add(colorButton); ! colorButton.addActionListener(new ActionListener() { ! public void actionPerformed(ActionEvent e) { ! changeColor(); ! } ! }); ! JButton saveButton = new JButton("Save graph"); ! saveButton.addActionListener(new ActionListener() { ! public void actionPerformed(ActionEvent e) { ! saveGraph(); ! } ! }); ! southPanel.add(Box.createHorizontalStrut(3)); ! southPanel.add(saveButton); ! content.add(southPanel, BorderLayout.SOUTH); ! // EVENT HANDLERS ! setDefaultCloseOperation(DISPOSE_ON_CLOSE); ! addWindowListener(new WindowAdapter() { ! public void windowClosing(WindowEvent e) { ! closeWindow(); ! } ! }); ! addComponentListener(new ComponentAdapter() { ! public void componentResized(ComponentEvent e) { ! createRrdGraph(); ! graphPanel.repaint(); ! } ! }); ! graphCombo.addItemListener(new ItemListener() { ! public void itemStateChanged(ItemEvent e) { ! if (e.getStateChange() == ItemEvent.SELECTED) { ! GraphComboItem item = (GraphComboItem) e.getItem(); ! dsIndex = item.getDsIndex(); ! arcIndex = item.getArcIndex(); ! createRrdGraph(); ! graphPanel.repaint(); ! } ! } ! }); ! } ! ! private void closeWindow() { ! Util.dismissWindow(this); ! } ! ! private void changeColor() { ! final JColorChooser picker = new JColorChooser(color); ! ActionListener okListener = new ActionListener() { ! public void actionPerformed(ActionEvent e) { ! color = picker.getColor(); ! createRrdGraph(); ! repaint(); ! } ! }; ! JColorChooser.createDialog(this, "Select color", true, picker, okListener, null).setVisible(true); ! } ! ! private void saveGraph() { ! JFileChooser chooser = new JFileChooser(); ! FileFilter filter = new FileFilter() { ! public boolean accept(File f) { ! return f.isDirectory() || f.getAbsolutePath().toLowerCase().endsWith(".png"); ! } ! ! public String getDescription() { ! return "PNG images"; ! } ! }; ! chooser.setFileFilter(filter); ! int returnVal = chooser.showSaveDialog(this); ! if (returnVal == JFileChooser.APPROVE_OPTION) { ! try { ! File selectedFile = chooser.getSelectedFile(); ! String path = selectedFile.getAbsolutePath(); ! if (!path.toLowerCase().endsWith(".png")) { ! path += ".png"; ! selectedFile = new File(path); ! } ! if (selectedFile.exists()) { ! // ask user to overwrite ! String message = "File [" + selectedFile.getName() + ! "] already exists. Do you want to overwrite it?"; ! int answer = JOptionPane.showConfirmDialog(this, ! message, "File exists", JOptionPane.YES_NO_OPTION); ! if (answer == JOptionPane.NO_OPTION) { ! return; ! } ! } ! String absolutePath = selectedFile.getAbsolutePath(); ! byte[] data = rrdGraph.getRrdGraphInfo().getBytes(); ! RandomAccessFile f = new RandomAccessFile(absolutePath, "rw"); ! try { ! f.write(data); ! } ! finally { ! f.close(); ! } ! } ! catch (IOException e) { ! Util.error(this, "Could not save graph to file:\n" + e); ! } ! } ! } ! ! class GraphPanel extends JPanel { ! public void paintComponent(Graphics g) { ! rrdGraph.render(g); ! } ! } ! ! class GraphComboItem { ! private String description; ! private int dsIndex, arcIndex; ! ! GraphComboItem(String description, int dsIndex, int arcIndex) { ! this.description = description; ! this.dsIndex = dsIndex; ! this.arcIndex = arcIndex; ! } ! ! public String toString() { ! return description; ! } ! ! int getDsIndex() { ! return dsIndex; ! } ! ! int getArcIndex() { ! return arcIndex; ! } ! } ! } Index: Util.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/inspector/Util.java,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** Util.java 27 Aug 2004 09:42:43 -0000 1.2 --- Util.java 21 Dec 2006 18:02:45 -0000 1.3 *************** *** 1,73 **** ! /* ============================================================ ! * JRobin : Pure java implementation of RRDTool's functionality ! * ============================================================ ! * ! * Project Info: http://www.jrobin.org ! * Project Lead: Sasa Markovic (sa...@jr...); ! * ! * (C) Copyright 2003, by Sasa Markovic. ! * ! * Developers: Sasa Markovic (sa...@jr...) ! * Arne Vandamme (cob...@jr...) ! * ! * This library is free software; you can redistribute it and/or modify it under the terms ! * of the GNU Lesser General Public License as published by the Free Software Foundation; ! * either version 2.1 of the License, or (at your option) any later version. ! * ! * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; ! * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. ! * See the GNU Lesser General Public License for more details. ! * ! * You should have received a copy of the GNU Lesser General Public License along with this ! * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, ! * Boston, MA 02111-1307, USA. ! */ ! package org.jrobin.inspector; ! ! import javax.swing.*; ! import java.awt.*; ! import java.util.Vector; ! ! class Util { ! static void centerOnScreen(Window window) { ! Toolkit t = Toolkit.getDefaultToolkit(); ! Dimension screenSize = t.getScreenSize(); ! Dimension frameSize = window.getPreferredSize(); ! double x = (screenSize.getWidth() - frameSize.getWidth()) / 2; ! double y = (screenSize.getHeight() - frameSize.getHeight()) / 2; ! window.setLocation((int) x, (int) y); ! } ! ! static void error(Component parent, String message) { ! JOptionPane.showMessageDialog(parent, message, "Error", JOptionPane.ERROR_MESSAGE); ! } ! ! static void error(Component parent, Exception e) { ! e.printStackTrace(); ! error(parent, e.toString()); ! } ! ! private static Vector windows = new Vector(); ! private static final int WINDOW_POSITION_SHIFT = 20; ! ! static void placeWindow(Window window) { ! int count = windows.size(); ! if(count == 0) { ! centerOnScreen(window); ! } ! else { ! Window last = (Window) windows.get(count - 1); ! int x = last.getX() + WINDOW_POSITION_SHIFT; ! int y = last.getY() + WINDOW_POSITION_SHIFT; ! window.setLocation(x, y); ! } ! windows.add(window); ! } ! ! static void dismissWindow(Window window) { ! windows.remove(window); ! if(windows.size() == 0) { ! System.exit(0); ! } ! } ! } --- 1,73 ---- ! /* ============================================================ ! * JRobin : Pure java implementation of RRDTool's functionality ! * ============================================================ ! * ! * Project Info: http://www.jrobin.org ! * Project Lead: Sasa Markovic (sa...@jr...); ! * ! * (C) Copyright 2003, by Sasa Markovic. ! * ! * Developers: Sasa Markovic (sa...@jr...) ! * ! * ! * 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.inspector; ! ! import javax.swing.*; ! import java.awt.*; ! import java.util.Vector; ! ! class Util { ! static void centerOnScreen(Window window) { ! Toolkit t = Toolkit.getDefaultToolkit(); ! Dimension screenSize = t.getScreenSize(); ! Dimension frameSize = window.getPreferredSize(); ! double x = (screenSize.getWidth() - frameSize.getWidth()) / 2; ! double y = (screenSize.getHeight() - frameSize.getHeight()) / 2; ! window.setLocation((int) x, (int) y); ! } ! ! static void error(Component parent, String message) { ! JOptionPane.showMessageDialog(parent, message, "Error", JOptionPane.ERROR_MESSAGE); ! } ! ! static void error(Component parent, Exception e) { ! e.printStackTrace(); ! error(parent, e.toString()); ! } ! ! private static Vector<Window> windows = new Vector<Window>(); ! private static final int WINDOW_POSITION_SHIFT = 20; ! ! static void placeWindow(Window window) { ! int count = windows.size(); ! if (count == 0) { ! centerOnScreen(window); ! } ! else { ! Window last = windows.get(count - 1); ! int x = last.getX() + WINDOW_POSITION_SHIFT; ! int y = last.getY() + WINDOW_POSITION_SHIFT; ! window.setLocation(x, y); ! } ! windows.add(window); ! } ! ! static void dismissWindow(Window window) { ! windows.remove(window); ! if (windows.size() == 0) { ! System.exit(0); ! } ! } ! } Index: EditDatasourceDialog.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/inspector/EditDatasourceDialog.java,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** EditDatasourceDialog.java 27 Aug 2004 09:42:43 -0000 1.2 --- EditDatasourceDialog.java 21 Dec 2006 18:02:44 -0000 1.3 *************** *** 1,208 **** ! /* ============================================================ ! * JRobin : Pure java implementation of RRDTool's functionality ! * ============================================================ ! * ! * Project Info: http://www.jrobin.org ! * Project Lead: Sasa Markovic (sa...@jr...); ! * ! * (C) Copyright 2003, by Sasa Markovic. ! * ! * Developers: Sasa Markovic (sa...@jr...) ! * Arne Vandamme (cob...@jr...) ! * ! * This library is free software; you can redistribute it and/or modify it under the terms ! * of the GNU Lesser General Public License as published by the Free Software Foundation; ! * either version 2.1 of the License, or (at your option) any later version. ! * ! * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; ! * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. ! * See the GNU Lesser General Public License for more details. ! * ! * You should have received a copy of the GNU Lesser General Public License along with this ! * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, ! * Boston, MA 02111-1307, USA. ! */ ! package org.jrobin.inspector; ! ! import org.jrobin.core.DsDef; ! import org.jrobin.core.RrdException; ! ! import javax.swing.*; ! import java.awt.*; ! import java.awt.event.WindowEvent; ! import java.awt.event.ActionListener; ! import java.awt.event.ActionEvent; ! ! class EditDatasourceDialog extends JDialog { ! private static final int FIELD_SIZE = 20; ! private static final String TITLE_NEW = "New datasource"; ! private static final String TITLE_EDIT = "Edit datasource"; ! ! private JLabel nameLabel = new JLabel("Datasource name: "); ! private JLabel typeLabel = new JLabel("Datasource type: "); ! private JLabel heartbeatLabel = new JLabel("Heartbeat: "); ! private JLabel minLabel = new JLabel("... [truncated message content] |
From: Tarus B. <ta...@us...> - 2006-12-21 18:02:48
|
Update of /cvsroot/jrobin/src/org/jrobin/data In directory sc8-pr-cvs6.sourceforge.net:/tmp/cvs-serv9082/org/jrobin/data Modified Files: Aggregates.java Aggregator.java CDef.java CubicSplineInterpolator.java DataProcessor.java Def.java LinearInterpolator.java Normalizer.java PDef.java Plottable.java RpnCalculator.java SDef.java Source.java Log Message: Adding the new 1.5.4 code Index: DataProcessor.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/data/DataProcessor.java,v retrieving revision 1.11 retrieving revision 1.12 diff -C2 -d -r1.11 -r1.12 *** DataProcessor.java 6 Apr 2005 20:10:09 -0000 1.11 --- DataProcessor.java 21 Dec 2006 18:02:43 -0000 1.12 *************** *** 1,961 **** ! /* ============================================================ ! * JRobin : Pure java implementation of RRDTool's functionality ! * ============================================================ ! * ! * Project Info: http://www.jrobin.org ! * Project Lead: Sasa Markovic (sa...@jr...); ! * ! * (C) Copyright 2003, by Sasa Markovic. ! * ! * Developers: Sasa Markovic (sa...@jr...) [...1825 lines suppressed...] ! System.out.println("Data processed in " + (System.currentTimeMillis() - laptime) + " milliseconds\n---"); ! System.out.println(dp.dump()); ! ! // aggregates ! System.out.println("\nAggregates for X"); ! Aggregates agg = dp.getAggregates("X"); ! System.out.println(agg.dump()); ! System.out.println("\nAggregates for Y"); ! agg = dp.getAggregates("Y"); ! System.out.println(agg.dump()); ! ! // 95-percentile ! System.out.println("\n95-percentile for X: " + Util.formatDouble(dp.get95Percentile("X"))); ! System.out.println("95-percentile for Y: " + Util.formatDouble(dp.get95Percentile("Y"))); ! ! // lastArchiveUpdateTime ! System.out.println("\nLast archive update time was: " + dp.getLastRrdArchiveUpdateTime()); ! } ! } ! Index: CDef.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/data/CDef.java,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** CDef.java 15 Dec 2004 14:55:41 -0000 1.2 --- CDef.java 21 Dec 2006 18:02:43 -0000 1.3 *************** *** 1,39 **** ! /* ============================================================ ! * JRobin : Pure java implementation of RRDTool's functionality ! * ============================================================ ! * ! * Project Info: http://www.jrobin.org ! * Project Lead: Sasa Markovic (sa...@jr...); ! * ! * (C) Copyright 2003, by Sasa Markovic. ! * ! * Developers: Sasa Markovic (sa...@jr...) ! * Arne Vandamme (cob...@jr...) ! * ! * This library is free software; you can redistribute it and/or modify it under the terms ! * of the GNU Lesser General Public License as published by the Free Software Foundation; ! * either version 2.1 of the License, or (at your option) any later version. ! * ! * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; ! * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. ! * See the GNU Lesser General Public License for more details. ! * ! * You should have received a copy of the GNU Lesser General Public License along with this ! * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, ! * Boston, MA 02111-1307, USA. ! */ ! ! package org.jrobin.data; ! ! class CDef extends Source { ! private String rpnExpression; ! ! CDef(String name, String rpnExpression) { ! super(name); ! this.rpnExpression = rpnExpression; ! } ! ! String getRpnExpression() { ! return rpnExpression; ! } ! } --- 1,39 ---- ! /* ============================================================ ! * JRobin : Pure java implementation of RRDTool's functionality ! * ============================================================ ! * ! * Project Info: http://www.jrobin.org ! * Project Lead: Sasa Markovic (sa...@jr...); ! * ! * (C) Copyright 2003-2005, by Sasa Markovic. ! * ! * Developers: Sasa Markovic (sa...@jr...) ! * ! * ! * This library is free software; you can redistribute it and/or modify it under the terms ! * of the GNU Lesser General Public License as published by the Free Software Foundation; ! * either version 2.1 of the License, or (at your option) any later version. ! * ! * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; ! * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. ! * See the GNU Lesser General Public License for more details. ! * ! * You should have received a copy of the GNU Lesser General Public License along with this ! * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, ! * Boston, MA 02111-1307, USA. ! */ ! ! package org.jrobin.data; ! ! class CDef extends Source { ! private String rpnExpression; ! ! CDef(String name, String rpnExpression) { ! super(name); ! this.rpnExpression = rpnExpression; ! } ! ! String getRpnExpression() { ! return rpnExpression; ! } ! } Index: Aggregates.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/data/Aggregates.java,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** Aggregates.java 6 Apr 2005 20:10:09 -0000 1.2 --- Aggregates.java 21 Dec 2006 18:02:42 -0000 1.3 *************** *** 1,136 **** ! /* ============================================================ ! * JRobin : Pure java implementation of RRDTool's functionality ! * ============================================================ ! * ! * Project Info: http://www.jrobin.org ! * Project Lead: Sasa Markovic (sa...@jr...); ! * ! * (C) Copyright 2003, by Sasa Markovic. ! * ! * Developers: Sasa Markovic (sa...@jr...) ! * Arne Vandamme (cob...@jr...) ! * ! * This library is free software; you can redistribute it and/or modify it under the terms ! * of the GNU Lesser General Public License as published by the Free Software Foundation; ! * either version 2.1 of the License, or (at your option) any later version. ! * ! * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; ! * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. ! * See the GNU Lesser General Public License for more details. ! * ! * You should have received a copy of the GNU Lesser General Public License along with this ! * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, ! * Boston, MA 02111-1307, USA. ! */ ! ! package org.jrobin.data; ! ! import org.jrobin.core.ConsolFuns; ! import org.jrobin.core.RrdException; ! import org.jrobin.core.Util; ! ! /** ! * Simple class which holds aggregated values (MIN, MAX, FIRST, LAST, AVERAGE and TOTAL). You ! * don't need to create objects of this class directly. Objects of this class are returned from ! * <code>getAggregates()</code> method in ! * {@link org.jrobin.core.FetchData#getAggregates(String) FetchData} and ! * {@link DataProcessor#getAggregates(String)} DataProcessor} classes. ! */ ! public class Aggregates implements ConsolFuns { ! double min = Double.NaN, max = Double.NaN; ! double first = Double.NaN, last = Double.NaN; ! double average = Double.NaN, total = Double.NaN; ! ! Aggregates() { ! // NOP; ! } ! ! /** ! * Returns the minimal value ! * @return Minimal value ! */ ! public double getMin() { ! return min; ! } ! ! /** ! * Returns the maximum value ! * @return Maximum value ! */ ! public double getMax() { ! return max; ! } ! ! /** ! * Returns the first falue ! * @return First value ! */ ! public double getFirst() { ! return first; ! } ! ! /** ! * Returns the last value ! * @return Last value ! */ ! public double getLast() { ! return last; ! } ! ! /** ! * Returns average ! * @return Average value ! */ ! public double getAverage() { ! return average; ! } ! ! /** ! * Returns total value ! * @return Total value ! */ ! public double getTotal() { ! return total; ! } ! ! /** ! * Returns single aggregated value for the give consolidation function ! * @param consolFun Consolidation function: MIN, MAX, FIRST, LAST, AVERAGE, TOTAL. These constanst ! * are conveniently defined in the {@link org.jrobin.core.ConsolFuns ConsolFuns} interface. ! * @return Aggregated value ! * @throws RrdException Thrown if unsupported consolidation function is supplied ! */ ! public double getAggregate(String consolFun) throws RrdException { ! if(consolFun.equals(CF_AVERAGE) || consolFun.equalsIgnoreCase( "AVG" ) ) { ! return average; ! } ! else if(consolFun.equals(CF_FIRST)) { ! return first; ! } ! else if(consolFun.equals(CF_LAST)) { ! return last; ! } ! else if(consolFun.equals(CF_MAX) || consolFun.equalsIgnoreCase( "MAXIMUM" ) ) { ! return max; ! } ! else if(consolFun.equals(CF_MIN) || consolFun.equalsIgnoreCase( "MINIMUM" ) ) { ! return min; ! } ! else if(consolFun.equals(CF_TOTAL)) { ! return total; ! } ! else { ! throw new RrdException("Unknown consolidation function: " + consolFun); ! } ! } ! ! /** ! * Returns String representing all aggregated values. Just for debugging purposes. ! * @return String containing all aggregated values ! */ ! public String dump() { ! return "MIN=" + Util.formatDouble(min) + ", MAX=" + Util.formatDouble(max) + "\n" + ! "FIRST=" + Util.formatDouble(first) + ", LAST=" + Util.formatDouble(last) + "\n" + ! "AVERAGE=" + Util.formatDouble(average) + ", TOTAL=" + Util.formatDouble(total); ! } ! } --- 1,144 ---- ! /* ============================================================ ! * JRobin : Pure java implementation of RRDTool's functionality ! * ============================================================ ! * ! * Project Info: http://www.jrobin.org ! * Project Lead: Sasa Markovic (sa...@jr...); ! * ! * (C) Copyright 2003-2005, by Sasa Markovic. ! * ! * Developers: Sasa Markovic (sa...@jr...) ! * ! * ! * This library is free software; you can redistribute it and/or modify it under the terms ! * of the GNU Lesser General Public License as published by the Free Software Foundation; ! * either version 2.1 of the License, or (at your option) any later version. ! * ! * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; ! * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. ! * See the GNU Lesser General Public License for more details. ! * ! * You should have received a copy of the GNU Lesser General Public License along with this ! * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, ! * Boston, MA 02111-1307, USA. ! */ ! ! package org.jrobin.data; ! ! import org.jrobin.core.ConsolFuns; ! import org.jrobin.core.RrdException; ! import org.jrobin.core.Util; ! ! /** ! * Simple class which holds aggregated values (MIN, MAX, FIRST, LAST, AVERAGE and TOTAL). You ! * don't need to create objects of this class directly. Objects of this class are returned from ! * <code>getAggregates()</code> method in ! * {@link org.jrobin.core.FetchData#getAggregates(String) FetchData} and ! * {@link DataProcessor#getAggregates(String)} DataProcessor} classes. ! */ ! public class Aggregates implements ConsolFuns { ! double min = Double.NaN, max = Double.NaN; ! double first = Double.NaN, last = Double.NaN; ! double average = Double.NaN, total = Double.NaN; ! ! Aggregates() { ! // NOP; ! } ! ! /** ! * Returns the minimal value ! * ! * @return Minimal value ! */ ! public double getMin() { ! return min; ! } ! ! /** ! * Returns the maximum value ! * ! * @return Maximum value ! */ ! public double getMax() { ! return max; ! } ! ! /** ! * Returns the first falue ! * ! * @return First value ! */ ! public double getFirst() { ! return first; ! } ! ! /** ! * Returns the last value ! * ! * @return Last value ! */ ! public double getLast() { ! return last; ! } ! ! /** ! * Returns average ! * ! * @return Average value ! */ ! public double getAverage() { ! return average; ! } ! ! /** ! * Returns total value ! * ! * @return Total value ! */ ! public double getTotal() { ! return total; ! } ! ! /** ! * Returns single aggregated value for the give consolidation function ! * ! * @param consolFun Consolidation function: MIN, MAX, FIRST, LAST, AVERAGE, TOTAL. These constanst ! * are conveniently defined in the {@link org.jrobin.core.ConsolFuns ConsolFuns} interface. ! * @return Aggregated value ! * @throws RrdException Thrown if unsupported consolidation function is supplied ! */ ! public double getAggregate(String consolFun) throws RrdException { ! if (consolFun.equals(CF_AVERAGE)) { ! return average; ! } ! else if (consolFun.equals(CF_FIRST)) { ! return first; ! } ! else if (consolFun.equals(CF_LAST)) { ! return last; ! } ! else if (consolFun.equals(CF_MAX)) { ! return max; ! } ! else if (consolFun.equals(CF_MIN)) { ! return min; ! } ! else if (consolFun.equals(CF_TOTAL)) { ! return total; ! } ! else { ! throw new RrdException("Unknown consolidation function: " + consolFun); ! } ! } ! ! /** ! * Returns String representing all aggregated values. Just for debugging purposes. ! * ! * @return String containing all aggregated values ! */ ! public String dump() { ! return "MIN=" + Util.formatDouble(min) + ", MAX=" + Util.formatDouble(max) + "\n" + ! "FIRST=" + Util.formatDouble(first) + ", LAST=" + Util.formatDouble(last) + "\n" + ! "AVERAGE=" + Util.formatDouble(average) + ", TOTAL=" + Util.formatDouble(total); ! } ! } Index: Plottable.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/data/Plottable.java,v retrieving revision 1.1.1.1 retrieving revision 1.2 diff -C2 -d -r1.1.1.1 -r1.2 *** Plottable.java 6 Sep 2005 20:40:54 -0000 1.1.1.1 --- Plottable.java 21 Dec 2006 18:02:43 -0000 1.2 *************** *** 30,42 **** * that represents that datasource, and then pass this class on to the RrdGraphDef.</p> */ ! public abstract class Plottable ! { /** * Retrieves datapoint value based on a given timestamp. * Use this method if you only have one series of data in this class. * @param timestamp Timestamp in seconds for the datapoint. * @return Double value of the datapoint. */ ! public double getValue( long timestamp ) { return Double.NaN; } --- 30,42 ---- * that represents that datasource, and then pass this class on to the RrdGraphDef.</p> */ ! public abstract class Plottable { /** * Retrieves datapoint value based on a given timestamp. * Use this method if you only have one series of data in this class. + * * @param timestamp Timestamp in seconds for the datapoint. * @return Double value of the datapoint. */ ! public double getValue(long timestamp) { return Double.NaN; } Index: Source.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/data/Source.java,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** Source.java 29 Dec 2004 11:36:50 -0000 1.4 --- Source.java 21 Dec 2006 18:02:43 -0000 1.5 *************** *** 1,69 **** ! /* ============================================================ ! * JRobin : Pure java implementation of RRDTool's functionality ! * ============================================================ ! * ! * Project Info: http://www.jrobin.org ! * Project Lead: Sasa Markovic (sa...@jr...); ! * ! * (C) Copyright 2003, by Sasa Markovic. ! * ! * Developers: Sasa Markovic (sa...@jr...) ! * Arne Vandamme (cob...@jr...) ! * ! * This library is free software; you can redistribute it and/or modify it under the terms ! * of the GNU Lesser General Public License as published by the Free Software Foundation; ! * either version 2.1 of the License, or (at your option) any later version. ! * ! * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; ! * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. ! * See the GNU Lesser General Public License for more details. ! * ! * You should have received a copy of the GNU Lesser General Public License along with this ! * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, ! * Boston, MA 02111-1307, USA. ! */ ! ! package org.jrobin.data; ! ! import org.jrobin.core.ConsolFuns; ! import org.jrobin.core.RrdException; ! ! abstract class Source implements ConsolFuns { ! final private String name; ! protected double[] values; ! protected long[] timestamps; ! ! Source(String name) { ! this.name = name; ! } ! ! String getName() { ! return name; ! } ! ! void setValues(double[] values) { ! this.values = values; ! } ! ! void setTimestamps(long[] timestamps) { ! this.timestamps = timestamps; ! } ! ! double[] getValues() { ! return values; ! } ! ! long[] getTimestamps() { ! return timestamps; ! } ! ! Aggregates getAggregates(long tStart, long tEnd) throws RrdException { ! Aggregator agg = new Aggregator(timestamps, values); ! return agg.getAggregates(tStart, tEnd); ! } ! ! double getPercentile(long tStart, long tEnd, double percentile) throws RrdException { ! Aggregator agg = new Aggregator(timestamps, values); ! return agg.getPercentile(tStart, tEnd, percentile); ! } ! } --- 1,69 ---- ! /* ============================================================ ! * JRobin : Pure java implementation of RRDTool's functionality ! * ============================================================ ! * ! * Project Info: http://www.jrobin.org ! * Project Lead: Sasa Markovic (sa...@jr...); ! * ! * (C) Copyright 2003-2005, by Sasa Markovic. ! * ! * Developers: Sasa Markovic (sa...@jr...) ! * ! * ! * This library is free software; you can redistribute it and/or modify it under the terms ! * of the GNU Lesser General Public License as published by the Free Software Foundation; ! * either version 2.1 of the License, or (at your option) any later version. ! * ! * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; ! * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. ! * See the GNU Lesser General Public License for more details. ! * ! * You should have received a copy of the GNU Lesser General Public License along with this ! * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, ! * Boston, MA 02111-1307, USA. ! */ ! ! package org.jrobin.data; ! ! import org.jrobin.core.ConsolFuns; ! import org.jrobin.core.RrdException; ! ! abstract class Source implements ConsolFuns { ! final private String name; ! protected double[] values; ! protected long[] timestamps; ! ! Source(String name) { ! this.name = name; ! } ! ! String getName() { ! return name; ! } ! ! void setValues(double[] values) { ! this.values = values; ! } ! ! void setTimestamps(long[] timestamps) { ! this.timestamps = timestamps; ! } ! ! double[] getValues() { ! return values; ! } ! ! long[] getTimestamps() { ! return timestamps; ! } ! ! Aggregates getAggregates(long tStart, long tEnd) throws RrdException { ! Aggregator agg = new Aggregator(timestamps, values); ! return agg.getAggregates(tStart, tEnd); ! } ! ! double getPercentile(long tStart, long tEnd, double percentile) throws RrdException { ! Aggregator agg = new Aggregator(timestamps, values); ! return agg.getPercentile(tStart, tEnd, percentile); ! } ! } Index: Aggregator.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/data/Aggregator.java,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** Aggregator.java 29 Dec 2004 11:36:50 -0000 1.3 --- Aggregator.java 21 Dec 2006 18:02:42 -0000 1.4 *************** *** 1,113 **** ! /* ============================================================ ! * JRobin : Pure java implementation of RRDTool's functionality ! * ============================================================ ! * ! * Project Info: http://www.jrobin.org ! * Project Lead: Sasa Markovic (sa...@jr...); ! * ! * (C) Copyright 2003, by Sasa Markovic. ! * ! * Developers: Sasa Markovic (sa...@jr...) ! * Arne Vandamme (cob...@jr...) ! * ! * This library is free software; you can redistribute it and/or modify it under the terms ! * of the GNU Lesser General Public License as published by the Free Software Foundation; ! * either version 2.1 of the License, or (at your option) any later version. ! * ! * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; ! * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. ! * See the GNU Lesser General Public License for more details. ! * ! * You should have received a copy of the GNU Lesser General Public License along with this ! * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, ! * Boston, MA 02111-1307, USA. ! */ ! ! package org.jrobin.data; ! ! import org.jrobin.core.ConsolFuns; ! import org.jrobin.core.Util; ! ! import java.util.List; ! import java.util.ArrayList; ! import java.util.Arrays; ! ! class Aggregator implements ConsolFuns { ! private long timestamps[], step; ! private double[] values; ! ! Aggregator(long[] timestamps, double[] values) { ! assert timestamps.length == values.length: "Incompatible timestamps/values arrays (unequal lengths)"; ! assert timestamps.length >= 2: "At least two timestamps must be supplied"; ! this.timestamps = timestamps; ! this.values = values; ! this.step = timestamps[1] - timestamps[0]; ! } ! ! Aggregates getAggregates(long tStart, long tEnd) { ! Aggregates agg = new Aggregates(); ! long totalSeconds = 0; ! boolean firstFound = false; ! for (int i = 0; i < timestamps.length; i++) { ! long left = Math.max(timestamps[i] - step, tStart); ! long right = Math.min(timestamps[i], tEnd); ! long delta = right - left; ! if (delta > 0) { ! double value = values[i]; ! agg.min = Util.min(agg.min, value); ! agg.max = Util.max(agg.max, value); ! if (!firstFound) { ! agg.first = value; ! firstFound = true; ! } ! agg.last = value; ! if (!Double.isNaN(value)) { ! agg.total = Util.sum(agg.total, delta * value); ! totalSeconds += delta; ! } ! } ! } ! agg.average = totalSeconds > 0 ? (agg.total / totalSeconds) : Double.NaN; ! return agg; ! } ! ! double getPercentile(long tStart, long tEnd, double percentile) { ! List valueList = new ArrayList(); ! // create a list of included datasource values (different from NaN) ! for (int i = 0; i < timestamps.length; i++) { ! long left = Math.max(timestamps[i] - step, tStart); ! long right = Math.min(timestamps[i], tEnd); ! if (right > left && !Double.isNaN(values[i])) { ! valueList.add(new Double(values[i])); ! } ! } ! // create an array to work with ! int count = valueList.size(); ! if (count > 1) { ! double[] valuesCopy = new double[count]; ! for (int i = 0; i < count; i++) { ! valuesCopy[i] = ((Double) valueList.get(i)).doubleValue(); ! } ! // sort array ! Arrays.sort(valuesCopy); ! // skip top (100% - percentile) values ! double topPercentile = (100.0 - percentile) / 100.0; ! count -= (int) Math.ceil(count * topPercentile); ! // if we have anything left... ! if (count > 0) { ! return valuesCopy[count - 1]; ! } ! } ! // not enough data available ! return Double.NaN; ! } ! ! /* ! public static void main(String[] args) { ! long[] t = {10, 20, 30, 40}; ! double[] v = {2, Double.NaN, 3, 1}; ! Aggregator agg = new Aggregator(t, v); ! System.out.println(agg.getAggregates(0, 40).dump()); ! } ! */ ! } --- 1,104 ---- ! /* ============================================================ ! * JRobin : Pure java implementation of RRDTool's functionality ! * ============================================================ ! * ! * Project Info: http://www.jrobin.org ! * Project Lead: Sasa Markovic (sa...@jr...); ! * ! * (C) Copyright 2003-2005, by Sasa Markovic. ! * ! * Developers: Sasa Markovic (sa...@jr...) ! * ! * ! * This library is free software; you can redistribute it and/or modify it under the terms ! * of the GNU Lesser General Public License as published by the Free Software Foundation; ! * either version 2.1 of the License, or (at your option) any later version. ! * ! * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; ! * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. ! * See the GNU Lesser General Public License for more details. ! * ! * You should have received a copy of the GNU Lesser General Public License along with this ! * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, ! * Boston, MA 02111-1307, USA. ! */ ! ! package org.jrobin.data; ! ! import org.jrobin.core.ConsolFuns; ! import org.jrobin.core.Util; ! ! import java.util.ArrayList; ! import java.util.Arrays; ! import java.util.List; ! ! class Aggregator implements ConsolFuns { ! private long timestamps[], step; ! private double[] values; ! ! Aggregator(long[] timestamps, double[] values) { ! assert timestamps.length == values.length: "Incompatible timestamps/values arrays (unequal lengths)"; ! assert timestamps.length >= 2: "At least two timestamps must be supplied"; ! this.timestamps = timestamps; ! this.values = values; ! this.step = timestamps[1] - timestamps[0]; ! } ! ! Aggregates getAggregates(long tStart, long tEnd) { ! Aggregates agg = new Aggregates(); ! long totalSeconds = 0; ! boolean firstFound = false; ! for (int i = 0; i < timestamps.length; i++) { ! long left = Math.max(timestamps[i] - step, tStart); ! long right = Math.min(timestamps[i], tEnd); ! long delta = right - left; ! if (delta > 0) { ! double value = values[i]; ! agg.min = Util.min(agg.min, value); ! agg.max = Util.max(agg.max, value); ! if (!firstFound) { ! agg.first = value; ! firstFound = true; ! } ! agg.last = value; ! if (!Double.isNaN(value)) { ! agg.total = Util.sum(agg.total, delta * value); ! totalSeconds += delta; ! } ! } ! } ! agg.average = totalSeconds > 0 ? (agg.total / totalSeconds) : Double.NaN; ! return agg; ! } ! ! double getPercentile(long tStart, long tEnd, double percentile) { ! List<Double> valueList = new ArrayList<Double>(); ! // create a list of included datasource values (different from NaN) ! for (int i = 0; i < timestamps.length; i++) { ! long left = Math.max(timestamps[i] - step, tStart); ! long right = Math.min(timestamps[i], tEnd); ! if (right > left && !Double.isNaN(values[i])) { ! valueList.add(values[i]); ! } ! } ! // create an array to work with ! int count = valueList.size(); ! if (count > 1) { ! double[] valuesCopy = new double[count]; ! for (int i = 0; i < count; i++) { ! valuesCopy[i] = valueList.get(i); ! } ! // sort array ! Arrays.sort(valuesCopy); ! // skip top (100% - percentile) values ! double topPercentile = (100.0 - percentile) / 100.0; ! count -= (int) Math.ceil(count * topPercentile); ! // if we have anything left... ! if (count > 0) { ! return valuesCopy[count - 1]; ! } ! } ! // not enough data available ! return Double.NaN; ! } ! } Index: Normalizer.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/data/Normalizer.java,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** Normalizer.java 15 Dec 2004 14:55:41 -0000 1.1 --- Normalizer.java 21 Dec 2006 18:02:43 -0000 1.2 *************** *** 1,104 **** ! /* ============================================================ ! * JRobin : Pure java implementation of RRDTool's functionality ! * ============================================================ ! * ! * Project Info: http://www.jrobin.org ! * Project Lead: Sasa Markovic (sa...@jr...); ! * ! * (C) Copyright 2003, by Sasa Markovic. ! * ! * Developers: Sasa Markovic (sa...@jr...) ! * Arne Vandamme (cob...@jr...) ! * ! * This library is free software; you can redistribute it and/or modify it under the terms ! * of the GNU Lesser General Public License as published by the Free Software Foundation; ! * either version 2.1 of the License, or (at your option) any later version. ! * ! * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; ! * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. ! * See the GNU Lesser General Public License for more details. ! * ! * You should have received a copy of the GNU Lesser General Public License along with this ! * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, ! * Boston, MA 02111-1307, USA. ! */ ! ! package org.jrobin.data; ! ! import org.jrobin.core.Util; ! import java.util.Arrays; ! ! class Normalizer { ! private long[] timestamps; ! int count; ! long step; ! ! Normalizer(long[] timestamps) { ! this.timestamps = timestamps; ! this.step = timestamps[1] - timestamps[0]; ! this.count = timestamps.length; ! } ! ! double[] normalize(long[] rawTimestamps, double[] rawValues) { ! int rawCount = rawTimestamps.length; ! long rawStep = rawTimestamps[1] - rawTimestamps[0]; ! // check if we have a simple match ! if(rawCount == count && rawStep == step && rawTimestamps[0] == timestamps[0]) { ! return getCopyOf(rawValues); ! } ! // reset all normalized values to NaN ! double[] values = new double[count]; ! Arrays.fill(values, Double.NaN); ! for (int rawSeg = 0, seg = 0; rawSeg < rawCount && seg < count; rawSeg++) { ! double rawValue = rawValues[rawSeg]; ! if (!Double.isNaN(rawValue)) { ! long rawLeft = rawTimestamps[rawSeg] - rawStep; ! while (seg < count && rawLeft >= timestamps[seg]) { ! seg++; ! } ! boolean overlap = true; ! for (int fillSeg = seg; overlap && fillSeg < count; fillSeg++) { ! long left = timestamps[fillSeg] - step; ! long t1 = Math.max(rawLeft, left); ! long t2 = Math.min(rawTimestamps[rawSeg], timestamps[fillSeg]); ! if (t1 < t2) { ! values[fillSeg] = Util.sum(values[fillSeg], (t2 - t1) * rawValues[rawSeg]); ! } ! else { ! overlap = false; ! } ! } ! } ! } ! for (int seg = 0; seg < count; seg++) { ! values[seg] /= step; ! } ! return values; ! } ! ! private static double[] getCopyOf(double[] rawValues) { ! int n = rawValues.length; ! double[] values = new double[n]; ! for(int i = 0; i < n; i++) { ! values[i] = rawValues[i]; ! } ! return values; ! } ! ! private static void dump(long[] t, double[] v) { ! for(int i = 0; i < v.length; i++) { ! System.out.print("[" + t[i] + "," + v[i] + "] "); ! } ! System.out.println(""); ! } ! ! public static void main(String[] args) { ! long rawTime[] = {100, 120, 140, 160, 180, 200}; ! double rawValues[] = {10, 30, 20, Double.NaN, 50, 40}; ! long time[] = {60, 100, 140, 180, 220, 260, 300}; ! Normalizer n = new Normalizer(time); ! double[] values = n.normalize(rawTime, rawValues); ! dump(rawTime, rawValues); ! dump(time, values); ! } ! } --- 1,87 ---- ! /* ============================================================ ! * JRobin : Pure java implementation of RRDTool's functionality ! * ============================================================ ! * ! * Project Info: http://www.jrobin.org ! * Project Lead: Sasa Markovic (sa...@jr...); ! * ! * (C) Copyright 2003-2005, by Sasa Markovic. ! * ! * Developers: Sasa Markovic (sa...@jr...) ! * ! * ! * This library is free software; you can redistribute it and/or modify it under the terms ! * of the GNU Lesser General Public License as published by the Free Software Foundation; ! * either version 2.1 of the License, or (at your option) any later version. ! * ! * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; ! * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. ! * See the GNU Lesser General Public License for more details. ! * ! * You should have received a copy of the GNU Lesser General Public License along with this ! * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, ! * Boston, MA 02111-1307, USA. ! */ ! ! package org.jrobin.data; ! ! import org.jrobin.core.Util; ! ! import java.util.Arrays; ! ! class Normalizer { ! final private long[] timestamps; ! final int count; ! final long step; ! ! Normalizer(long[] timestamps) { ! this.timestamps = timestamps; ! this.step = timestamps[1] - timestamps[0]; ! this.count = timestamps.length; ! } ! ! double[] normalize(long[] rawTimestamps, double[] rawValues) { ! int rawCount = rawTimestamps.length; ! long rawStep = rawTimestamps[1] - rawTimestamps[0]; ! // check if we have a simple match ! if (rawCount == count && rawStep == step && rawTimestamps[0] == timestamps[0]) { ! return getCopyOf(rawValues); ! } ! // reset all normalized values to NaN ! double[] values = new double[count]; ! Arrays.fill(values, Double.NaN); ! for (int rawSeg = 0, seg = 0; rawSeg < rawCount && seg < count; rawSeg++) { ! double rawValue = rawValues[rawSeg]; ! if (!Double.isNaN(rawValue)) { ! long rawLeft = rawTimestamps[rawSeg] - rawStep; ! while (seg < count && rawLeft >= timestamps[seg]) { ! seg++; ! } ! boolean overlap = true; ! for (int fillSeg = seg; overlap && fillSeg < count; fillSeg++) { ! long left = timestamps[fillSeg] - step; ! long t1 = Math.max(rawLeft, left); ! long t2 = Math.min(rawTimestamps[rawSeg], timestamps[fillSeg]); ! if (t1 < t2) { ! values[fillSeg] = Util.sum(values[fillSeg], (t2 - t1) * rawValues[rawSeg]); ! } ! else { ! overlap = false; ! } ! } ! } ! } ! for (int seg = 0; seg < count; seg++) { ! values[seg] /= step; ! } ! return values; ! } ! ! private static double[] getCopyOf(double[] rawValues) { ! int n = rawValues.length; ! double[] values = new double[n]; ! System.arraycopy(rawValues, 0, values, 0, n); ! return values; ! } ! } ! Index: SDef.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/data/SDef.java,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** SDef.java 29 Dec 2004 11:36:50 -0000 1.3 --- SDef.java 21 Dec 2006 18:02:43 -0000 1.4 *************** *** 1,69 **** ! /* ============================================================ ! * JRobin : Pure java implementation of RRDTool's functionality ! * ============================================================ ! * ! * Project Info: http://www.jrobin.org ! * Project Lead: Sasa Markovic (sa...@jr...); ! * ! * (C) Copyright 2003, by Sasa Markovic. ! * ! * Developers: Sasa Markovic (sa...@jr...) ! * Arne Vandamme (cob...@jr...) ! * ! * This library is free software; you can redistribute it and/or modify it under the terms ! * of the GNU Lesser General Public License as published by the Free Software Foundation; ! * either version 2.1 of the License, or (at your option) any later version. ! * ! * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; ! * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. ! * See the GNU Lesser General Public License for more details. ! * ! * You should have received a copy of the GNU Lesser General Public License along with this ! * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, ! * Boston, MA 02111-1307, USA. ! */ ! ! package org.jrobin.data; ! ! import org.jrobin.core.RrdException; ! ! class SDef extends Source { ! private String defName; ! private String consolFun; ! private double value; ! ! SDef(String name, String defName, String consolFun) { ! super(name); ! this.defName = defName; ! this.consolFun = consolFun; ! } ! ! String getDefName() { ! return defName; ! } ! ! String getConsolFun() { ! return consolFun; ! } ! ! void setValue(double value) { ! this.value = value; ! int count = getTimestamps().length; ! double[] values = new double[count]; ! for(int i = 0; i < count; i++) { ! values[i] = value; ! } ! setValues(values); ! } ! ! Aggregates getAggregates(long tStart, long tEnd) throws RrdException { ! Aggregates agg = new Aggregates(); ! agg.first = agg.last = agg.min = agg.max = agg.average = value; ! agg.total = value * (tEnd - tStart); ! return agg; ! } ! ! double getPercentile(long tStart, long tEnd, double percentile) throws RrdException { ! return value; ! } ! } --- 1,69 ---- ! /* ============================================================ ! * JRobin : Pure java implementation of RRDTool's functionality ! * ============================================================ ! * ! * Project Info: http://www.jrobin.org ! * Project Lead: Sasa Markovic (sa...@jr...); ! * ! * (C) Copyright 2003-2005, by Sasa Markovic. ! * ! * Developers: Sasa Markovic (sa...@jr...) ! * ! * ! * This library is free software; you can redistribute it and/or modify it under the terms ! * of the GNU Lesser General Public License as published by the Free Software Foundation; ! * either version 2.1 of the License, or (at your option) any later version. ! * ! * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; ! * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. ! * See the GNU Lesser General Public License for more details. ! * ! * You should have received a copy of the GNU Lesser General Public License along with this ! * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, ! * Boston, MA 02111-1307, USA. ! */ ! ! package org.jrobin.data; ! ! import org.jrobin.core.RrdException; ! ! class SDef extends Source { ! private String defName; ! private String consolFun; ! private double value; ! ! SDef(String name, String defName, String consolFun) { ! super(name); ! this.defName = defName; ! this.consolFun = consolFun; ! } ! ! String getDefName() { ! return defName; ! } ! ! String getConsolFun() { ! return consolFun; ! } ! ! void setValue(double value) { ! this.value = value; ! int count = getTimestamps().length; ! double[] values = new double[count]; ! for (int i = 0; i < count; i++) { ! values[i] = value; ! } ! setValues(values); ! } ! ! Aggregates getAggregates(long tStart, long tEnd) throws RrdException { ! Aggregates agg = new Aggregates(); ! agg.first = agg.last = agg.min = agg.max = agg.average = value; ! agg.total = value * (tEnd - tStart); ! return agg; ! } ! ! double getPercentile(long tStart, long tEnd, double percentile) throws RrdException { ! return value; ! } ! } Index: RpnCalculator.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/data/RpnCalculator.java,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** RpnCalculator.java 15 Dec 2004 14:55:41 -0000 1.3 --- RpnCalculator.java 21 Dec 2006 18:02:43 -0000 1.4 *************** *** 1,562 **** ! /* ============================================================ ! * JRobin : Pure java implementation of RRDTool's functionality ! * ============================================================ ! * ! * Project Info: http://www.jrobin.org ! * Project Lead: Sasa Markovic (sa...@jr...); ! * ! * (C) Copyright 2003, by Sasa Markovic. ! * ! * Developers: Sasa Markovic (sa...@jr...) [...1092 lines suppressed...] ! } ! return stack[pos - 1]; ! } ! ! void reset() { ! pos = 0; ! } ! ! boolean isEmpty() { ! return pos <= 0; ! } ! } ! ! private class Token { ! byte id = -1; ! double number = Double.NaN; ! String variable = null; ! double[] values = null; ! } ! } Index: Def.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/data/Def.java,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** Def.java 29 Dec 2004 11:36:50 -0000 1.5 --- Def.java 21 Dec 2006 18:02:43 -0000 1.6 *************** *** 1,119 **** ! /* ============================================================ ! * JRobin : Pure java implementation of RRDTool's functionality ! * ============================================================ ! * ! * Project Info: http://www.jrobin.org ! * Project Lead: Sasa Markovic (sa...@jr...); ! * ! * (C) Copyright 2003, by Sasa Markovic. ! * ! * Developers: Sasa Markovic (sa...@jr...) ! * Arne Vandamme (cob...@jr...) ! * ! * This library is free software; you can redistribute it and/or modify it under the terms ! * of the GNU Lesser General Public License as published by the Free Software Foundation; ! * either version 2.1 of the License, or (at your option) any later version. ! * ! * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; ! * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. ! * See the GNU Lesser General Public License for more details. ! * ! * You should have received a copy of the GNU Lesser General Public License along with this ! * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, ! * Boston, MA 02111-1307, USA. ! */ ! ! package org.jrobin.data; ! ! import org.jrobin.core.Util; ! import org.jrobin.core.FetchData; ! import org.jrobin.core.RrdException; ! ! import java.io.IOException; ! ! class Def extends Source { ! private String path, dsName, consolFun, backend; ! private FetchData fetchData; ! ! Def(String name, FetchData fetchData) { ! this(name, null, name, null, null); ! setFetchData(fetchData); ! } ! ! Def(String name, String path, String dsName, String consolFunc) { ! this(name, path, dsName, consolFunc, null); ! } ! ! Def(String name, String path, String dsName, String consolFunc, String backend) { ! super(name); ! this.path = path; ! this.dsName = dsName; ! this.consolFun = consolFunc; ! this.backend = backend; ! } ! ! String getPath() { ! return path; ! } ! ! String getCanonicalPath() throws IOException { ! return Util.getCanonicalPath(path); ! } ! ! String getDsName() { ! return dsName; ! } ! ! String getConsolFun() { ! return consolFun; ! } ! ! String getBackend() { ! return backend; ! } ! ! boolean isCompatibleWith(Def def) throws IOException { ! return getCanonicalPath().equals(def.getCanonicalPath()) && ! getConsolFun().equals(def.consolFun) && ! ((backend == null && def.backend == null) || ! (backend != null && def.backend != null && backend.equals(def.backend))); ! } ! ! void setFetchData(FetchData fetchData) { ! this.fetchData = fetchData; ! } ! ! long[] getRrdTimestamps() { ! return fetchData.getTimestamps(); ! } ! ! double[] getRrdValues() throws RrdException { ! return fetchData.getValues(dsName); ! } ! ! long getArchiveEndTime() { ! return fetchData.getArcEndTime(); ! } ! ! long getFetchStep() { ! return fetchData.getStep(); ! } ! ! Aggregates getAggregates(long tStart, long tEnd) throws RrdException { ! long[] t = getRrdTimestamps(); ! double[] v = getRrdValues(); ! Aggregator agg = new Aggregator(t, v); ! return agg.getAggregates(tStart, tEnd); ! } ! ! double getPercentile(long tStart, long tEnd, double percentile) throws RrdException { ! long[] t = getRrdTimestamps(); ! double[] v = getRrdValues(); ! Aggregator agg = new Aggregator(t, v); ! return agg.getPercentile(tStart, tEnd, percentile); ! } ! ! boolean isLoaded() { ! return fetchData != null; ! } ! } --- 1,119 ---- ! /* ============================================================ ! * JRobin : Pure java implementation of RRDTool's functionality ! * ============================================================ ! * ! * Project Info: http://www.jrobin.org ! * Project Lead: Sasa Markovic (sa...@jr...); ! * ! * (C) Copyright 2003-2005, by Sasa Markovic. ! * ! * Developers: Sasa Markovic (sa...@jr...) ! * ! * ! * This library is free software; you can redistribute it and/or modify it under the terms ! * of the GNU Lesser General Public License as published by the Free Software Foundation; ! * either version 2.1 of the License, or (at your option) any later version. ! * ! * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; ! * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. ! * See the GNU Lesser General Public License for more details. ! * ! * You should have received a copy of the GNU Lesser General Public License along with this ! * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, ! * Boston, MA 02111-1307, USA. ! */ ! ! package org.jrobin.data; ! ! import org.jrobin.core.FetchData; ! import org.jrobin.core.RrdException; ! import org.jrobin.core.Util; ! ! import java.io.IOException; ! ! class Def extends Source { ! private String path, dsName, consolFun, backend; ! private FetchData fetchData; ! ! Def(String name, FetchData fetchData) { ! this(name, null, name, null, null); ! setFetchData(fetchData); ! } ! ! Def(String name, String path, String dsName, String consolFunc) { ! this(name, path, dsName, consolFunc, null); ! } ! ! Def(String name, String path, String dsName, String consolFunc, String backend) { ! super(name); ! this.path = path; ! this.dsName = dsName; ! this.consolFun = consolFunc; ! this.backend = backend; ! } ! ! String getPath() { ! return path; ! } ! ! String getCanonicalPath() throws IOException { ! return Util.getCanonicalPath(path); ! } ! ! String getDsName() { ! return dsName; ! } ! ! String getConsolFun() { ! return consolFun; ! } ! ! String getBackend() { ! return backend; ! } ! ! boolean isCompatibleWith(Def def) throws IOException { ! return getCanonicalPath().equals(def.getCanonicalPath()) && ! getConsolFun().equals(def.consolFun) && ! ((backend == null && def.backend == null) || ! (backend != null && def.backend != null && backend.equals(def.backend))); ! } ! ! void setFetchData(FetchData fetchData) { ! this.fetchData = fetchData; ! } ! ! long[] getRrdTimestamps() { ! return fetchData.getTimestamps(); ! } ! ! double[] getRrdValues() throws RrdException { ! return fetchData.getValues(dsName); ! } ! ! long getArchiveEndTime() { ! return fetchData.getArcEndTime(); ! } ! ! long getFetchStep() { ! return fetchData.getStep(); ! } ! ! Aggregates getAggregates(long tStart, long tEnd) throws RrdException { ! long[] t = getRrdTimestamps(); ! double[] v = getRrdValues(); ! Aggregator agg = new Aggregator(t, v); ! return agg.getAggregates(tStart, tEnd); ! } ! ! double getPercentile(long tStart, long tEnd, double percentile) throws RrdException { ! long[] t = getRrdTimestamps(); ! double[] v = getRrdValues(); ! Aggregator agg = new Aggregator(t, v); ! return agg.getPercentile(tStart, tEnd, percentile); ! } ! ! boolean isLoaded() { ! return fetchData != null; ! } ! } Index: PDef.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/data/PDef.java,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** PDef.java 15 Dec 2004 14:55:41 -0000 1.2 --- PDef.java 21 Dec 2006 18:02:43 -0000 1.3 *************** *** 1,64 **** ! /* ============================================================ ! * JRobin : Pure java implementation of RRDTool's functionality ! * ============================================================ ! * ! * Project Info: http://www.jrobin.org ! * Project Lead: Sasa Markovic (sa...@jr...); ! * ! * (C) Copyright 2003, by Sasa Markovic. ! * ! * Developers: Sasa Markovic (sa...@jr...) ! * Arne Vandamme (cob...@jr...) ! * ! * This library is free software; you can redistribute it and/or modify it under the terms ! * of the GNU Lesser General Public License as published by the Free Software Foundation; ! * either version 2.1 of the License, or (at your option) any later version. ! * ! * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; ! * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. ! * See the GNU Lesser General Public License for more details. ! * ! * You should have received a copy of the GNU Lesser General Public License along with this ! * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, ! * Boston, MA 02111-1307, USA. ! */ ! ! package org.jrobin.data; ! ! import org.jrobin.graph.Plottable; ! ! class PDef extends Source { ! private final Plottable plottable; ! ! PDef(String name, Plottable plottable) { ! super(name); ! this.plottable = plottable; ! } ! ! PDef(String name, final Plottable plottable, final int index) { ! super(name); ! this.plottable = new Plottable() { ! public double getValue(long timestamp) { ! return plottable.getValue(timestamp, index); ! } ! }; ! } ! ! PDef(String name, final Plottable plottable, final String sourceName) { ! super(name); ! this.plottable = new Plottable() { ! public double getValue(long timestamp) { ! return plottable.getValue(timestamp, sourceName); ! } ! }; ! } ! ! void calculateValues() { ! long[] times = getTimestamps(); ! double[] vals = new double[times.length]; ! for(int i = 0; i < times.length; i++) { ! vals[i] = plottable.getValue(times[i]); ! } ! setValues(vals); ! } ! } --- 1,44 ---- ! /* ============================================================ ! * JRobin : Pure java implementation of RRDTool's functionality ! * ============================================================ ! * ! * Project Info: http://www.jrobin.org ! * Project Lead: Sasa Markovic (sa...@jr...); ! * ! * (C) Copyright 2003-2005, by Sasa Markovic. ! * ! * Developers: Sasa Markovic (sa...@jr...) ! * ! * ! * This library is free software; you can redistribute it and/or modify it under the terms ! * of the GNU Lesser General Public License as published by the Free Software Foundation; ! * either version 2.1 of the License, or (at your option) any later version. ! * ! * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; ! * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. ! * See the GNU Lesser General Public License for more details. ! * ! * You should have received a copy of the GNU Lesser General Public License along with this ! * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, ! * Boston, MA 02111-1307, USA. ! */ ! ! package org.jrobin.data; ! ! class PDef extends Source { ! private final Plottable plottable; ! ! PDef(String name, Plottable plottable) { ! super(name); ! this.plottable = plottable; ! } ! ! void calculateValues() { ! long[] times = getTimestamps(); ! double[] vals = new double[times.length]; ! for (int i = 0; i < times.length; i++) { ! vals[i] = plottable.getValue(times[i]); ! } ! setValues(vals); ! } ! } Index: LinearInterpolator.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/data/LinearInterpolator.java,v retrieving revision 1.1.1.1 retrieving revision 1.2 diff -C2 -d -r1.1.1.1 -r1.2 *** LinearInterpolator.java 6 Sep 2005 20:40:54 -0000 1.1.1.1 --- LinearInterpolator.java 21 Dec 2006 18:02:43 -0000 1.2 *************** *** 34,38 **** * Class used to interpolate datasource values from the collection of (timestamp, values) * points. This class is suitable for linear interpolation only. <p> ! * * Interpolation algorithm returns different values based on the value passed to * {@link #setInterpolationMethod(int) setInterpolationMethod()}. If not set, interpolation --- 34,38 ---- * Class used to interpolate datasource values from the collection of (timestamp, values) * points. This class is suitable for linear interpolation only. <p> ! * <p/> * Interpolation algorithm returns different values based on the value passed to * {@link #setInterpolationMethod(int) setInterpolationMethod()}. If not set, interpolation *************** *** 40,57 **** * Interpolation method handles NaN datasource * values gracefully.<p> - * */ public class LinearInterpolator extends Plottable { ! /** constant used to specify LEFT interpolation. ! * See {@link #setInterpolationMethod(int) setInterpolationMethod()} for explanation. */ public static final int INTERPOLATE_LEFT = 0; ! /** constant used to specify RIGHT interpolation. ! * See {@link #setInterpolationMethod(int) setInterpolationMethod()} for explanation. */ public static final int INTERPOLATE_RIGHT = 1; ! /** constant used to specify LINEAR interpolation (default interpolation method). ! * 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; --- 40,64 ---- * Interpolation method handles NaN datasource * values gracefully.<p> */ public class LinearInterpolator extends Plottable { ! /** ! * constant used to specify LEFT interpolation. ! * See {@link #setInterpolationMethod(int) setInterpolationMethod()} for explanation. ! */ public static final int INTERPOLATE_LEFT = 0; ! /** ! * constant used to specify RIGHT interpolation. ! * See {@link #setInterpolationMethod(int) setInterpolationMethod()} for explanation. ! */ public static final int INTERPOLATE_RIGHT = 1; ! /** ! * constant used to specify LINEAR interpolation (default interpolation method). ! * 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; *************** *** 67,74 **** /** * Creates LinearInterpolator from arrays of timestamps and corresponding datasource values. * @param timestamps timestamps in seconds ! * @param values corresponding datasource values * @throws RrdException Thrown if supplied arrays do not contain at least two values, or if ! * timestamps are not ordered, or array lengths are not equal. */ public LinearInterpolator(long[] timestamps, double[] values) throws RrdException { --- 74,82 ---- /** * Creates LinearInterpolator from arrays of timestamps and corresponding datasource values. + * * @param timestamps timestamps in seconds ! * @param values corresponding datasource values * @throws RrdException Thrown if supplied arrays do not contain at least two values, or if ! * timestamps are not ordered, or array lengths are not equal. */ public LinearInterpolator(long[] timestamps, double[] values) throws RrdException { *************** *** 80,92 **** /** * Creates LinearInterpolator from arrays of timestamps and corresponding datasource values. ! * @param dates Array of Date objects * @param values corresponding datasource values * @throws RrdException Thrown if supplied arrays do not contain at least two values, or if ! * timestamps are not ordered, or array lengths are not equal. */ public LinearInterpolator(Date[] dates, double[] values) throws RrdException { this.values = values; timestamps = new long[dates.length]; ! for(int i = 0; i < dates.length; i++) { timestamps[i] = Util.getTimestamp(dates[i]); } --- 88,101 ---- /** * Creates LinearInterpolator from arrays of timestamps and corresponding datasource values. ! * ! * @param dates Array of Date objects * @param values corresponding datasource values * @throws RrdException Thrown if supplied arrays do not contain at least two values, or if ! * timestamps are not ordered, or array lengths are not equal. */ public LinearInterpolator(Date[] dates, double[] values) throws RrdException { this.values = values; timestamps = new long[dates.length]; ! for (int i = 0; i < dates.length; i++) { timestamps[i] = Util.getTimestamp(dates[i]); } *************** *** 96,108 **** /** * Creates LinearInterpolator from arrays of timestamps and corresponding datasource values. ! * @param dates array of GregorianCalendar objects * @param values corresponding datasource values * @throws RrdException Thrown if supplied arrays do not contain at least two values, or if ! * timestamps are not ordered, or array lengths are not equal. */ public LinearInterpolator(Calendar[] dates, double[] values) throws RrdException { this.values = values; timestamps = new long[dates.length]; ! for(int i = 0; i < dates.length; i++) { timestamps[i] = Util.getTimestamp(dates[i]); } --- 105,118 ---- /** * Creates LinearInterpolator from arrays of timestamps and corresponding datasource values. ! * ! * @param dates array of GregorianCalendar objects * @param values corresponding datasource values * @throws RrdException Thrown if supplied arrays do not contain at least two values, or if ! * timestamps are not ordered, or array lengths are not equal. */ public LinearInterpolator(Calendar[] dates, double[] values) throws RrdException { this.values = values; timestamps = new long[dates.length]; ! for (int i = 0; i < dates.length; i++) { timestamps[i] = Util.getTimestamp(dates[i]); } *************** *** 112,124 **** private void validate() throws RrdException { boolean ok = true; ! if(timestamps.length != values.length || timestamps.length < 2) { ok = false; } ! for(int i = 0; i < timestamps.length - 1 && ok; i++) { ! if(timestamps[i] >= timestamps[i + 1]) { ok = false; } } ! if(!ok) { throw new RrdException("Invalid plottable data supplied"); } --- 122,134 ---- private void validate() throws RrdException { boolean ok = true; ! if (timestamps.length != values.length || timestamps.length < 2) { ok = false; } ! for (int i = 0; i < timestamps.length - 1 && ok; i++) { ! if (timestamps[i] >= timestamps[i + 1]) { ok = false; } } ! if (!ok) { throw new RrdException("Invalid plottable data supplied"); } *************** *** 135,154 **** * </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 re... [truncated message content] |
From: Tarus B. <ta...@us...> - 2006-12-21 18:00:49
|
Update of /cvsroot/jrobin/src/org/jrobin/graph In directory sc8-pr-cvs6.sourceforge.net:/tmp/cvs-serv8611 Removed Files: Cdef.java Pdef.java Sdef.java Log Message: More cleanup. --- Pdef.java DELETED --- --- Cdef.java DELETED --- --- Sdef.java DELETED --- |
From: Tarus B. <ta...@us...> - 2006-12-21 17:56:12
|
Update of /cvsroot/jrobin/src/org/jrobin/mrtg In directory sc8-pr-cvs6.sourceforge.net:/tmp/cvs-serv6614 Removed Files: Debug.java MrtgConstants.java MrtgException.java Log Message: Removing more dead files. --- MrtgConstants.java DELETED --- --- Debug.java DELETED --- --- MrtgException.java DELETED --- |
Update of /cvsroot/jrobin/src/org/jrobin/mrtg/client In directory sc8-pr-cvs6.sourceforge.net:/tmp/cvs-serv6448/client Removed Files: AboutDialog.java Client.java EditLinkDialog.java EditRouterDialog.java GraphFrame.java HelpDialog.java HostDialog.java LinkInfo.java MrtgData.java Resources.java RouterInfo.java RpcClient.java ServerInfo.java SplashWindow.java TreeElementInfo.java TreeRenderer.java Util.java Log Message: Removing dead files. --- HelpDialog.java DELETED --- --- ServerInfo.java DELETED --- --- EditLinkDialog.java DELETED --- --- TreeRenderer.java DELETED --- --- MrtgData.java DELETED --- --- HostDialog.java DELETED --- --- Resources.java DELETED --- --- TreeElementInfo.java DELETED --- --- GraphFrame.java DELETED --- --- SplashWindow.java DELETED --- --- Client.java DELETED --- --- Util.java DELETED --- --- RouterInfo.java DELETED --- --- LinkInfo.java DELETED --- --- AboutDialog.java DELETED --- --- EditRouterDialog.java DELETED --- --- RpcClient.java DELETED --- |
From: Tarus B. <ta...@us...> - 2006-12-21 17:55:15
|
Update of /cvsroot/jrobin/src/org/jrobin/mrtg/server In directory sc8-pr-cvs6.sourceforge.net:/tmp/cvs-serv6448/server Removed Files: Config.java Device.java DeviceList.java Listener.java Plotter.java Poller.java Port.java RawSample.java RrdWriter.java Server.java SnmpReader.java Timer.java Log Message: Removing dead files. --- Plotter.java DELETED --- --- Listener.java DELETED --- --- RrdWriter.java DELETED --- --- Poller.java DELETED --- --- RawSample.java DELETED --- --- Server.java DELETED --- --- Config.java DELETED --- --- Device.java DELETED --- --- Timer.java DELETED --- --- DeviceList.java DELETED --- --- SnmpReader.java DELETED --- --- Port.java DELETED --- |
From: Tarus B. <ta...@us...> - 2006-12-21 17:49:18
|
Update of /cvsroot/jrobin/src/org/jrobin/graph In directory sc8-pr-cvs6.sourceforge.net:/tmp/cvs-serv4063 Removed Files: CDef.java PDef.java SDef.java Log Message: Removing conflicts. --- PDef.java DELETED --- --- CDef.java DELETED --- --- SDef.java DELETED --- |
From: DJ G. <djg...@us...> - 2005-09-06 21:27:16
|
Update of /cvsroot/jrobin/src/org/jrobin/core/jrrd In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv15741/src/org/jrobin/core/jrrd Added Files: Tag: release-1-5-2 Archive.java CDPStatusBlock.java ConsolidationFunctionType.java Constants.java DataChunk.java DataSource.java DataSourceType.java Header.java PDPStatusBlock.java RRDException.java RRDFile.java RRDatabase.java Log Message: fix import conflicts, take two; anyone want to take bets on whether or not I'm done? --- NEW FILE: DataSourceType.java --- /* * Copyright (C) 2001 Ciaran Treanor <ci...@co...> * * Distributable under GPL license. * See terms of license at gnu.org. * * $Id: DataSourceType.java,v 1.1.4.2 2005/09/06 21:27:04 djgregor Exp $ */ package org.jrobin.core.jrrd; /** * Class DataSourceType * * @author <a href="mailto:ci...@co...">Ciaran Treanor</a> * @version $Revision: 1.1.4.2 $ */ public class DataSourceType { private static final int _COUNTER = 0; private static final String STR_COUNTER = "COUNTER"; /** * Field COUNTER */ public static final DataSourceType COUNTER = new DataSourceType(_COUNTER); private static final int _ABSOLUTE = 1; private static final String STR_ABSOLUTE = "ABSOLUTE"; /** * Field ABSOLUTE */ public static final DataSourceType ABSOLUTE = new DataSourceType(_ABSOLUTE); private static final int _GAUGE = 2; private static final String STR_GAUGE = "GAUGE"; /** * Field GAUGE */ public static final DataSourceType GAUGE = new DataSourceType(_GAUGE); private static final int _DERIVE = 3; private static final String STR_DERIVE = "DERIVE"; /** * Field DERIVE */ public static final DataSourceType DERIVE = new DataSourceType(_DERIVE); private int type; private DataSourceType(int type) { this.type = type; } /** * Returns a <code>DataSourceType</code> with the given name. * * @param s name of the <code>DataSourceType</code> required. * @return a <code>DataSourceType</code> with the given name. */ public static DataSourceType get(String s) { if (s.equalsIgnoreCase(STR_COUNTER)) { return COUNTER; } else if (s.equalsIgnoreCase(STR_ABSOLUTE)) { return ABSOLUTE; } else if (s.equalsIgnoreCase(STR_GAUGE)) { return GAUGE; } else if (s.equalsIgnoreCase(STR_DERIVE)) { return DERIVE; } else { throw new IllegalArgumentException("Invalid DataSourceType"); } } /** * Compares this object against the specified object. * * @return <code>true</code> if the objects are the same, * <code>false</code> otherwise. */ public boolean equals(Object obj) { if (!(obj instanceof DataSourceType)) { throw new IllegalArgumentException("Not a DataSourceType"); } return (((DataSourceType) obj).type == type) ? true : false; } /** * Returns a string representation of this object. * * @return a string representation of this object. */ public String toString() { String strType; switch (type) { case _COUNTER: strType = STR_COUNTER; break; case _ABSOLUTE: strType = STR_ABSOLUTE; break; case _GAUGE: strType = STR_GAUGE; break; case _DERIVE: strType = STR_DERIVE; break; default : // Don't you just hate it when you see a line like this? throw new RuntimeException("This should never happen"); } return strType; } } --- NEW FILE: ConsolidationFunctionType.java --- /* * Copyright (C) 2001 Ciaran Treanor <ci...@co...> * * Distributable under GPL license. * See terms of license at gnu.org. * * $Id: ConsolidationFunctionType.java,v 1.1.4.2 2005/09/06 21:27:04 djgregor Exp $ */ package org.jrobin.core.jrrd; /** * Class ConsolidationFunctionType * * @author <a href="mailto:ci...@co...">Ciaran Treanor</a> * @version $Revision: 1.1.4.2 $ */ public class ConsolidationFunctionType { private static final int _AVERAGE = 0; private static final String STR_AVERAGE = "AVERAGE"; /** * Field AVERAGE */ public static final ConsolidationFunctionType AVERAGE = new ConsolidationFunctionType(_AVERAGE); private static final int _MIN = 1; private static final String STR_MIN = "MIN"; /** * Field MIN */ public static final ConsolidationFunctionType MIN = new ConsolidationFunctionType(_MIN); private static final int _MAX = 2; private static final String STR_MAX = "MAX"; /** * Field MAX */ public static final ConsolidationFunctionType MAX = new ConsolidationFunctionType(_MAX); private static final int _LAST = 3; private static final String STR_LAST = "LAST"; /** * Field LAST */ public static final ConsolidationFunctionType LAST = new ConsolidationFunctionType(_LAST); private int type; private ConsolidationFunctionType(int type) { this.type = type; } /** * Returns a <code>ConsolidationFunctionType</code> with the given name. * * @param s name of the <code>ConsolidationFunctionType</code> required. * @return a <code>ConsolidationFunctionType</code> with the given name. */ public static ConsolidationFunctionType get(String s) { if (s.equalsIgnoreCase(STR_AVERAGE)) { return AVERAGE; } else if (s.equalsIgnoreCase(STR_MIN)) { return MIN; } else if (s.equalsIgnoreCase(STR_MAX)) { return MAX; } else if (s.equalsIgnoreCase(STR_LAST)) { return LAST; } else { throw new IllegalArgumentException("Invalid ConsolidationFunctionType"); } } /** * Compares this object against the specified object. * * @return <code>true</code> if the objects are the same, * <code>false</code> otherwise. */ public boolean equals(Object o) { if (!(o instanceof ConsolidationFunctionType)) { throw new IllegalArgumentException("Not a ConsolidationFunctionType"); } return (((ConsolidationFunctionType) o).type == type) ? true : false; } /** * Returns a string representation of this object. * * @return a string representation of this object. */ public String toString() { String strType; switch (type) { case _AVERAGE: strType = STR_AVERAGE; break; case _MIN: strType = STR_MIN; break; case _MAX: strType = STR_MAX; break; case _LAST: strType = STR_LAST; break; default : throw new RuntimeException("This should never happen"); } return strType; } } --- NEW FILE: RRDException.java --- /* * Copyright (C) 2001 Ciaran Treanor <ci...@co...> * * Distributable under GPL license. * See terms of license at gnu.org. * * $Id: RRDException.java,v 1.1.4.2 2005/09/06 21:27:04 djgregor Exp $ */ package org.jrobin.core.jrrd; /** * This exception may be throw if an error occurs while operating * on an RRD object. * * @author <a href="mailto:ci...@co...">Ciaran Treanor</a> * @version $Revision: 1.1.4.2 $ */ public class RRDException extends Exception { /** * Constructs an RRDException with no detail message. */ public RRDException() { super(); } /** * Constructs an RRDException with the specified detail message. */ public RRDException(String message) { super(message); } } --- NEW FILE: Header.java --- /* * Copyright (C) 2001 Ciaran Treanor <ci...@co...> * * Distributable under GPL license. * See terms of license at gnu.org. * * $Id: Header.java,v 1.1.4.2 2005/09/06 21:27:04 djgregor Exp $ */ package org.jrobin.core.jrrd; import java.io.IOException; /** * Instances of this class model the header section of an RRD file. * * @author <a href="mailto:ci...@co...">Ciaran Treanor</a> * @version $Revision: 1.1.4.2 $ */ public class Header implements Constants { static final long offset = 0; long size; String version; int dsCount; int rraCount; int pdpStep; Header(RRDFile file) throws IOException { if (!file.readString(4).equals(COOKIE)) { throw new IOException("Invalid COOKIE"); } if (!(version = file.readString(5)).equals(VERSION)) { throw new IOException("Unsupported RRD version (" + version + ")"); } file.align(); // Consume the FLOAT_COOKIE file.readDouble(); dsCount = file.readInt(); rraCount = file.readInt(); pdpStep = file.readInt(); // Skip rest of stat_head_t.par file.align(); file.skipBytes(80); size = file.getFilePointer() - offset; } /** * Returns the version of the database. * * @return the version of the database. */ public String getVersion() { return version; } /** * Returns the number of <code>DataSource</code>s in the database. * * @return the number of <code>DataSource</code>s in the database. */ public int getDSCount() { return dsCount; } /** * Returns the number of <code>Archive</code>s in the database. * * @return the number of <code>Archive</code>s in the database. */ public int getRRACount() { return rraCount; } /** * Returns the primary data point interval in seconds. * * @return the primary data point interval in seconds. */ public int getPDPStep() { return pdpStep; } /** * Returns a summary the contents of this header. * * @return a summary of the information contained in this header. */ public String toString() { StringBuffer sb = new StringBuffer("[Header: OFFSET=0x00, SIZE=0x"); sb.append(Long.toHexString(size)); sb.append(", version="); sb.append(version); sb.append(", dsCount="); sb.append(dsCount); sb.append(", rraCount="); sb.append(rraCount); sb.append(", pdpStep="); sb.append(pdpStep); sb.append("]"); return sb.toString(); } } --- NEW FILE: Archive.java --- /* * Copyright (C) 2001 Ciaran Treanor <ci...@co...> * * Distributable under GPL license. * See terms of license at gnu.org. * * $Id: Archive.java,v 1.2.2.2 2005/09/06 21:27:04 djgregor Exp $ */ package org.jrobin.core.jrrd; import java.io.IOException; import java.io.PrintStream; import java.text.DecimalFormat; import java.text.NumberFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.Iterator; /** * Instances of this class model an archive section of an RRD file. * * @author <a href="mailto:ci...@co...">Ciaran Treanor</a> * @version $Revision: 1.2.2.2 $ */ public class Archive { RRDatabase db; long offset; long dataOffset; long size; ConsolidationFunctionType type; int rowCount; int pdpCount; double xff; ArrayList<CDPStatusBlock> cdpStatusBlocks; int currentRow; private double[][] values; Archive(RRDatabase db) throws IOException { this.db = db; RRDFile file = db.rrdFile; offset = file.getFilePointer(); type = ConsolidationFunctionType.get(file.readString(Constants.CF_NAM_SIZE)); rowCount = file.readInt(); pdpCount = file.readInt(); file.align(); xff = file.readDouble(); // Skip rest of rra_def_t.par[] file.align(); file.skipBytes(72); size = file.getFilePointer() - offset; } /** * Returns the type of function used to calculate the consolidated data point. * * @return the type of function used to calculate the consolidated data point. */ public ConsolidationFunctionType getType() { return type; } void loadCDPStatusBlocks(RRDFile file, int numBlocks) throws IOException { cdpStatusBlocks = new ArrayList<CDPStatusBlock>(); for (int i = 0; i < numBlocks; i++) { cdpStatusBlocks.add(new CDPStatusBlock(file)); } } /** * Returns the <code>CDPStatusBlock</code> at the specified position in this archive. * * @param index index of <code>CDPStatusBlock</code> to return. * @return the <code>CDPStatusBlock</code> at the specified position in this archive. */ public CDPStatusBlock getCDPStatusBlock(int index) { return cdpStatusBlocks.get(index); } /** * Returns an iterator over the CDP status blocks in this archive in proper sequence. * * @return an iterator over the CDP status blocks in this archive in proper sequence. * @see CDPStatusBlock */ public Iterator<CDPStatusBlock> getCDPStatusBlocks() { return cdpStatusBlocks.iterator(); } void loadCurrentRow(RRDFile file) throws IOException { currentRow = file.readInt(); } void loadData(RRDFile file, int dsCount) throws IOException { dataOffset = file.getFilePointer(); // Skip over the data to position ourselves at the start of the next archive file.skipBytes(8 * rowCount * dsCount); } DataChunk loadData(DataChunk chunk) throws IOException { Calendar end = Calendar.getInstance(); Calendar start = (Calendar) end.clone(); start.add(Calendar.DATE, -1); loadData(chunk, start.getTime().getTime() / 1000, end.getTime().getTime() / 1000); return chunk; } void loadData(DataChunk chunk, long startTime, long endTime) throws IOException { long pointer; if (chunk.start < 0) { pointer = currentRow + 1; } else { pointer = currentRow + chunk.start + 1; } db.rrdFile.ras.seek(dataOffset + (pointer * 8)); //cat.debug("Archive Base: " + dataOffset + " Archive Pointer: " + pointer); //cat.debug("Start Offset: " + chunk.start + " End Offset: " // + (rowCount - chunk.end)); double[][] data = chunk.data; /* * This is also terrible - cleanup - CT */ int row = 0; for (int i = chunk.start; i < rowCount - chunk.end; i++, row++) { if (i < 0) { // no valid data yet for (int ii = 0; ii < chunk.dsCount; ii++) { data[row][ii] = Double.NaN; } } else if (i >= rowCount) { // past valid data area for (int ii = 0; ii < chunk.dsCount; ii++) { data[row][ii] = Double.NaN; } } else { // inside the valid are but the pointer has to be wrapped if (pointer >= rowCount) { pointer -= rowCount; db.rrdFile.ras.seek(dataOffset + (pointer * 8)); } for (int ii = 0; ii < chunk.dsCount; ii++) { data[row][ii] = db.rrdFile.readDouble(); } pointer++; } } } void printInfo(PrintStream s, NumberFormat numberFormat, int index) { StringBuffer sb = new StringBuffer("rra["); sb.append(index); s.print(sb); s.print("].cf = \""); s.print(type); s.println("\""); s.print(sb); s.print("].rows = "); s.println(rowCount); s.print(sb); s.print("].pdp_per_row = "); s.println(pdpCount); s.print(sb); s.print("].xff = "); s.println(xff); sb.append("].cdp_prep["); int cdpIndex = 0; for (Iterator<CDPStatusBlock> i = cdpStatusBlocks.iterator(); i.hasNext();) { CDPStatusBlock cdp = i.next(); s.print(sb); s.print(cdpIndex); s.print("].value = "); double value = cdp.value; s.println(Double.isNaN(value) ? "NaN" : numberFormat.format(value)); s.print(sb); s.print(cdpIndex++); s.print("].unknown_datapoints = "); s.println(cdp.unknownDatapoints); } } void toXml(PrintStream s) { try { s.println("\t<rra>"); s.print("\t\t<cf> "); s.print(type); s.println(" </cf>"); s.print("\t\t<pdp_per_row> "); s.print(pdpCount); s.print(" </pdp_per_row> <!-- "); s.print(db.header.pdpStep * pdpCount); s.println(" seconds -->"); s.print("\t\t<xff> "); s.print(xff); s.println(" </xff>"); s.println(); s.println("\t\t<cdp_prep>"); for (int i = 0; i < cdpStatusBlocks.size(); i++) { cdpStatusBlocks.get(i).toXml(s); } s.println("\t\t</cdp_prep>"); s.println("\t\t<database>"); long timer = -(rowCount - 1); int counter = 0; int row = currentRow; db.rrdFile.ras.seek(dataOffset + (row + 1) * 16); long lastUpdate = db.lastUpdate.getTime() / 1000; int pdpStep = db.header.pdpStep; NumberFormat numberFormat = new DecimalFormat("0.0000000000E0"); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z"); while (counter++ < rowCount) { row++; if (row == rowCount) { row = 0; db.rrdFile.ras.seek(dataOffset); } long now = (lastUpdate - lastUpdate % (pdpCount * pdpStep)) + (timer * pdpCount * pdpStep); timer++; s.print("\t\t\t<!-- "); s.print(dateFormat.format(new Date(now * 1000))); s.print(" / "); s.print(now); s.print(" --> "); for (int col = 0; col < db.header.dsCount; col++) { s.print("<v> "); double value = db.rrdFile.readDouble(); // NumberFormat doesn't know how to handle NaN if (Double.isNaN(value)) { s.print("NaN"); } else { s.print(numberFormat.format(value)); } s.print(" </v>"); } s.println("</row>"); } s.println("\t\t</database>"); s.println("\t</rra>"); } catch (IOException e) { // Is the best thing to do here? throw new RuntimeException(e.getMessage()); } } /* // THIS IS THE ORIGINAL CODE: BUGGY! Replaced by Sasa Markovic with a new method // Funny: the bug will appear only if dsCount != 2 :) public double[][] getValuesOriginal() throws IOException { if (values != null) { return values; } values = new double[db.header.dsCount][rowCount]; int row = currentRow; db.rrdFile.ras.seek(dataOffset + (row + 1) * 16); // <----- BUG (resolved below) for (int counter = 0; counter < rowCount; counter++) { row++; if (row == rowCount) { row = 0; db.rrdFile.ras.seek(dataOffset); } for (int col = 0; col < db.header.dsCount; col++) { double value = db.rrdFile.readDouble(); values[col][counter] = value; } } return values; } */ // Resolved bug from the original method (see above) public double[][] getValues() throws IOException { // OK PART if (values != null) { return values; } values = new double[db.header.dsCount][rowCount]; int row = currentRow; // HERE ARE THE DRAGONS! db.rrdFile.ras.seek(dataOffset + (row + 1) * db.header.dsCount * 8); // OK, TOO! for (int counter = 0; counter < rowCount; counter++) { row++; if (row == rowCount) { row = 0; db.rrdFile.ras.seek(dataOffset); } for (int col = 0; col < db.header.dsCount; col++) { double value = db.rrdFile.readDouble(); values[col][counter] = value; } } return values; } /** * Returns the number of primary data points required for a consolidated * data point in this archive. * * @return the number of primary data points required for a consolidated * data point in this archive. */ public int getPdpCount() { return pdpCount; } /** * Returns the number of entries in this archive. * * @return the number of entries in this archive. */ public int getRowCount() { return rowCount; } /** * Returns the X-Files Factor for this archive. * * @return the X-Files Factor for this archive. */ public double getXff() { return xff; } /** * Returns a summary the contents of this archive. * * @return a summary of the information contained in this archive. */ public String toString() { StringBuffer sb = new StringBuffer("[Archive: OFFSET=0x"); sb.append(Long.toHexString(offset)); sb.append(", SIZE=0x"); sb.append(Long.toHexString(size)); sb.append(", type="); sb.append(type); sb.append(", rowCount="); sb.append(rowCount); sb.append(", pdpCount="); sb.append(pdpCount); sb.append(", xff="); sb.append(xff); sb.append(", currentRow="); sb.append(currentRow); sb.append("]"); for (Iterator<CDPStatusBlock> i = cdpStatusBlocks.iterator(); i.hasNext();) { CDPStatusBlock cdp = i.next(); sb.append("\n\t\t"); sb.append(cdp.toString()); } return sb.toString(); } } --- NEW FILE: RRDFile.java --- /* * Copyright (C) 2001 Ciaran Treanor <ci...@co...> * * Distributable under GPL license. * See terms of license at gnu.org. * * $Id: RRDFile.java,v 1.1.4.2 2005/09/06 21:27:04 djgregor Exp $ */ package org.jrobin.core.jrrd; import java.io.*; /** * This class is a quick hack to read information from an RRD file. Writing * to RRD files is not currently supported. As I said, this is a quick hack. * Some thought should be put into the overall design of the file IO. * <p/> * Currently this can read RRD files that were generated on Solaris (Sparc) * and Linux (x86). * * @author <a href="mailto:ci...@co...">Ciaran Treanor</a> * @version $Revision: 1.1.4.2 $ */ public class RRDFile implements Constants { boolean bigEndian; int alignment; RandomAccessFile ras; byte[] buffer; RRDFile(String name) throws IOException { this(new File(name)); } RRDFile(File file) throws IOException { ras = new RandomAccessFile(file, "r"); buffer = new byte[128]; initDataLayout(file); } private void initDataLayout(File file) throws IOException { if (file.exists()) { // Load the data formats from the file ras.read(buffer, 0, 24); int index; if ((index = indexOf(FLOAT_COOKIE_BIG_ENDIAN, buffer)) != -1) { bigEndian = true; } else if ((index = indexOf(FLOAT_COOKIE_LITTLE_ENDIAN, buffer)) != -1) { bigEndian = false; } else { throw new IOException("Invalid RRD file"); } switch (index) { case 12: alignment = 4; break; case 16: alignment = 8; break; default : throw new RuntimeException("Unsupported architecture"); } } else { // Default to data formats for this hardware architecture } ras.seek(0); // Reset file pointer to start of file } private int indexOf(byte[] pattern, byte[] array) { return (new String(array)).indexOf(new String(pattern)); } boolean isBigEndian() { return bigEndian; } int getAlignment() { return alignment; } double readDouble() throws IOException { //double value; byte[] tx = new byte[8]; ras.read(buffer, 0, 8); if (bigEndian) { tx = buffer; } else { for (int i = 0; i < 8; i++) { tx[7 - i] = buffer[i]; } } DataInputStream reverseDis = new DataInputStream(new ByteArrayInputStream(tx)); return reverseDis.readDouble(); } int readInt() throws IOException { return readInt(false); } int readInt(boolean dump) throws IOException { ras.read(buffer, 0, 4); int value; if (bigEndian) { value = (0xFF & buffer[3]) | ((0xFF & buffer[2]) << 8) | ((0xFF & buffer[1]) << 16) | ((0xFF & buffer[0]) << 24); } else { value = (0xFF & buffer[0]) | ((0xFF & buffer[1]) << 8) | ((0xFF & buffer[2]) << 16) | ((0xFF & buffer[3]) << 24); } return value; } String readString(int maxLength) throws IOException { ras.read(buffer, 0, maxLength); return new String(buffer, 0, maxLength).trim(); } void skipBytes(int n) throws IOException { ras.skipBytes(n); } int align(int boundary) throws IOException { int skip = (int) (boundary - (ras.getFilePointer() % boundary)) % boundary; if (skip != 0) { ras.skipBytes(skip); } return skip; } int align() throws IOException { return align(alignment); } long info() throws IOException { return ras.getFilePointer(); } long getFilePointer() throws IOException { return ras.getFilePointer(); } void close() throws IOException { ras.close(); } } --- NEW FILE: Constants.java --- /* * Copyright (C) 2001 Ciaran Treanor <ci...@co...> * * Distributable under GPL license. * See terms of license at gnu.org. * * $Id: Constants.java,v 1.1.4.2 2005/09/06 21:27:04 djgregor Exp $ */ package org.jrobin.core.jrrd; interface Constants { int DS_NAM_SIZE = 20; int DST_SIZE = 20; int CF_NAM_SIZE = 20; int LAST_DS_LEN = 30; static String COOKIE = "RRD"; static String VERSION = "0001"; double FLOAT_COOKIE = 8.642135E130; static byte[] FLOAT_COOKIE_BIG_ENDIAN = {0x5B, 0x1F, 0x2B, 0x43, (byte) 0xC7, (byte) 0xC0, 0x25, 0x2F}; static byte[] FLOAT_COOKIE_LITTLE_ENDIAN = {0x2F, 0x25, (byte) 0xC0, (byte) 0xC7, 0x43, 0x2B, 0x1F, 0x5B}; } --- NEW FILE: CDPStatusBlock.java --- /* * Copyright (C) 2001 Ciaran Treanor <ci...@co...> * * Distributable under GPL license. * See terms of license at gnu.org. * * $Id: CDPStatusBlock.java,v 1.1.4.2 2005/09/06 21:27:04 djgregor Exp $ */ package org.jrobin.core.jrrd; import java.io.IOException; import java.io.PrintStream; /** * Instances of this class model the consolidation data point status from an RRD file. * * @author <a href="mailto:ci...@co...">Ciaran Treanor</a> * @version $Revision: 1.1.4.2 $ */ public class CDPStatusBlock { long offset; long size; int unknownDatapoints; double value; CDPStatusBlock(RRDFile file) throws IOException { offset = file.getFilePointer(); value = file.readDouble(); unknownDatapoints = file.readInt(); // Skip rest of cdp_prep_t.scratch file.skipBytes(68); size = file.getFilePointer() - offset; } /** * Returns the number of unknown primary data points that were integrated. * * @return the number of unknown primary data points that were integrated. */ public int getUnknownDatapoints() { return unknownDatapoints; } /** * Returns the value of this consolidated data point. * * @return the value of this consolidated data point. */ public double getValue() { return value; } void toXml(PrintStream s) { s.print("\t\t\t<ds><value> "); s.print(value); s.print(" </value> <unknown_datapoints> "); s.print(unknownDatapoints); s.println(" </unknown_datapoints></ds>"); } /** * Returns a summary the contents of this CDP status block. * * @return a summary of the information contained in the CDP status block. */ public String toString() { StringBuffer sb = new StringBuffer("[CDPStatusBlock: OFFSET=0x"); sb.append(Long.toHexString(offset)); sb.append(", SIZE=0x"); sb.append(Long.toHexString(size)); sb.append(", unknownDatapoints="); sb.append(unknownDatapoints); sb.append(", value="); sb.append(value); sb.append("]"); return sb.toString(); } } --- NEW FILE: RRDatabase.java --- /* * Copyright (C) 2001 Ciaran Treanor <ci...@co...> * * Distributable under GPL license. * See terms of license at gnu.org. * * $Id: RRDatabase.java,v 1.2.4.2 2005/09/06 21:27:04 djgregor Exp $ */ package org.jrobin.core.jrrd; import java.io.File; import java.io.IOException; import java.io.PrintStream; import java.text.DecimalFormat; import java.text.NumberFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.Iterator; /** * Instances of this class model * <a href="http://people.ee.ethz.ch/~oetiker/webtools/rrdtool/">Round Robin Database</a> * (RRD) files. * * @author <a href="mailto:ci...@co...">Ciaran Treanor</a> * @version $Revision: 1.2.4.2 $ */ public class RRDatabase { RRDFile rrdFile; // RRD file name private String name; Header header; ArrayList<DataSource> dataSources; ArrayList<Archive> archives; Date lastUpdate; /** * Creates a database to read from. * * @param name the filename of the file to read from. * @throws IOException if an I/O error occurs. */ public RRDatabase(String name) throws IOException { this(new File(name)); } /** * Creates a database to read from. * * @param file the file to read from. * @throws IOException if an I/O error occurs. */ public RRDatabase(File file) throws IOException { name = file.getName(); rrdFile = new RRDFile(file); header = new Header(rrdFile); // Load the data sources dataSources = new ArrayList<DataSource>(); for (int i = 0; i < header.dsCount; i++) { DataSource ds = new DataSource(rrdFile); dataSources.add(ds); } // Load the archives archives = new ArrayList<Archive>(); for (int i = 0; i < header.rraCount; i++) { Archive archive = new Archive(this); archives.add(archive); } rrdFile.align(); lastUpdate = new Date((long) (rrdFile.readInt()) * 1000); // Load PDPStatus(s) for (int i = 0; i < header.dsCount; i++) { DataSource ds = dataSources.get(i); ds.loadPDPStatusBlock(rrdFile); } // Load CDPStatus(s) for (int i = 0; i < header.rraCount; i++) { Archive archive = archives.get(i); archive.loadCDPStatusBlocks(rrdFile, header.dsCount); } // Load current row information for each archive for (int i = 0; i < header.rraCount; i++) { Archive archive = archives.get(i); archive.loadCurrentRow(rrdFile); } // Now load the data for (int i = 0; i < header.rraCount; i++) { Archive archive = archives.get(i); archive.loadData(rrdFile, header.dsCount); } } /** * Returns the <code>Header</code> for this database. * * @return the <code>Header</code> for this database. */ public Header getHeader() { return header; } /** * Returns the date this database was last updated. To convert this date to * the form returned by <code>rrdtool last</code> call Date.getTime() and * divide the result by 1000. * * @return the date this database was last updated. */ public Date getLastUpdate() { return lastUpdate; } /** * Returns the <code>DataSource</code> at the specified position in this database. * * @param index index of <code>DataSource</code> to return. * @return the <code>DataSource</code> at the specified position in this database */ public DataSource getDataSource(int index) { return dataSources.get(index); } /** * Returns an iterator over the data sources in this database in proper sequence. * * @return an iterator over the data sources in this database in proper sequence. */ public Iterator<DataSource> getDataSources() { return dataSources.iterator(); } /** * Returns the <code>Archive</code> at the specified position in this database. * * @param index index of <code>Archive</code> to return. * @return the <code>Archive</code> at the specified position in this database. */ public Archive getArchive(int index) { return archives.get(index); } /** * Returns an iterator over the archives in this database in proper sequence. * * @return an iterator over the archives in this database in proper sequence. */ public Iterator<Archive> getArchives() { return archives.iterator(); } /** * Returns the number of archives in this database. * * @return the number of archives in this database. */ public int getNumArchives() { return header.rraCount; } /** * Returns an iterator over the archives in this database of the given type * in proper sequence. * * @param type the consolidation function that should have been applied to * the data. * @return an iterator over the archives in this database of the given type * in proper sequence. */ public Iterator<Archive> getArchives(ConsolidationFunctionType type) { return getArchiveList(type).iterator(); } ArrayList<Archive> getArchiveList(ConsolidationFunctionType type) { ArrayList<Archive> subset = new ArrayList<Archive>(); for (int i = 0; i < archives.size(); i++) { Archive archive = archives.get(i); if (archive.getType().equals(type)) { subset.add(archive); } } return subset; } /** * Closes this database stream and releases any associated system resources. * * @throws IOException if an I/O error occurs. */ public void close() throws IOException { rrdFile.close(); } /** * Outputs the header information of the database to the given print stream * using the default number format. The default format for <code>double</code> * is 0.0000000000E0. * * @param s the PrintStream to print the header information to. */ public void printInfo(PrintStream s) { NumberFormat numberFormat = new DecimalFormat("0.0000000000E0"); printInfo(s, numberFormat); } /** * Returns data from the database corresponding to the given consolidation * function and a step size of 1. * * @param type the consolidation function that should have been applied to * the data. * @return the raw data. * @throws RRDException if there was a problem locating a data archive with * the requested consolidation function. * @throws IOException if there was a problem reading data from the database. */ public DataChunk getData(ConsolidationFunctionType type) throws RRDException, IOException { return getData(type, 1L); } /** * Returns data from the database corresponding to the given consolidation * function. * * @param type the consolidation function that should have been applied to * the data. * @param step the step size to use. * @return the raw data. * @throws RRDException if there was a problem locating a data archive with * the requested consolidation function. * @throws IOException if there was a problem reading data from the database. */ public DataChunk getData(ConsolidationFunctionType type, long step) throws RRDException, IOException { ArrayList<Archive> possibleArchives = getArchiveList(type); if (possibleArchives.size() == 0) { throw new RRDException("Database does not contain an Archive of consolidation function type " + type); } Calendar endCal = Calendar.getInstance(); endCal.set(Calendar.MILLISECOND, 0); Calendar startCal = (Calendar) endCal.clone(); startCal.add(Calendar.DATE, -1); long end = endCal.getTime().getTime() / 1000; long start = startCal.getTime().getTime() / 1000; Archive archive = findBestArchive(start, end, step, possibleArchives); // Tune the parameters step = header.pdpStep * archive.pdpCount; start -= start % step; if (end % step != 0) { end += step - end % step; } int rows = (int) ((end - start) / step + 1); //cat.debug("start " + start + " end " + end + " step " + step + " rows " // + rows); // Find start and end offsets // This is terrible - some of this should be encapsulated in Archive - CT. long lastUpdateLong = lastUpdate.getTime() / 1000; long archiveEndTime = lastUpdateLong - (lastUpdateLong % step); long archiveStartTime = archiveEndTime - (step * (archive.rowCount - 1)); int startOffset = (int) ((start - archiveStartTime) / step); int endOffset = (int) ((archiveEndTime - end) / step); //cat.debug("start " + archiveStartTime + " end " + archiveEndTime // + " startOffset " + startOffset + " endOffset " // + (archive.rowCount - endOffset)); DataChunk chunk = new DataChunk(start, startOffset, endOffset, step, header.dsCount, rows); archive.loadData(chunk); return chunk; } /* * This is almost a verbatim copy of the original C code by Tobias Oetiker. * I need to put more of a Java style on it - CT */ private Archive findBestArchive(long start, long end, long step, ArrayList<Archive> archives) { Archive archive = null; Archive bestFullArchive = null; Archive bestPartialArchive = null; long lastUpdateLong = lastUpdate.getTime() / 1000; int firstPart = 1; int firstFull = 1; long bestMatch = 0; //long bestPartRRA = 0; long bestStepDiff = 0; long tmpStepDiff = 0; for (int i = 0; i < archives.size(); i++) { archive = archives.get(i); long calEnd = lastUpdateLong - (lastUpdateLong % (archive.pdpCount * header.pdpStep)); long calStart = calEnd - (archive.pdpCount * archive.rowCount * header.pdpStep); long fullMatch = end - start; if ((calEnd >= end) && (calStart < start)) { // Best full match tmpStepDiff = Math.abs(step - (header.pdpStep * archive.pdpCount)); if ((firstFull != 0) || (tmpStepDiff < bestStepDiff)) { firstFull = 0; bestStepDiff = tmpStepDiff; bestFullArchive = archive; } } else { // Best partial match long tmpMatch = fullMatch; if (calStart > start) { tmpMatch -= calStart - start; } if (calEnd < end) { tmpMatch -= end - calEnd; } if ((firstPart != 0) || (bestMatch < tmpMatch)) { firstPart = 0; bestMatch = tmpMatch; bestPartialArchive = archive; } } } // See how the matching went // optimise this if (firstFull == 0) { archive = bestFullArchive; } else if (firstPart == 0) { archive = bestPartialArchive; } return archive; } /** * Outputs the header information of the database to the given print stream * using the given number format. The format is almost identical to that * produced by * <a href="http://people.ee.ethz.ch/~oetiker/webtools/rrdtool/manual/rrdinfo.html">rrdtool info</a> * * @param s the PrintStream to print the header information to. * @param numberFormat the format to print <code>double</code>s as. */ public void printInfo(PrintStream s, NumberFormat numberFormat) { s.print("filename = \""); s.print(name); s.println("\""); s.print("rrd_version = \""); s.print(header.version); s.println("\""); s.print("step = "); s.println(header.pdpStep); s.print("last_update = "); s.println(lastUpdate.getTime() / 1000); for (Iterator<DataSource> i = dataSources.iterator(); i.hasNext();) { DataSource ds = i.next(); ds.printInfo(s, numberFormat); } int index = 0; for (Iterator<Archive> i = archives.iterator(); i.hasNext();) { Archive archive = i.next(); archive.printInfo(s, numberFormat, index++); } } /** * Outputs the content of the database to the given print stream * as a stream of XML. The XML format is almost identical to that produced by * <a href="http://people.ee.ethz.ch/~oetiker/webtools/rrdtool/manual/rrddump.html">rrdtool dump</a> * * @param s the PrintStream to send the XML to. */ public void toXml(PrintStream s) { s.println("<!--"); s.println(" -- Round Robin RRDatabase Dump "); s.println(" -- Generated by jRRD <ci...@co...>"); s.println(" -->"); s.println("<rrd>"); s.print("\t<version> "); s.print(header.version); s.println(" </version>"); s.print("\t<step> "); s.print(header.pdpStep); s.println(" </step> <!-- Seconds -->"); s.print("\t<lastupdate> "); s.print(lastUpdate.getTime() / 1000); s.print(" </lastupdate> <!-- "); s.print(lastUpdate.toString()); s.println(" -->"); s.println(); for (int i = 0; i < header.dsCount; i++) { DataSource ds = dataSources.get(i); ds.toXml(s); } s.println("<!-- Round Robin Archives -->"); for (int i = 0; i < header.rraCount; i++) { Archive archive = archives.get(i); archive.toXml(s); } s.println("</rrd>"); } /** * Returns a summary the contents of this database. * * @return a summary of the information contained in this database. */ public String toString() { StringBuffer sb = new StringBuffer("\n"); sb.append(header.toString()); for (Iterator<DataSource> i = dataSources.iterator(); i.hasNext();) { DataSource ds = i.next(); sb.append("\n\t"); sb.append(ds.toString()); } for (Iterator<Archive> i = archives.iterator(); i.hasNext();) { Archive archive = i.next(); sb.append("\n\t"); sb.append(archive.toString()); } return sb.toString(); } } --- NEW FILE: DataSource.java --- /* * Copyright (C) 2001 Ciaran Treanor <ci...@co...> * * Distributable under GPL license. * See terms of license at gnu.org. * * $Id: DataSource.java,v 1.1.4.2 2005/09/06 21:27:04 djgregor Exp $ */ package org.jrobin.core.jrrd; import java.io.IOException; import java.io.PrintStream; import java.text.NumberFormat; /** * Instances of this class model a data source in an RRD file. * * @author <a href="mailto:ci...@co...">Ciaran Treanor</a> * @version $Revision: 1.1.4.2 $ */ public class DataSource { long offset; long size; String name; DataSourceType type; int minimumHeartbeat; double minimum; double maximum; PDPStatusBlock pdpStatusBlock; DataSource(RRDFile file) throws IOException { offset = file.getFilePointer(); name = file.readString(Constants.DS_NAM_SIZE); type = DataSourceType.get(file.readString(Constants.DST_SIZE)); file.align(8); minimumHeartbeat = file.readInt(true); file.align(8); minimum = file.readDouble(); maximum = file.readDouble(); // Skip rest of ds_def_t.par[] file.align(); file.skipBytes(56); size = file.getFilePointer() - offset; } void loadPDPStatusBlock(RRDFile file) throws IOException { pdpStatusBlock = new PDPStatusBlock(file); } /** * Returns the primary data point status block for this data source. * * @return the primary data point status block for this data source. */ public PDPStatusBlock getPDPStatusBlock() { return pdpStatusBlock; } /** * Returns the minimum required heartbeat for this data source. * * @return the minimum required heartbeat for this data source. */ public int getMinimumHeartbeat() { return minimumHeartbeat; } /** * Returns the minimum value input to this data source can have. * * @return the minimum value input to this data source can have. */ public double getMinimum() { return minimum; } /** * Returns the type this data source is. * * @return the type this data source is. * @see DataSourceType */ public DataSourceType getType() { return type; } /** * Returns the maximum value input to this data source can have. * * @return the maximum value input to this data source can have. */ public double getMaximum() { return maximum; } /** * Returns the name of this data source. * * @return the name of this data source. */ public String getName() { return name; } void printInfo(PrintStream s, NumberFormat numberFormat) { StringBuffer sb = new StringBuffer("ds["); sb.append(name); s.print(sb); s.print("].type = \""); s.print(type); s.println("\""); s.print(sb); s.print("].minimal_heartbeat = "); s.println(minimumHeartbeat); s.print(sb); s.print("].min = "); s.println(Double.isNaN(minimum) ? "NaN" : numberFormat.format(minimum)); s.print(sb); s.print("].max = "); s.println(Double.isNaN(maximum) ? "NaN" : numberFormat.format(maximum)); s.print(sb); s.print("].last_ds = "); s.println(pdpStatusBlock.lastReading); s.print(sb); s.print("].value = "); double value = pdpStatusBlock.value; s.println(Double.isNaN(value) ? "NaN" : numberFormat.format(value)); s.print(sb); s.print("].unknown_sec = "); s.println(pdpStatusBlock.unknownSeconds); } void toXml(PrintStream s) { s.println("\t<ds>"); s.print("\t\t<name> "); s.print(name); s.println(" </name>"); s.print("\t\t<type> "); s.print(type); s.println(" </type>"); s.print("\t\t<minimal_heartbeat> "); s.print(minimumHeartbeat); s.println(" </minimal_heartbeat>"); s.print("\t\t<min> "); s.print(minimum); s.println(" </min>"); s.print("\t\t<max> "); s.print(maximum); s.println(" </max>"); s.println(); s.println("\t\t<!-- PDP Status -->"); s.print("\t\t<last_ds> "); s.print(pdpStatusBlock.lastReading); s.println(" </last_ds>"); s.print("\t\t<value> "); s.print(pdpStatusBlock.value); s.println(" </value>"); s.print("\t\t<unknown_sec> "); s.print(pdpStatusBlock.unknownSeconds); s.println(" </unknown_sec>"); s.println("\t</ds>"); s.println(); } /** * Returns a summary the contents of this data source. * * @return a summary of the information contained in this data source. */ public String toString() { StringBuffer sb = new StringBuffer("[DataSource: OFFSET=0x"); sb.append(Long.toHexString(offset)); sb.append(", SIZE=0x"); sb.append(Long.toHexString(size)); sb.append(", name="); sb.append(name); sb.append(", type="); sb.append(type.toString()); sb.append(", minHeartbeat="); sb.append(minimumHeartbeat); sb.append(", min="); sb.append(minimum); sb.append(", max="); sb.append(maximum); sb.append("]"); sb.append("\n\t\t"); sb.append(pdpStatusBlock.toString()); return sb.toString(); } } --- NEW FILE: PDPStatusBlock.java --- /* * Copyright (C) 2001 Ciaran Treanor <ci...@co...> * * Distributable under GPL license. * See terms of license at gnu.org. * * $Id: PDPStatusBlock.java,v 1.1.4.2 2005/09/06 21:27:04 djgregor Exp $ */ package org.jrobin.core.jrrd; import java.io.IOException; /** * Instances of this class model the primary data point status from an RRD file. * * @author <a href="mailto:ci...@co...">Ciaran Treanor</a> * @version $Revision: 1.1.4.2 $ */ public class PDPStatusBlock { long offset; long size; String lastReading; int unknownSeconds; double value; PDPStatusBlock(RRDFile file) throws IOException { offset = file.getFilePointer(); lastReading = file.readString(Constants.LAST_DS_LEN); file.align(4); unknownSeconds = file.readInt(); file.skipBytes(4); value = file.readDouble(); // Skip rest of pdp_prep_t.par[] file.skipBytes(64); size = file.getFilePointer() - offset; } /** * Returns the last reading from the data source. * * @return the last reading from the data source. */ public String getLastReading() { return lastReading; } /** * Returns the current value of the primary data point. * * @return the current value of the primary data point. */ public double getValue() { return value; } /** * Returns the number of seconds of the current primary data point is * unknown data. * * @return the number of seconds of the current primary data point is unknown data. */ public int getUnknownSeconds() { return unknownSeconds; } /** * Returns a summary the contents of this PDP status block. * * @return a summary of the information contained in this PDP status block. */ public String toString() { StringBuffer sb = new StringBuffer("[PDPStatus: OFFSET=0x"); sb.append(Long.toHexString(offset)); sb.append(", SIZE=0x"); sb.append(Long.toHexString(size)); sb.append(", lastReading="); sb.append(lastReading); sb.append(", unknownSeconds="); sb.append(unknownSeconds); sb.append(", value="); sb.append(value); sb.append("]"); return sb.toString(); } } --- NEW FILE: DataChunk.java --- /* * Copyright (C) 2001 Ciaran Treanor <ci...@co...> * * Distributable under GPL license. * See terms of license at gnu.org. * * $Id: DataChunk.java,v 1.2.2.2 2005/09/06 21:27:04 djgregor Exp $ */ package org.jrobin.core.jrrd; /** * Models a chunk of result data from an RRDatabase. * * @author <a href="mailto:ci...@co...">Ciaran Treanor</a> * @version $Revision: 1.2.2.2 $ */ public class DataChunk { private static final String NEWLINE = System.getProperty("line.separator"); long startTime; int start; int end; long step; int dsCount; double[][] data; int rows; DataChunk(long startTime, int start, int end, long step, int dsCount, int rows) { this.startTime = startTime; this.start = start; this.end = end; this.step = step; this.dsCount = dsCount; this.rows = rows; data = new double[rows][dsCount]; } /** * Returns a summary of the contents of this data chunk. The first column is * the time (RRD format) and the following columns are the data source * values. * * @return a summary of the contents of this data chunk. */ public String toString() { StringBuffer sb = new StringBuffer(); long time = startTime; for (int row = 0; row < rows; row++, time += step) { sb.append(time); sb.append(": "); for (int ds = 0; ds < dsCount; ds++) { sb.append(data[row][ds]); sb.append(" "); } sb.append(NEWLINE); } return sb.toString(); } } |