You can subscribe to this list here.
2003 |
Jan
|
Feb
|
Mar
|
Apr
|
May
|
Jun
|
Jul
|
Aug
|
Sep
(11) |
Oct
(60) |
Nov
(68) |
Dec
(10) |
---|---|---|---|---|---|---|---|---|---|---|---|---|
2004 |
Jan
(10) |
Feb
(15) |
Mar
(30) |
Apr
(20) |
May
(32) |
Jun
(30) |
Jul
(61) |
Aug
(13) |
Sep
(14) |
Oct
(13) |
Nov
(28) |
Dec
(10) |
2005 |
Jan
(7) |
Feb
(5) |
Mar
|
Apr
(2) |
May
|
Jun
|
Jul
|
Aug
|
Sep
(4) |
Oct
|
Nov
|
Dec
|
2006 |
Jan
|
Feb
|
Mar
|
Apr
|
May
|
Jun
|
Jul
|
Aug
|
Sep
|
Oct
|
Nov
|
Dec
(15) |
2007 |
Jan
|
Feb
|
Mar
|
Apr
|
May
|
Jun
|
Jul
(20) |
Aug
(35) |
Sep
(3) |
Oct
(2) |
Nov
|
Dec
|
2008 |
Jan
|
Feb
|
Mar
|
Apr
|
May
|
Jun
|
Jul
|
Aug
(14) |
Sep
(2) |
Oct
|
Nov
|
Dec
|
2010 |
Jan
|
Feb
|
Mar
|
Apr
|
May
|
Jun
|
Jul
|
Aug
|
Sep
|
Oct
|
Nov
|
Dec
(3) |
2011 |
Jan
|
Feb
|
Mar
|
Apr
(5) |
May
|
Jun
|
Jul
|
Aug
|
Sep
|
Oct
|
Nov
|
Dec
|
From: Sasa M. <sa...@us...> - 2004-07-14 12:52:42
|
Update of /cvsroot/jrobin/src/org/jrobin/demo/graph In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv22919/org/jrobin/demo/graph Modified Files: ExportExportDemo.java ExportImportDemo.java LazyDemo.java Log Message: Minor interventions to graph demo applications - path to res/demo directory is now determined during runtime. See Util.getJrobinHomeDirectory for explanation. Index: ExportExportDemo.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/demo/graph/ExportExportDemo.java,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** ExportExportDemo.java 13 Jul 2004 12:16:08 -0000 1.1 --- ExportExportDemo.java 14 Jul 2004 12:52:34 -0000 1.2 *************** *** 53,56 **** --- 53,57 ---- private static void prepare( String[] args ) { + /* if ( args.length != 1 ) { *************** *** 64,67 **** --- 65,70 ---- demoResources = new File(args[0]).getAbsolutePath() + "/"; + */ + demoResources = Util.getJRobinHomeDirectory() + "/res/demo/"; } Index: ExportImportDemo.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/demo/graph/ExportImportDemo.java,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** ExportImportDemo.java 13 Jul 2004 12:16:08 -0000 1.1 --- ExportImportDemo.java 14 Jul 2004 12:52:34 -0000 1.2 *************** *** 52,55 **** --- 52,56 ---- private static void prepare( String[] args ) { + /* if ( args.length != 1 ) { *************** *** 63,66 **** --- 64,69 ---- demoResources = new File(args[0]).getAbsolutePath() + "/"; + */ + demoResources = Util.getJRobinHomeDirectory() + "/res/demo/"; } Index: LazyDemo.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/demo/graph/LazyDemo.java,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** LazyDemo.java 13 Jul 2004 16:19:07 -0000 1.1 --- LazyDemo.java 14 Jul 2004 12:52:34 -0000 1.2 *************** *** 83,86 **** --- 83,87 ---- private static void prepare( String[] args ) { + /* if ( args.length != 1 ) { *************** *** 94,97 **** --- 95,100 ---- demoResources = new File(args[0]).getAbsolutePath() + "/"; + */ + demoResources = Util.getJRobinHomeDirectory() + "/res/demo/"; rrd1 = demoResources + rrd1; rrd2 = demoResources + rrd2; |
From: Sasa M. <sa...@us...> - 2004-07-14 12:52:42
|
Update of /cvsroot/jrobin/src/org/jrobin/core In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv22919/org/jrobin/core Modified Files: RrdDb.java Util.java Log Message: Minor interventions to graph demo applications - path to res/demo directory is now determined during runtime. See Util.getJrobinHomeDirectory for explanation. Index: Util.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/core/Util.java,v retrieving revision 1.18 retrieving revision 1.19 diff -C2 -d -r1.18 -r1.19 *** Util.java 12 Jul 2004 13:35:16 -0000 1.18 --- Util.java 14 Jul 2004 12:52:34 -0000 1.19 *************** *** 496,499 **** return "[" + seconds + " sec]"; } ! } \ No newline at end of file --- 496,536 ---- return "[" + seconds + " sec]"; } ! ! /** ! * Returns the root directory of the JRobin distribution. Useful in some demo applications, ! * probably of no use anywhere else.<p> ! * ! * The function assumes that all JRobin .class files are placed under ! * the <root>/classes subdirectory and that all jars (libraries) are placed in the ! * <root>/lib subdirectory (the original JRobin directory structure).<p> ! * ! * @return absolute path to JRobin's home directory ! */ ! public static String getJRobinHomeDirectory() { ! String className = Util.class.getName().replace('.', '/'); ! String uri = Util.class.getResource("/" + className + ".class").toString(); ! if(uri.startsWith("file:/")) { ! uri = uri.substring(6); ! File file = new File(uri); ! // let's go 5 steps backwards ! for(int i = 0; i < 5; i++) { ! file = file.getParentFile(); ! } ! uri = file.getAbsolutePath(); ! } ! else if(uri.startsWith("jar:file:/")) { ! uri = uri.substring(10, uri.lastIndexOf('!')); ! File file = new File(uri); ! // let's go 2 steps backwards ! for(int i = 0; i < 2; i++) { ! file = file.getParentFile(); ! } ! uri = file.getAbsolutePath(); ! } ! else { ! uri = null; ! } ! return uri; ! } ! } \ No newline at end of file Index: RrdDb.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/core/RrdDb.java,v retrieving revision 1.23 retrieving revision 1.24 diff -C2 -d -r1.23 -r1.24 *** RrdDb.java 9 Jul 2004 12:20:10 -0000 1.23 --- RrdDb.java 14 Jul 2004 12:52:34 -0000 1.24 *************** *** 988,991 **** --- 988,992 ---- public static void main(String[] args) { + System.out.println("JRobin base directory: " + Util.getJRobinHomeDirectory()); System.out.println("JRobin Java Library :: RRDTool choice for the Java world"); System.out.println("http://www.jrobin.org"); |
From: Sasa M. <sa...@us...> - 2004-07-14 09:00:04
|
Update of /cvsroot/jrobin/src/org/jrobin/core In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv17677/org/jrobin/core Modified Files: RrdNioBackend.java Log Message: minor tweaks Index: RrdNioBackend.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/core/RrdNioBackend.java,v retrieving revision 1.10 retrieving revision 1.11 diff -C2 -d -r1.10 -r1.11 *** RrdNioBackend.java 13 Jul 2004 11:45:39 -0000 1.10 --- RrdNioBackend.java 14 Jul 2004 08:59:55 -0000 1.11 *************** *** 84,88 **** protected void setLength(long length) throws IOException { super.setLength(length); ! byteBuffer = file.getChannel().map(FileChannel.MapMode.READ_WRITE, 0, length); } --- 84,88 ---- protected void setLength(long length) throws IOException { super.setLength(length); ! byteBuffer = channel.map(FileChannel.MapMode.READ_WRITE, 0, length); } |
From: Arne V. <cob...@us...> - 2004-07-13 20:57:57
|
Update of /cvsroot/jrobin/src/org/jrobin/cmd In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv10289/org/jrobin/cmd Modified Files: RrdCmdScanner.java RrdCommander.java RrdToolCmd.java Added Files: RrdXportCmd.java Log Message: JRobin 1.4.1 - Changed to experimental rrdtool cmd parsing - Added RrdXportCmd Index: RrdCmdScanner.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/cmd/RrdCmdScanner.java,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** RrdCmdScanner.java 12 Jul 2004 13:35:16 -0000 1.1 --- RrdCmdScanner.java 13 Jul 2004 20:57:44 -0000 1.2 *************** *** 33,39 **** class RrdCmdScanner { ! private static final Pattern PATTERN = Pattern.compile("([^\"\\s]*\"[^\"]*\")|([^\"\\s]+)"); ! private LinkedList words = new LinkedList(); private String cmdType; RrdCmdScanner(String[] cmdWords) { --- 33,43 ---- class RrdCmdScanner { ! //private static final Pattern PATTERN = Pattern.compile("([^\"\\s]*\"[^\"]*\")|([^\"\\s]+)"); ! private String cmdType; + private String command; + + private LinkedList options = new LinkedList(); + private LinkedList words = new LinkedList(); RrdCmdScanner(String[] cmdWords) { *************** *** 46,54 **** } ! RrdCmdScanner(String command) { ! parseWords(command); } ! private void parseWords(String command) { Matcher m = PATTERN.matcher(command); while(m.find()) { --- 50,122 ---- } ! RrdCmdScanner( String command ) ! { ! // Set the command type only ! String cmd = command.trim(); ! int typePos = command.indexOf( ' ' ); ! cmdType = cmd.substring( 0, typePos ); ! ! this.command = cmd.substring( typePos ).trim(); ! ! //parseWords(command); } ! protected void parse( String[] keywords ) ! { ! StringBuffer sbuf = new StringBuffer( "( -)"); ! ! for ( int i = 0; i < keywords.length; i++ ) ! sbuf.append( "|( " + keywords[i] + ":)" ); ! ! Pattern pattern = Pattern.compile( sbuf.toString() ); ! ! parseWords( command, pattern ); ! } ! ! private void parseWords( String command, Pattern pattern ) ! { ! int start = 0, stop = 0; ! ! Matcher m = pattern.matcher(command); ! ! while ( m.find() ) ! { ! if ( start == 0 ) ! start = m.start(); ! else ! { ! stop = m.start(); ! ! // Put this 'word' away ! storeWord( command.substring( start, stop ).trim() ); ! ! // This is a new start ! start = stop; ! stop = 0; ! } ! } ! ! // Ok, see if we have to put the last word away ! if ( start > 0 && stop == 0 ) ! storeWord( command.substring( start ).trim() ); ! } ! ! private void storeWord( String word ) ! { ! if ( word.charAt(0) == '-' ) // This is an option ! options.add( word ); ! else // This is a general 'word' ! { ! // TODO: Remove \ characters or other 'in between' characters that are used in scripting ! // TODO: Remove leading single and double quotes in text, make sure all special characters are detected and treated okay ! // TODO: Best way to try this probably to put the code from: http://www.jrobin.org/phpBB2/viewtopic.php?t=39 in a file ! // TODO: read that file in, and then see if the resulting string parses correctly ! words.add( word ); ! } ! } ! ! /* ! private void parseWords2(String command) { ! // Make this a bit more complex, read until ' -', or keyword Matcher m = PATTERN.matcher(command); while(m.find()) { *************** *** 62,65 **** --- 130,134 ---- } } + */ String getCmdType() { *************** *** 67,70 **** --- 136,171 ---- } + String getOptionValue( String shortFormWord, String longFormWord ) throws RrdException + { + String shortForm = "-" + shortFormWord; + String longForm = "--" + longFormWord; + + for ( int i = 0; i < options.size(); i++ ) + { + String value = null; + String option = (String) options.get( i ); + + if ( shortForm != null && option.startsWith( shortForm ) ) + value = option.substring( shortForm.length() ).trim(); + else if ( longForm != null && option.startsWith( longForm ) ) + { + // Next character might be = + value = option.substring( longForm.length() ).trim(); + if ( value.length() > 1 && value.charAt(0) == '=' ) + value = value.substring( 1 ); + } + + if ( value != null ) + { + options.remove( i ); + + return value; + } + } + + // Option not found + return null; + } + /* String getOptionValue(String shortForm, String longForm) throws RrdException { for(int i = 0; i < words.size(); i++) { *************** *** 87,90 **** --- 188,192 ---- return null; } + */ String getOptionValue(String shortForm, String longForm, String defaultValue) throws RrdException { *************** *** 94,97 **** --- 196,204 ---- boolean getBooleanOption(String shortForm, String longForm) throws RrdException { + return (getOptionValue( shortForm, longForm ) != null); + } + + /* + boolean getBooleanOption2(String shortForm, String longForm) throws RrdException { for(int i = 0; i < words.size(); i++) { String word = (String) words.get(i); *************** *** 105,108 **** --- 212,216 ---- return false; } + */ String[] getRemainingWords() { Index: RrdToolCmd.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/cmd/RrdToolCmd.java,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** RrdToolCmd.java 12 Jul 2004 13:35:17 -0000 1.1 --- RrdToolCmd.java 13 Jul 2004 20:57:47 -0000 1.2 *************** *** 34,37 **** --- 34,41 ---- abstract class RrdToolCmd { + + // Holds the list of keywords + static String[] keywords = new String[0]; + static boolean rrdDbPoolUsed = true; static boolean standardOutUsed = true; *************** *** 53,56 **** --- 57,61 ---- } + RrdCmdScanner cmdScanner; *************** *** 61,68 **** abstract String getCmdType(); ! Object go() throws IOException, RrdException { if(!getCmdType().equals(cmdScanner.getCmdType())) { return null; } return execute(); } --- 66,78 ---- abstract String getCmdType(); ! Object go() throws IOException, RrdException ! { if(!getCmdType().equals(cmdScanner.getCmdType())) { return null; } + + // Parse the command based on the keywords + cmdScanner.parse( keywords ); + return execute(); } Index: RrdCommander.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/cmd/RrdCommander.java,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** RrdCommander.java 13 Jul 2004 11:45:39 -0000 1.3 --- RrdCommander.java 13 Jul 2004 20:57:47 -0000 1.4 *************** *** 103,107 **** * unknown RRDTool syntax/command/option, internal RRD errors...) */ ! public static synchronized Object execute(String command) throws IOException, RrdException { RrdCmdScanner cmdScanner = new RrdCmdScanner(command); RrdToolCmd[] commanders = { --- 103,108 ---- * unknown RRDTool syntax/command/option, internal RRD errors...) */ ! public static synchronized Object execute(String command) throws IOException, RrdException ! { RrdCmdScanner cmdScanner = new RrdCmdScanner(command); RrdToolCmd[] commanders = { *************** *** 121,124 **** --- 122,143 ---- throw new RrdException("Unknown RRDTool command: " + command); } + /*public static synchronized Object execute(String command) throws IOException, RrdException { + RrdCmdScanner cmdScanner = new RrdCmdScanner(command); + RrdToolCmd[] commanders = { + new RrdCreateCmd(cmdScanner), + new RrdLastCmd(cmdScanner), + new RrdUpdateCommand(cmdScanner), + new RrdDumpCmd(cmdScanner), + new RrdFetchCmd(cmdScanner), + new RrdXportCmd(cmdScanner) + }; + for(int i = 0; i < commanders.length; i++) { + Object result = commanders[i].go(); + if(result != null) { + return result; + } + } + throw new RrdException("Unknown RRDTool command: " + command); + }*/ public static void main(String[] args) { --- NEW FILE: RrdXportCmd.java --- /* ============================================================ * JRobin : Pure java implementation of RRDTool's functionality * ============================================================ * * Project Info: http://www.jrobin.org * Project Lead: Sasa Markovic (sa...@jr...); * * (C) Copyright 2003, by Sasa Markovic. * * Developers: Sasa Markovic (sa...@jr...) * Arne Vandamme (cob...@jr...) * * This library is free software; you can redistribute it and/or modify it under the terms * of the GNU Lesser General Public License as published by the Free Software Foundation; * either version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with this * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, * Boston, MA 02111-1307, USA. */ package org.jrobin.cmd; import org.jrobin.core.RrdException; import org.jrobin.graph.RrdExportDef; import org.jrobin.graph.RrdExport; import org.jrobin.graph.ExportData; import java.io.IOException; /** * <p>Description</p> * * @author Arne Vandamme (cob...@jr...) */ public class RrdXportCmd extends RrdToolCmd { static final String DEFAULT_START = "end-1day"; static final String DEFAULT_END = "now"; static { keywords = new String[] { "DEF", "CDEF", "XPORT" }; } public RrdXportCmd( RrdCmdScanner cmdScanner ) { super(cmdScanner); } String getCmdType() { return "xport"; } Object execute() throws RrdException, IOException { // --start String startStr = cmdScanner.getOptionValue( "s", "start", DEFAULT_START ); TimeSpec spec1 = new TimeParser(startStr).parse(); // --end String endStr = cmdScanner.getOptionValue( "e", "end", DEFAULT_END ); TimeSpec spec2 = new TimeParser(endStr).parse(); long[] timestamps = TimeSpec.getTimestamps(spec1, spec2); // --step String resolutionStr = cmdScanner.getOptionValue( "step", null, "1" ); // Smallest step possible is default long resolution = parseLong( resolutionStr ); // --maxrows String maxrowsStr = cmdScanner.getOptionValue( "m", "maxrows", "400" ); int maxRows = parseInt( maxrowsStr ); RrdExportDef exportDef = new RrdExportDef( timestamps[0], timestamps[1] ); exportDef.setResolution( resolution ); exportDef.setStrictExport( true ); // Always use strict export in case of RrdTool command String[] words = cmdScanner.getRemainingWords(); for ( int i = 0; i < words.length; i++ ) { if ( words[i].startsWith("DEF:") ) parseDef( words[i], exportDef ); else if ( words[i].startsWith("CDEF:") ) parseCdef( words[i], exportDef ); else if ( words[i].startsWith("XPORT:") ) parseXport( words[i], exportDef ); } // Now create the export data RrdExport export = new RrdExport( exportDef ); ExportData data = export.fetch( maxRows ); System.out.println( data.exportXml() ); return data; } /** * DEF:vname=rrd:ds-name:CF */ private void parseDef( String word, RrdExportDef def ) throws RrdException { String[] tokens = word.split(":"); if ( tokens.length != 4 ) throw new RrdException( "Invalid DEF command: " + word ); String[] token1 = tokens[1].split("="); if ( token1.length != 2 ) throw new RrdException( "Invalid DEF command: " + word ); def.datasource( token1[0], token1[1], tokens[2], tokens[3] ); } /** * CDEF:vname=rpn-expression */ private void parseCdef( String word, RrdExportDef def ) throws RrdException { String[] tokens = word.split(":"); if ( tokens.length != 2 ) throw new RrdException( "Invalid CDEF command: " + word ); String[] token1 = tokens[1].split("="); if ( token1.length != 2 ) throw new RrdException( "Invalid CDEF command: " + word ); def.datasource( token1[0], token1[1] ); } /** * XPORT:vname:legend */ private void parseXport( String word, RrdExportDef def ) throws RrdException { String[] tokens = word.split(":"); if ( tokens.length < 2 || tokens.length > 3 ) throw new RrdException( "Invalid XPORT command: " + word ); if ( tokens.length == 2 ) def.export( tokens[1] ); else def.export( tokens[1], tokens[2] ); } public static void main( String[] args ) throws Exception { String cmd = "xport --start now-1h --end now DEF:xx=host-inout.lo.rrd:output:AVERAGE DEF:yy=host-inout.lo.rrd:input:AVERAGE CDEF:aa=xx,yy,+,8,* " + "XPORT:xx:\"out bytes\" XPORT:aa:\"in and out bits\""; cmd = "xport --start now-1h --end now -m 10 DEF:xx=/code/idea-projects/jrobin/res/demo/eth0.rrd:ifOutOctets:AVERAGE XPORT:xx:outgoing traffic"; RrdCommander.execute( cmd ); } } |
From: Arne V. <cob...@us...> - 2004-07-13 18:42:34
|
Update of /cvsroot/jrobin/src/org/jrobin/core In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv9700/org/jrobin/core Modified Files: RrdBackendFactory.java RrdFileBackendFactory.java RrdMemoryBackendFactory.java RrdNioBackendFactory.java Log Message: JRobin 1.4.0 - Minor tweaks - Added LazyDemo demo Index: RrdFileBackendFactory.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/core/RrdFileBackendFactory.java,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** RrdFileBackendFactory.java 1 Jun 2004 14:41:01 -0000 1.4 --- RrdFileBackendFactory.java 13 Jul 2004 18:42:24 -0000 1.5 *************** *** 64,68 **** * @return Factory name (equals to string "FILE") */ ! protected String getFactoryName() { return NAME; } --- 64,68 ---- * @return Factory name (equals to string "FILE") */ ! public String getFactoryName() { return NAME; } Index: RrdNioBackendFactory.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/core/RrdNioBackendFactory.java,v retrieving revision 1.7 retrieving revision 1.8 diff -C2 -d -r1.7 -r1.8 *** RrdNioBackendFactory.java 9 Jun 2004 09:44:47 -0000 1.7 --- RrdNioBackendFactory.java 13 Jul 2004 18:42:24 -0000 1.8 *************** *** 133,137 **** * @return Factory name (equals to string "NIO") */ ! protected String getFactoryName() { return NAME; } --- 133,137 ---- * @return Factory name (equals to string "NIO") */ ! public String getFactoryName() { return NAME; } Index: RrdBackendFactory.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/core/RrdBackendFactory.java,v retrieving revision 1.6 retrieving revision 1.7 diff -C2 -d -r1.6 -r1.7 *** RrdBackendFactory.java 1 Jun 2004 14:41:01 -0000 1.6 --- RrdBackendFactory.java 13 Jul 2004 18:42:19 -0000 1.7 *************** *** 190,193 **** * @return Name of the factory. */ ! protected abstract String getFactoryName(); } --- 190,193 ---- * @return Name of the factory. */ ! public abstract String getFactoryName(); } Index: RrdMemoryBackendFactory.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/core/RrdMemoryBackendFactory.java,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** RrdMemoryBackendFactory.java 20 May 2004 14:49:29 -0000 1.2 --- RrdMemoryBackendFactory.java 13 Jul 2004 18:42:24 -0000 1.3 *************** *** 94,98 **** * @return Factory name (equals to "MEMORY"). */ ! protected String getFactoryName() { return NAME; } --- 94,98 ---- * @return Factory name (equals to "MEMORY"). */ ! public String getFactoryName() { return NAME; } |
From: Arne V. <cob...@us...> - 2004-07-13 16:20:17
|
Update of /cvsroot/jrobin/src/org/jrobin/graph In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv10041/org/jrobin/graph Modified Files: FetchSourceList.java Grapher.java RrdExporter.java Log Message: JRobin 1.4.0 - Minor tweaks - Added LazyDemo demo Index: Grapher.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/graph/Grapher.java,v retrieving revision 1.17 retrieving revision 1.18 diff -C2 -d -r1.17 -r1.18 *** Grapher.java 10 Jul 2004 00:07:03 -0000 1.17 --- Grapher.java 13 Jul 2004 16:20:07 -0000 1.18 *************** *** 285,288 **** --- 285,290 ---- protected boolean shouldGenerate( long prevGenTime ) throws RrdException, IOException { + FetchSourceList fetchSources = graphDef.getFetchSources(); + fetchSources.openAll(); Index: RrdExporter.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/graph/RrdExporter.java,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** RrdExporter.java 11 Jul 2004 22:04:13 -0000 1.3 --- RrdExporter.java 13 Jul 2004 16:20:07 -0000 1.4 *************** *** 48,56 **** protected Source[] sources; protected HashMap sourceIndex; - protected FetchSourceList fetchSources; RrdExporter( RrdExportDef def ) { ! rrdOpener = new RrdOpener( false, true ); setExportDef( def ); } --- 48,55 ---- protected Source[] sources; protected HashMap sourceIndex; RrdExporter( RrdExportDef def ) { ! setRrdOpener( new RrdOpener( false, true ) ); setExportDef( def ); } *************** *** 58,62 **** RrdExporter( RrdExportDef def, RrdOpener rrdOpener ) { ! this.rrdOpener = rrdOpener; setExportDef( def ); } --- 57,61 ---- RrdExporter( RrdExportDef def, RrdOpener rrdOpener ) { ! setRrdOpener( rrdOpener ); setExportDef( def ); } *************** *** 65,76 **** { this.def = def; - this.fetchSources = def.getFetchSources(); - fetchSources.setRrdOpener( rrdOpener ); } void setRrdOpener( RrdOpener rrdOpener ) { ! if ( fetchSources != null ) ! fetchSources.setRrdOpener( rrdOpener ); } --- 64,72 ---- { this.def = def; } void setRrdOpener( RrdOpener rrdOpener ) { ! this.rrdOpener = rrdOpener; } *************** *** 87,94 **** --- 83,94 ---- protected void calculateSeries( int maxRows ) throws RrdException, IOException { + FetchSourceList fetchSources; ValueExtractor ve; FetchSource src; String[] varList; + fetchSources = def.getFetchSources(); + fetchSources.setRrdOpener( rrdOpener ); + long finalEndTime = Long.MAX_VALUE; boolean changingEndTime = false; Index: FetchSourceList.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/graph/FetchSourceList.java,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** FetchSourceList.java 29 Jun 2004 09:34:39 -0000 1.2 --- FetchSourceList.java 13 Jul 2004 16:20:07 -0000 1.3 *************** *** 50,53 **** --- 50,54 ---- private boolean persistent; + private boolean openerLocked; private boolean opened; *************** *** 69,73 **** public FetchSourceList( int defaultSize ) { ! this( defaultSize, false ); } --- 70,74 ---- public FetchSourceList( int defaultSize ) { ! this( defaultSize, false, false ); } *************** *** 82,92 **** * @param persistent True if the list is persistent, false if not. */ ! public FetchSourceList( int defaultSize, boolean persistent ) { ! map = new HashMap( defaultSize ); ! list = new ArrayList( defaultSize ); ! opened = false; ! this.persistent = persistent; } --- 83,94 ---- * @param persistent True if the list is persistent, false if not. */ ! public FetchSourceList( int defaultSize, boolean persistent, boolean lockOpener ) { ! map = new HashMap( defaultSize ); ! list = new ArrayList( defaultSize ); ! opened = false; ! this.persistent = persistent; ! this.openerLocked = lockOpener; } *************** *** 103,109 **** * for RrdDb retrieval. */ ! public FetchSourceList( int defaultSize, boolean persistent, RrdOpener rrdOpener ) { ! this( defaultSize, persistent ); this.rrdOpener = rrdOpener; --- 105,111 ---- * for RrdDb retrieval. */ ! public FetchSourceList( int defaultSize, boolean persistent, boolean lockOpener, RrdOpener rrdOpener ) { ! this( defaultSize, persistent , lockOpener); this.rrdOpener = rrdOpener; *************** *** 122,126 **** { // Only allow RrdOpener change if not persistent ! if ( !persistent ) this.rrdOpener = rrdOpener; } --- 124,128 ---- { // Only allow RrdOpener change if not persistent ! if ( !persistent && !openerLocked ) this.rrdOpener = rrdOpener; } *************** *** 143,151 **** * @param persistent True if the list should behave as persistent. */ ! public void setPersistent( boolean persistent ) { this.persistent = persistent; } /** * Returns the number of FetchSources hold in the list. * @return Number of different FetchSources. --- 145,170 ---- * @param persistent True if the list should behave as persistent. */ ! public void setPersistent( boolean persistent ) ! { this.persistent = persistent; } /** + * This locks the RrdOpener in the FetchSourceList. Subsequent call so + * setRrdOpener() will be ignored until it is unlocked. + */ + public void lockOpener() { + openerLocked = true; + } + + /** + * Unlocks the RrdOpener object, means calls to setRrdOpener() can change + * the internal rrdOpener object. + */ + public void unlockOpener() { + openerLocked = false; + } + + /** * Returns the number of FetchSources hold in the list. * @return Number of different FetchSources. |
From: Arne V. <cob...@us...> - 2004-07-13 16:19:18
|
Update of /cvsroot/jrobin/src/org/jrobin/demo/graph In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv9814/org/jrobin/demo/graph Added Files: LazyDemo.java LazyDemoOpener.java Log Message: JRobin 1.4.0 - Minor tweaks - Added LazyDemo demo --- NEW FILE: LazyDemo.java --- /* ============================================================ * JRobin : Pure java implementation of RRDTool's functionality * ============================================================ * * Project Info: http://www.jrobin.org * Project Lead: Sasa Markovic (sa...@jr...) * * Developers: Sasa Markovic (sa...@jr...) * Arne Vandamme (cob...@jr...) * * (C) Copyright 2003, by Sasa Markovic. * * This library is free software; you can redistribute it and/or modify it under the terms * of the GNU Lesser General Public License as published by the Free Software Foundation; * either version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with this * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, * Boston, MA 02111-1307, USA. */ package org.jrobin.demo.graph; import org.jrobin.core.Util; import org.jrobin.core.RrdException; import org.jrobin.graph.RrdGraphDef; import org.jrobin.graph.RrdGraph; import org.jrobin.graph.FetchSourceList; import java.io.File; import java.io.IOException; import java.awt.*; import java.util.GregorianCalendar; /** * <p>This demo shows the use of the FetchSourceList class, the RrdOpener class * and the RrdGraphDef setLazy() method.</p> * * @author Arne Vandamme (cob...@ch...) */ public class LazyDemo { private static String rrd1 = "eth0.rrd"; private static String rrd2 = "eth1.rrd"; private static String graph1 = Util.getJRobinDemoPath( "lazy-graph1.png" ); private static String graph2 = Util.getJRobinDemoPath( "lazy-graph2.png" ); private static String graph3 = Util.getJRobinDemoPath( "lazy-graph3.png" ); private static String graph4 = Util.getJRobinDemoPath( "lazy-graph4.png" ); private static String demoResources = ""; private static int runCount = 0; private static long runStart, runStop; private static long[] runTimes = new long[4]; private static RrdGraph graph; private static RrdGraphDef graphDef; private static GregorianCalendar start1, end1, start2, end2, start3, end3, start4, end4; static { // Statically initialize the start and end times start1 = new GregorianCalendar( 2004, GregorianCalendar.JULY, 3 ); end1 = new GregorianCalendar( 2004, GregorianCalendar.JULY, 4 ); start2 = new GregorianCalendar( 2004, GregorianCalendar.JULY, 1 ); end2 = new GregorianCalendar( 2004, GregorianCalendar.JULY, 8 ); start3 = new GregorianCalendar( 2004, GregorianCalendar.JUNE, 1 ); end3 = new GregorianCalendar( 2004, GregorianCalendar.JULY, 1 ); start4 = new GregorianCalendar( 2004, GregorianCalendar.JULY, 1 ); end4 = new GregorianCalendar( 2004, GregorianCalendar.AUGUST, 1 ); } private static void println( String str ) { System.out.println( str ); } private static void prepare( String[] args ) { if ( args.length != 1 ) { println( "Usage: LazyDemo <path_to_demo_resources>" ); println( " The only argument to this program should be the path to the JRobin" ); println( " demo resources. These are normally included in the JRobin distribution" ); println( " in the <jrobin>/res/demo directory." ); System.exit( 1 ); } demoResources = new File(args[0]).getAbsolutePath() + "/"; rrd1 = demoResources + rrd1; rrd2 = demoResources + rrd2; } private static void createGraphs() throws RrdException, IOException { runStart = System.currentTimeMillis(); // -- First graph is one day in time graphDef.setTimePeriod( start1, end1 ); graph.saveAsPNG( graph1 ); // -- Second is one week in time graphDef.setTimePeriod( start2, end2 ); graph.saveAsPNG( graph2 ); // -- Third is one month in time graphDef.setTimePeriod( start3, end3 ); graph.saveAsPNG( graph3 ); // -- Fourth is again one month in time graphDef.setTimePeriod( start4, end4 ); graph.saveAsPNG( graph4 ); runStop = System.currentTimeMillis(); runTimes[ runCount++ ] = (runStop - runStart); } public static void main( String[] args ) throws RrdException, IOException { prepare( args ); println( "+-----------------------------------------------------------------------------------+" ); println( "| JRobin LazyDemo |" ); println( "| |" ); println( "| This demo illustrates the use of RrdOpener, FetchSourceList and the lazy flag of |" ); println( "| the RrdGraphDef. |" ); println( "| |" ); println( "+-----------------------------------------------------------------------------------+" ); long execStart = System.currentTimeMillis(); // -- Create the basic RrdGraphDef and RrdGraph graphDef = new RrdGraphDef(); graphDef.area( "bitsOutEth0", Color.RED, "Outgoing eth0" ); graphDef.stack( "bitsOutEth1", Color.GREEN, "Outgoing eth1" ); graphDef.stack( "bitsInEth0", Color.BLUE, "Incoming eth0" ); graphDef.stack( "bitsInEth1", Color.YELLOW, "Incoming eth1" ); graph = new RrdGraph( graphDef ); // -- Put the datasources in a FetchSourceList and add it to the graphDef // -- The FetchSourceList also uses our LazyDemoOpener, overriding the default RrdOpener for a graph // -- Lock the RrdOpener, this way it is not overridden by graph generation FetchSourceList fsl = new FetchSourceList( 2 , false, true, new LazyDemoOpener() ); fsl.add( "bitsOutEth0", rrd1, "ifOutOctets", "AVERAGE" ); fsl.add( "bitsInEth0", rrd1, "ifInOctets", "AVERAGE" ); fsl.add( "bitsOutEth1", rrd2, "ifOutOctets", "AVERAGE" ); fsl.add( "bitsInEth1", rrd2, "ifInOctets", "AVERAGE" ); graphDef.setDatasources( fsl ); // -- Run the graphs 2 times, second time with lazy, but the FetchSourceList should not be persistent println( "\n>>> GRAPH RUN 1" ); graphDef.setLazy( false ); // Disable lazy flag, graphs will be generated createGraphs(); println( "\n>>> GRAPH RUN 2" ); graphDef.setLazy( true ); // Enable lazy flag, graphs will be skipped createGraphs(); // -- Now run the graphs 2 times again, second time with lazy, but now the FetchSourceList is persistent fsl.setPersistent( true ); // Mark the FSL as persistent, RRDs will only be opened once, not closed again println( "\n>>> Manually opening all RRD references" ); fsl.openAll(); // Manually open all RRDs, this is more obvious than the implicit opening in graph generation println( "\n>>> GRAPH RUN 3" ); graphDef.setLazy( false ); // Disable lazy flag, graphs will be generated createGraphs(); println( "\n>>> GRAPH RUN 4" ); graphDef.setLazy( true ); // Enable lazy flag, graphs will be skipped createGraphs(); fsl.setPersistent( false ); // Remove persistence so we can release datasources println( "\n>>> Manually releasing all RRD references" ); fsl.releaseAll(); // Release the datasources again // -- Print out timing results println( "\n>>> Generation time results:" ); println( " First run, no lazy, no persistence - normal generation: " + runTimes[0] + " ms" ); println( " Second run, lazy, no persistence - generation skipped: " + runTimes[1] + " ms" ); println( " Third run, no lazy, persistence - normal generation: " + runTimes[2] + " ms" ); println( " Fourth run, lazy, persistence - generation skipped: " + runTimes[3] + " ms" ); } } --- NEW FILE: LazyDemoOpener.java --- /* ============================================================ * JRobin : Pure java implementation of RRDTool's functionality * ============================================================ * * Project Info: http://www.jrobin.org * Project Lead: Sasa Markovic (sa...@jr...); * * (C) Copyright 2003, by Sasa Markovic. * * Developers: Sasa Markovic (sa...@jr...) * Arne Vandamme (cob...@jr...) * * This library is free software; you can redistribute it and/or modify it under the terms * of the GNU Lesser General Public License as published by the Free Software Foundation; * either version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with this * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, * Boston, MA 02111-1307, USA. */ package org.jrobin.demo.graph; import org.jrobin.core.RrdOpener; import org.jrobin.core.RrdDb; import org.jrobin.core.RrdBackendFactory; import org.jrobin.core.RrdException; import java.io.IOException; /** * <p>Basic implementation showing the use of RrdOpener. This demo * class simply logs an attempt to retrieve an RrdDb and diverts all * actual RrdDb retrieval to the basic RrdOpener.</p> * * @author Arne Vandamme (cob...@jr...) */ public class LazyDemoOpener extends RrdOpener { /** * Custom constructor. */ LazyDemoOpener() { // Our custom RrdOpener does not use the pool, to better illustrate super( false, true ); System.out.println( "LOG: RrdOpener object created." ); } /** * Retrieves an RrdDb instance. */ public RrdDb getRrd( String name, RrdBackendFactory backendFactory ) throws RrdException, IOException { RrdDb db = null; System.out.println( "LOG: Access request for RRD with name " + name + " (backend: " + backendFactory.getFactoryName() + ")" ); db = super.getRrd( name, backendFactory ); if ( db == null ) System.out.println( "LOG: FAILURE locating RRD with name " + name ); else System.out.println( "LOG: SUCCESS locating RRD with name " + name ); return db; } /** * Releases RrdDb instance. */ public void releaseRrd( RrdDb rrdDb ) throws IOException, RrdException { System.out.println( "LOG: Releasing RRD " + rrdDb.getPath() ); super.releaseRrd( rrdDb ); } } |
From: Arne V. <cob...@us...> - 2004-07-13 12:16:18
|
Update of /cvsroot/jrobin/src/org/jrobin/demo/graph In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv27003/org/jrobin/demo/graph Modified Files: ExportTemplate.java Added Files: ExportExportDemo.java ExportImportDemo.java Log Message: JRobin 1.4.0 - Minor tweaks - Added ExportExportDemo and ExportImportDemo - Added importXml() with dsNamePrefix to FetchData - Added demo resources --- NEW FILE: ExportExportDemo.java --- /* ============================================================ * JRobin : Pure java implementation of RRDTool's functionality * ============================================================ * * Project Info: http://www.jrobin.org * Project Lead: Sasa Markovic (sa...@jr...); * * (C) Copyright 2003, by Sasa Markovic. * * Developers: Sasa Markovic (sa...@jr...) * Arne Vandamme (cob...@jr...) * * This library is free software; you can redistribute it and/or modify it under the terms * of the GNU Lesser General Public License as published by the Free Software Foundation; * either version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with this * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, * Boston, MA 02111-1307, USA. */ package org.jrobin.demo.graph; import org.jrobin.graph.RrdExportDef; import org.jrobin.graph.RrdExportDefTemplate; import org.jrobin.graph.RrdExport; import org.jrobin.graph.ExportData; import org.jrobin.core.RrdException; import org.jrobin.core.Util; import java.io.IOException; import java.io.File; import java.util.GregorianCalendar; /** * <p>This is a small demo that illustrates JRobin export functionality.</p> * * @author Arne Vandamme (cob...@jr...) */ public class ExportExportDemo { public static String exportRrd1 = Util.getJRobinDemoPath( "export-eth0.xml" ); public static String exportRrd2 = Util.getJRobinDemoPath( "export-eth1.xml" ); private static String demoResources = ""; private static void println( String str ) { System.out.println( str ); } private static void prepare( String[] args ) { if ( args.length != 1 ) { println( "Usage: ExportExportDemo <path_to_demo_resources>" ); println( " The only argument to this program should be the path to the JRobin" ); println( " demo resources. These are normally included in the JRobin distribution" ); println( " in the <jrobin>/res/demo directory." ); System.exit( 1 ); } demoResources = new File(args[0]).getAbsolutePath() + "/"; } public static void main( String[] args ) throws RrdException, IOException { prepare( args ); println( "+----------------------------------------------------------------------------------+" ); println( "| JRobin ExportExportDemo |" ); println( "| |" ); println( "| This demo will perform the same export on two different rrd files. In fact the |" ); println( "| two RRD files contain the same data, they are data from a network interface and |" ); println( "| contain a full days worth of samples on July 3rd 2004. For this example the RRD |" ); println( "| are treated as if from two different interfaces: eth0 and eth1. |" ); println( "| |" ); println( "+----------------------------------------------------------------------------------+" ); long execStart = System.currentTimeMillis(); // -- Read in the export def xml println( ">>> Reading export def template\n" ); RrdExportDefTemplate xmlTemplate = new RrdExportDefTemplate( new File(demoResources + "exportdef.xml") ); // -- The data we're interested in is from the 3rd of july 2004, to the 4th GregorianCalendar start = new GregorianCalendar( 2004, GregorianCalendar.JULY, 3 ); GregorianCalendar end = new GregorianCalendar( 2004, GregorianCalendar.JULY, 4 ); xmlTemplate.setVariable( "start", start ); xmlTemplate.setVariable( "end", end ); Util.getLapTime(); // -- Exporting the first rrd println( ">>> Exporting data from eth0 for July 3rd, 2004" ); println( ">>> Number of rows for the export is limited to 400." ); xmlTemplate.setVariable( "rrd", demoResources + "eth0.rrd" ); RrdExportDef exportDef = xmlTemplate.getRrdExportDef(); RrdExport export = new RrdExport( exportDef ); // We don't limit the number of rows returned, this will try to auto limit on 400 max ExportData dataFromRrd1 = export.fetch(); // Save the exported data to export xml dataFromRrd1.exportXml( exportRrd1 ); println( ">>> File saved: " + exportRrd1 + " " + Util.getLapTime() + "\n" ); // -- Exporting the second rrd println( ">>> Exporting data from eth1 for July 3rd, 2004" ); println( ">>> Number of rows for the export is limited to 20." ); println( " This means the same data as in the previous export (since in fact" ); println( " both RRD files are the same) will be aggregated to around 20 rows." ); xmlTemplate.setVariable( "rrd", demoResources + "eth1.rrd" ); exportDef = xmlTemplate.getRrdExportDef(); export.setExportDef( exportDef ); // Now we limit the number of rows retrieved to 20 ExportData dataFromRrd2 = export.fetch( 20 ); // Save the exported data to export xml dataFromRrd2.exportXml( exportRrd2 ); println( ">>> File saved: " + exportRrd2 + " " + Util.getLapTime() + "\n" ); long execStop = System.currentTimeMillis(); println( ">>> Demo finished in " + (execStop - execStart) + " milliseconds" ); } } --- NEW FILE: ExportImportDemo.java --- /* ============================================================ * JRobin : Pure java implementation of RRDTool's functionality * ============================================================ * * Project Info: http://www.jrobin.org * Project Lead: Sasa Markovic (sa...@jr...); * * (C) Copyright 2003, by Sasa Markovic. * * Developers: Sasa Markovic (sa...@jr...) * Arne Vandamme (cob...@jr...) * * This library is free software; you can redistribute it and/or modify it under the terms * of the GNU Lesser General Public License as published by the Free Software Foundation; * either version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with this * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, * Boston, MA 02111-1307, USA. */ package org.jrobin.demo.graph; import org.jrobin.core.Util; import org.jrobin.core.RrdException; import org.jrobin.graph.*; import java.io.File; import java.io.IOException; import java.util.GregorianCalendar; /** * <p>This is a small demo that creates a graph based on the export XML from the ExportExportDemo.</p> * * @author Arne Vandamme (cob...@jr...) */ public class ExportImportDemo { private static String exportRrd1 = ExportExportDemo.exportRrd1; private static String exportRrd2 = ExportExportDemo.exportRrd2; private static String exportCombined = Util.getJRobinDemoPath( "export-combined.xml" ); private static String graphFile = Util.getJRobinDemoPath( "export-graph.png" ); private static String demoResources = ""; private static void println( String str ) { System.out.println( str ); } private static void prepare( String[] args ) { if ( args.length != 1 ) { println( "Usage: ExportImportDemo <path_to_demo_resources>" ); println( " The only argument to this program should be the path to the JRobin" ); println( " demo resources. These are normally included in the JRobin distribution" ); println( " in the <jrobin>/res/demo directory." ); System.exit( 1 ); } demoResources = new File(args[0]).getAbsolutePath() + "/"; } public static void main( String[] args ) throws RrdException, IOException { prepare( args ); println( "+-----------------------------------------------------------------------------------+" ); println( "| JRobin ExportImportDemo |" ); println( "| |" ); println( "| This demo supposes the ExportExportDemo has been run and the necessary data has |" ); println( "| been exported to the jrobin-demo directory. The ExportImportDemo creates a graph |" ); println( "| containing the data from the separate export XML files, the configuration of the |" ); println( "| graph is in the RrdGraphDef xml file in the directory passed as argument on the |" ); println( "| command line. |" ); println( "| |" ); println( "+-----------------------------------------------------------------------------------+" ); long execStart = System.currentTimeMillis(); // -- Read in the graph def xml RrdGraphDefTemplate xmlTemplate = new RrdGraphDefTemplate( new File(demoResources + "export-graphdef.xml") ); // -- The data we're interested in is from the 3rd of july 2004, to the 4th GregorianCalendar start = new GregorianCalendar( 2004, GregorianCalendar.JULY, 3 ); GregorianCalendar end = new GregorianCalendar( 2004, GregorianCalendar.JULY, 4 ); xmlTemplate.setVariable( "start", start ); xmlTemplate.setVariable( "end", end ); xmlTemplate.setVariable( "export1", exportRrd1 ); xmlTemplate.setVariable( "export2", exportRrd2 ); Util.getLapTime(); // -- Create the graph println( ">>> Creating graph image from XML graph def" ); RrdGraphDef graphDef = xmlTemplate.getRrdGraphDef(); RrdGraph graph = new RrdGraph( graphDef ); graph.saveAsPNG( graphFile ); println( ">>> File saved: " + graphFile + " " + Util.getLapTime() + "\n" ); // -- Dump the combined export println( ">>> Dumping combined export xml" ); ExportData combinedData = graph.getExportData(); combinedData.exportXml( exportCombined ); println( ">>> File saved: " + exportCombined + " " + Util.getLapTime() + "\n" ); // -- Print out information println( ">>> Retrieving AVERAGE outoing traffic from combined export" ); println( combinedData.print( "eth0-2", "AVERAGE", " From eth0 data: @5.2 @sbit/s" ) ); println( combinedData.print( "eth1-2", "AVERAGE", " From eth1 data: @5.2 @sbit/s" ) ); long execStop = System.currentTimeMillis(); println( "\n>>> Demo finished in " + (execStop - execStart) + " milliseconds" ); } } Index: ExportTemplate.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/demo/graph/ExportTemplate.java,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** ExportTemplate.java 11 Jul 2004 22:44:59 -0000 1.1 --- ExportTemplate.java 13 Jul 2004 12:16:08 -0000 1.2 *************** *** 91,95 **** public static void main( String[] args ) { ! if ( args.length < 2 ) { System.out.println( "Usage: ExportTemplate [-m width] [-f <dump_file>] <template_file>" ); --- 91,95 ---- public static void main( String[] args ) { ! if ( args.length < 1 ) { System.out.println( "Usage: ExportTemplate [-m width] [-f <dump_file>] <template_file>" ); |
From: Arne V. <cob...@us...> - 2004-07-13 12:15:14
|
Update of /cvsroot/jrobin/res/demo In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv26733/demo Added Files: eth0.rrd eth1.rrd export-graphdef.xml exportdef.xml Log Message: JRobin 1.4.0 - Minor tweaks - Added ExportExportDemo and ExportImportDemo - Added importXml() with dsNamePrefix to FetchData - Added demo resources --- NEW FILE: eth1.rrd --- (This appears to be a binary file; contents omitted.) --- NEW FILE: eth0.rrd --- (This appears to be a binary file; contents omitted.) --- NEW FILE: exportdef.xml --- <!-- This is a sample RrdExportDef in XML format. --> <rrd_export_def> <span> <start>${start}</start> <end>${end}</end> </span> <datasources> <def> <name>bytesIn</name> <rrd>${rrd}</rrd> <source>ifInOctets</source> <cf>AVERAGE</cf> </def> <def> <name>bytesOut</name> <rrd>${rrd}</rrd> <source>ifOutOctets</source> <cf>AVERAGE</cf> </def> <def> <name>bitsIn</name> <rpn>bytesIn,8,*</rpn> </def> <def> <name>bitsOut</name> <rpn>bytesOut,8,*</rpn> </def> </datasources> <exports> <export> <datasource>bitsIn</datasource> <legend>Incoming traffic</legend> </export> <export> <datasource>bitsOut</datasource> <legend>Outgoing traffic</legend> </export> </exports> </rrd_export_def> --- NEW FILE: export-graphdef.xml --- <!-- This is a sample RrdGraphDef in XML format. --> <rrd_graph_def> <span> <start>${start}</start> <end>${end}</end> </span> <datasources> <export_data> <file>${export1}</file> <ds_name_prefix>eth0-</ds_name_prefix> </export_data> <export_data> <file>${export2}</file> <ds_name_prefix>eth1-</ds_name_prefix> </export_data> </datasources> <graph> <line> <datasource>eth1-2</datasource> <color>#0000FF</color> <legend>Outgoing eth1</legend> <width>2</width> </line> <line> <datasource>eth0-2</datasource> <color>#FF0000</color> <legend>Outgoing eth0</legend> <width>2</width> </line> </graph> </rrd_graph_def> |
From: Arne V. <cob...@us...> - 2004-07-13 12:14:08
|
Update of /cvsroot/jrobin/res/demo In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv26428/demo Log Message: Directory /cvsroot/jrobin/res/demo added to the repository |
From: Arne V. <cob...@us...> - 2004-07-13 12:13:24
|
Update of /cvsroot/jrobin/src/org/jrobin/graph In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv26272/org/jrobin/graph Modified Files: ExportData.java RrdExportDefTemplate.java RrdGraphDefTemplate.java Log Message: JRobin 1.4.0 - Minor tweaks - Added ExportExportDemo and ExportImportDemo - Added importXml() with dsNamePrefix to FetchData - Added demo resources Index: ExportData.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/graph/ExportData.java,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** ExportData.java 11 Jul 2004 22:04:13 -0000 1.3 --- ExportData.java 13 Jul 2004 12:13:13 -0000 1.4 *************** *** 103,106 **** --- 103,121 ---- /** + * Create an ExportData object based on export XML string.. + * + * @param xportXml File containing export xml. + * @param dsNamePrefix Prefix of the datasource names. + * @throws RrdException Thrown in case of JRobin specific exception. + * @throws IOException Thrown in case of I/O related exception. + */ + public ExportData( String xportXml, String dsNamePrefix ) throws RrdException, IOException + { + this(); + + importXml( xportXml, dsNamePrefix ); + } + + /** * Create an ExportData object based on export XML file. * *************** *** 131,134 **** --- 146,163 ---- } + /** + * Create an ExportData object based on export XML file. + * + * @param xmlFile File containing export xml. + * @param dsNamePrefix Prefix of the datasource names. + * @throws RrdException Thrown in case of JRobin specific exception. + * @throws IOException Thrown in case of I/O related exception. + */ + public ExportData( File xmlFile, String dsNamePrefix ) throws RrdException, IOException + { + this(); + + importXml( xmlFile, dsNamePrefix ); + } *************** *** 390,394 **** { Element root = Util.Xml.getRootElement( xmlFile ); ! importXml( root, useLegendNames ); } --- 419,423 ---- { Element root = Util.Xml.getRootElement( xmlFile ); ! importXml( root, useLegendNames, "d" ); } *************** *** 397,459 **** * The XML can be from either a JRobin or RRDtool export. * ! * The name of the datasources found will depend on the 'useLegendNames' flag. * * @param xportXml String containing the XML result of an export. ! * @param useLegendNames True if the names for the datasources should be set to ! * the legend values, false if they should be d1, d2, ... */ ! public void importXml( String xportXml, boolean useLegendNames ) throws RrdException, IOException { Element root = Util.Xml.getRootElement( xportXml ); ! importXml( root, useLegendNames ); } ! private void importXml( Element root, boolean useLegendNames ) throws RrdException, IOException { ! Node meta = Util.Xml.getFirstChildNode( root, "meta" ); ! Node[] dataRows = Util.Xml.getChildNodes( Util.Xml.getFirstChildNode( root, "data" ), "row" ); ! ! sourceByName.clear(); ! legends.clear(); ! ! // -- Parse the metadata ! int columns = Util.Xml.getChildValueAsInt( meta, "columns" ); ! long step = Util.Xml.getChildValueAsLong( meta, "step" ); ! String[] dsNames = new String[ columns ]; ! Node[] legendNodes = Util.Xml.getChildNodes( Util.Xml.getFirstChildNode( meta, "legend"), "entry" ); ! for ( int i = 0; i < legendNodes.length; i++ ) ! { ! String legend = Util.Xml.getValue( legendNodes[i] ); ! if ( useLegendNames ) ! dsNames[i] = legend; ! else ! dsNames[i] = "d" + (i + 1); ! ! legends.put( dsNames[i], legend ); ! } ! ! // -- Parse the data ! timestamps = new long[ dataRows.length ]; ! sources = new Source[ columns ]; ! arraySize = timestamps.length; ! ! for ( int i = 0; i < sources.length; i++ ) ! { ! sources[i] = new Def( dsNames[i], arraySize, arraySize ); ! sources[i].setFetchedStep( step ); ! } ! ! for ( int i = 0; i < dataRows.length; i++ ) ! { ! timestamps[i] = Util.Xml.getChildValueAsLong( dataRows[i], "t" ); ! Node[] data = Util.Xml.getChildNodes( dataRows[i], "v" ); ! ! for ( int j = 0; j < data.length; j++ ) ! sources[j].set( i, timestamps[i], Util.Xml.getValueAsDouble(data[j]) ); ! } ! // -- Set the datasource - name ! for ( int i = 0; i < sources.length; i++ ) ! sourceByName.put( sources[i].getName(), sources[i] ); } --- 426,471 ---- * The XML can be from either a JRobin or RRDtool export. * ! * The name of the datasources found will be the prefix passed as parameter, ! * followed by a number, making the name unique. * * @param xportXml String containing the XML result of an export. ! * @param dsNamePrefix Prefix of the datasource names. */ ! public void importXml( String xportXml, String dsNamePrefix ) throws RrdException, IOException { Element root = Util.Xml.getRootElement( xportXml ); ! importXml( root, false, dsNamePrefix ); } ! /** ! * Imports a export XML string and maps it back to this ExportData object. ! * The XML can be from either a JRobin or RRDtool export. ! * ! * The name of the datasources found will be the prefix passed as parameter, ! * followed by a number, making the name unique. ! * ! * @param xmlFile File containing export XML dump. ! * @param dsNamePrefix Prefix of the datasource names. ! */ ! public void importXml( File xmlFile, String dsNamePrefix ) throws RrdException, IOException { ! Element root = Util.Xml.getRootElement( xmlFile ); ! importXml( root, false, dsNamePrefix ); ! } ! /** ! * Imports a export XML string and maps it back to this ExportData object. ! * The XML can be from either a JRobin or RRDtool export. ! * ! * The name of the datasources found will depend on the 'useLegendNames' flag. ! * ! * @param xportXml String containing the XML result of an export. ! * @param useLegendNames True if the names for the datasources should be set to ! * the legend values, false if they should be d1, d2, ... ! */ ! public void importXml( String xportXml, boolean useLegendNames ) throws RrdException, IOException ! { ! Element root = Util.Xml.getRootElement( xportXml ); ! importXml( root, useLegendNames, "d" ); } *************** *** 553,555 **** --- 565,616 ---- return (Source) sourceByName.get(name); } + + private void importXml( Element root, boolean useLegendNames, String dsNamePrefix ) throws RrdException + { + Node meta = Util.Xml.getFirstChildNode( root, "meta" ); + Node[] dataRows = Util.Xml.getChildNodes( Util.Xml.getFirstChildNode( root, "data" ), "row" ); + + sourceByName.clear(); + legends.clear(); + + // -- Parse the metadata + int columns = Util.Xml.getChildValueAsInt( meta, "columns" ); + long step = Util.Xml.getChildValueAsLong( meta, "step" ); + String[] dsNames = new String[ columns ]; + Node[] legendNodes = Util.Xml.getChildNodes( Util.Xml.getFirstChildNode( meta, "legend"), "entry" ); + for ( int i = 0; i < legendNodes.length; i++ ) + { + String legend = Util.Xml.getValue( legendNodes[i] ); + if ( useLegendNames ) + dsNames[i] = legend; + else + dsNames[i] = dsNamePrefix + (i + 1); + + legends.put( dsNames[i], legend ); + } + + // -- Parse the data + timestamps = new long[ dataRows.length ]; + sources = new Source[ columns ]; + arraySize = timestamps.length; + + for ( int i = 0; i < sources.length; i++ ) + { + sources[i] = new Def( dsNames[i], arraySize, arraySize ); + sources[i].setFetchedStep( step ); + } + + for ( int i = 0; i < dataRows.length; i++ ) + { + timestamps[i] = Util.Xml.getChildValueAsLong( dataRows[i], "t" ); + Node[] data = Util.Xml.getChildNodes( dataRows[i], "v" ); + + for ( int j = 0; j < data.length; j++ ) + sources[j].set( i, timestamps[i], Util.Xml.getValueAsDouble(data[j]) ); + } + + // -- Set the datasource - name + for ( int i = 0; i < sources.length; i++ ) + sourceByName.put( sources[i].getName(), sources[i] ); + } } Index: RrdExportDefTemplate.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/graph/RrdExportDefTemplate.java,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** RrdExportDefTemplate.java 11 Jul 2004 22:04:14 -0000 1.1 --- RrdExportDefTemplate.java 13 Jul 2004 12:13:13 -0000 1.2 *************** *** 134,138 **** private void resolveDatasources(Node datasourceNode) throws RrdException { ! validateTagsOnlyOnce(datasourceNode, new String[] { "def*" }); Node[] nodes = getChildNodes(datasourceNode, "def"); for(int i = 0; i < nodes.length; i++) { --- 134,138 ---- private void resolveDatasources(Node datasourceNode) throws RrdException { ! validateTagsOnlyOnce(datasourceNode, new String[] { "def*", "export_data*" }); Node[] nodes = getChildNodes(datasourceNode, "def"); for(int i = 0; i < nodes.length; i++) { *************** *** 173,176 **** --- 173,202 ---- } } + + nodes = getChildNodes(datasourceNode, "export_data"); + for ( int i = 0; i < nodes.length; i++ ) + { + validateTagsOnlyOnce( nodes[i], new String[] {"file", "ds_name_prefix", "use_legend_names"} ); + String file = getChildValue( nodes[i], "file" ); + String prefix = "d"; + boolean use_legends = false; + + if ( Util.Xml.hasChildNode( nodes[i], "ds_name_prefix" ) ) + prefix = getChildValue(nodes[i], "ds_name_prefix"); + + if ( Util.Xml.hasChildNode( nodes[i], "use_legend_names" ) ) + use_legends = getChildValueAsBoolean(nodes[i], "use_legend_names"); + + try + { + if ( !prefix.equals("d") ) + def.addExportData( new ExportData( new File(file), prefix ) ); + else + def.addExportData( new ExportData( new File(file), use_legends ) ); + } + catch ( IOException ioe ) { + throw new RrdException( ioe ); + } + } } Index: RrdGraphDefTemplate.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/graph/RrdGraphDefTemplate.java,v retrieving revision 1.8 retrieving revision 1.9 diff -C2 -d -r1.8 -r1.9 *** RrdGraphDefTemplate.java 11 Jul 2004 22:04:14 -0000 1.8 --- RrdGraphDefTemplate.java 13 Jul 2004 12:13:13 -0000 1.9 *************** *** 487,491 **** private void resolveDatasources(Node datasourceNode) throws RrdException { ! validateTagsOnlyOnce(datasourceNode, new String[] { "def*" }); Node[] nodes = getChildNodes(datasourceNode, "def"); for(int i = 0; i < nodes.length; i++) { --- 487,491 ---- private void resolveDatasources(Node datasourceNode) throws RrdException { ! validateTagsOnlyOnce(datasourceNode, new String[] { "def*", "export_data*" }); Node[] nodes = getChildNodes(datasourceNode, "def"); for(int i = 0; i < nodes.length; i++) { *************** *** 526,529 **** --- 526,555 ---- } } + + nodes = getChildNodes(datasourceNode, "export_data"); + for ( int i = 0; i < nodes.length; i++ ) + { + validateTagsOnlyOnce( nodes[i], new String[] {"file", "ds_name_prefix", "use_legend_names"} ); + String file = getChildValue( nodes[i], "file" ); + String prefix = "d"; + boolean use_legends = false; + + if ( Util.Xml.hasChildNode( nodes[i], "ds_name_prefix" ) ) + prefix = getChildValue(nodes[i], "ds_name_prefix"); + + if ( Util.Xml.hasChildNode( nodes[i], "use_legend_names" ) ) + use_legends = getChildValueAsBoolean(nodes[i], "use_legend_names"); + + try + { + if ( !prefix.equals("d") ) + rrdGraphDef.addExportData( new ExportData( new File(file), prefix ) ); + else + rrdGraphDef.addExportData( new ExportData( new File(file), use_legends ) ); + } + catch ( IOException ioe ) { + throw new RrdException( ioe ); + } + } } *************** *** 537,541 **** "overlay", "show_legend", "show_signature", "time_axis", "time_axis_label", "title", "title_font", "title_font_color", "units_exponent", "value_axis", ! "vertical_label" }); Node[] optionNodes = getChildNodes(rootOptionNode); --- 563,567 ---- "overlay", "show_legend", "show_signature", "time_axis", "time_axis_label", "title", "title_font", "title_font_color", "units_exponent", "value_axis", ! "vertical_label", "strict_export", "resolution" }); Node[] optionNodes = getChildNodes(rootOptionNode); *************** *** 679,685 **** "maj_grid_unit_steps", "date_format", "center_labels", "first_day_of_week" }); ! if ( hasChildNode( optionNode, "min_grid_time_unit" ) ) ! { int unit1 = resolveUnit(getChildValue(optionNode, "min_grid_time_unit")); int step1 = getChildValueAsInt(optionNode, "min_grid_unit_steps"); --- 705,711 ---- "maj_grid_unit_steps", "date_format", "center_labels", "first_day_of_week" }); ! if ( hasChildNode( optionNode, "min_grid_time_unit" ) ) ! { int unit1 = resolveUnit(getChildValue(optionNode, "min_grid_time_unit")); int step1 = getChildValueAsInt(optionNode, "min_grid_unit_steps"); *************** *** 690,697 **** rrdGraphDef.setTimeAxis(unit1, step1, unit2, step2, format, center); } ! // Determine first day of the week if ( hasChildNode( optionNode, "first_day_of_week" ) ) ! { int dow = resolveDayUnit( getChildValue(optionNode, "first_day_of_week") ); rrdGraphDef.setFirstDayOfWeek( dow ); --- 716,723 ---- rrdGraphDef.setTimeAxis(unit1, step1, unit2, step2, format, center); } ! // Determine first day of the week if ( hasChildNode( optionNode, "first_day_of_week" ) ) ! { int dow = resolveDayUnit( getChildValue(optionNode, "first_day_of_week") ); rrdGraphDef.setFirstDayOfWeek( dow ); *************** *** 735,738 **** --- 761,772 ---- rrdGraphDef.setVerticalLabel(label); } + // STRICT EXPORT + else if(option.equals("strict_export")) { + rrdGraphDef.setStrictExport( getValueAsBoolean(optionNode) ); + } + // RESOLUTION + else if(option.equals("resolution")) { + rrdGraphDef.setResolution( getValueAsInt(optionNode) ); + } } } *************** *** 764,768 **** } } ! private int resolveDayUnit( String unit ) { if ( unit.equalsIgnoreCase("monday") ) { --- 798,802 ---- } } ! private int resolveDayUnit( String unit ) { if ( unit.equalsIgnoreCase("monday") ) { *************** *** 790,794 **** throw new IllegalArgumentException( "Invalid day unit specified: " + unit ); } ! } --- 824,828 ---- throw new IllegalArgumentException( "Invalid day unit specified: " + unit ); } ! } |
From: Sasa M. <sa...@us...> - 2004-07-13 11:45:48
|
Update of /cvsroot/jrobin/src/org/jrobin/core In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv21479/org/jrobin/core Modified Files: RrdNioBackend.java Log Message: rrdrestore command supported Index: RrdNioBackend.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/core/RrdNioBackend.java,v retrieving revision 1.9 retrieving revision 1.10 diff -C2 -d -r1.9 -r1.10 *** RrdNioBackend.java 12 Jul 2004 13:35:16 -0000 1.9 --- RrdNioBackend.java 13 Jul 2004 11:45:39 -0000 1.10 *************** *** 37,40 **** --- 37,52 ---- */ public class RrdNioBackend extends RrdFileBackend { + /** + * Defines if the <code>System.gc()</code> method should be executed when the backend is closed. + * NIO backend uses large in-memory buffer to cache file data. The buffer remains 'active' + * (by prohibiting file re-creation, for example) as long as it is not garbage collected. + * By forcing <code>gc()</code> after the file is closed memory gets freed sooner and file + * re-creation won't fail.<p> + * + * The constant is set to false initially and currently there is no API to change it + * during runtime.<p> + */ + public static final boolean SHOULD_GC_AFTER_CLOSE = false; + private static final Timer syncTimer = new Timer(true); *************** *** 104,112 **** */ public void close() throws IOException { if(syncTask != null) { syncTask.cancel(); } ! super.close(); // calls sync() byteBuffer = null; } --- 116,130 ---- */ public void close() throws IOException { + // cancel synchronization if(syncTask != null) { syncTask.cancel(); } ! super.close(); // calls sync() eventually ! // release the buffer, make it eligible for GC as soon as possible byteBuffer = null; + if(SHOULD_GC_AFTER_CLOSE) { + // I am not happy with this, but it might be necessary in the future + System.gc(); + } } |
From: Sasa M. <sa...@us...> - 2004-07-13 11:45:47
|
Update of /cvsroot/jrobin/src/org/jrobin/cmd In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv21479/org/jrobin/cmd Modified Files: RrdCommander.java Added Files: RrdRestoreCmd.java Log Message: rrdrestore command supported Index: RrdCommander.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/cmd/RrdCommander.java,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** RrdCommander.java 12 Jul 2004 13:54:03 -0000 1.2 --- RrdCommander.java 13 Jul 2004 11:45:39 -0000 1.3 *************** *** 96,99 **** --- 96,101 ---- *<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 *************** *** 108,112 **** new RrdUpdateCommand(cmdScanner), new RrdDumpCmd(cmdScanner), ! new RrdFetchCmd(cmdScanner) }; for(int i = 0; i < commanders.length; i++) { --- 110,115 ---- new RrdUpdateCommand(cmdScanner), new RrdDumpCmd(cmdScanner), ! new RrdFetchCmd(cmdScanner), ! new RrdRestoreCmd(cmdScanner) }; for(int i = 0; i < commanders.length; i++) { --- NEW FILE: RrdRestoreCmd.java --- 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 { public RrdRestoreCmd(RrdCmdScanner cmdScanner) { super(cmdScanner); } String getCmdType() { return "restore"; } Object execute() throws RrdException, IOException { boolean check = cmdScanner.getBooleanOption("r", "range-check"); String[] words = cmdScanner.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); } } } |
From: Sasa M. <sa...@us...> - 2004-07-13 10:40:43
|
Update of /cvsroot/jrobin/src/org/jrobin/inspector In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv11427/org/jrobin/inspector Modified Files: RrdInspector.java Log Message: Resolved problem with multiple main frames on startup Index: RrdInspector.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/inspector/RrdInspector.java,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** RrdInspector.java 24 May 2004 15:02:29 -0000 1.5 --- RrdInspector.java 13 Jul 2004 10:40:34 -0000 1.6 *************** *** 59,67 **** private String lastDirectory = null; ! RrdInspector() { super(TITLE); constructUI(); showCentered(); ! //selectFile(); } --- 59,72 ---- private String lastDirectory = null; ! private RrdInspector(String path) { super(TITLE); constructUI(); showCentered(); ! if(path == null) { ! selectFile(); ! } ! else { ! loadFile(new File(path)); ! } } *************** *** 443,447 **** } ! private static void printUsage() { System.err.println("usage: " + RrdInspector.class.getName() + " [<filename>]"); System.exit(1); --- 448,452 ---- } ! private static void printUsageAndExit() { System.err.println("usage: " + RrdInspector.class.getName() + " [<filename>]"); System.exit(1); *************** *** 449,465 **** public static void main(String[] args) { - new RrdInspector(); - File file = null; if (args.length > 1) { ! printUsage(); ! } else if (args.length == 1) { ! file = new File(args[0]); ! } ! RrdInspector inspector = new RrdInspector(); ! if (file == null) { ! inspector.selectFile(); ! } else { ! inspector.loadFile(file); } } } --- 454,462 ---- public static void main(String[] args) { if (args.length > 1) { ! printUsageAndExit(); } + String path = (args.length == 1)? args[0]: null; + new RrdInspector(path); } } |
From: Sasa M. <sa...@us...> - 2004-07-13 09:39:20
|
Update of /cvsroot/jrobin/src/org/jrobin/core In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv2452/org/jrobin/core Modified Files: RrdToolkit.java Log Message: Resolved problem with .bak files removal Index: RrdToolkit.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/core/RrdToolkit.java,v retrieving revision 1.9 retrieving revision 1.10 diff -C2 -d -r1.9 -r1.10 *** RrdToolkit.java 20 May 2004 10:29:33 -0000 1.9 --- RrdToolkit.java 13 Jul 2004 09:39:09 -0000 1.10 *************** *** 256,260 **** File dest = new File(destPath); if (saveBackup) { ! String backupPath = destPath + ".bak"; File backup = new File(backupPath); deleteFile(backup); --- 256,260 ---- File dest = new File(destPath); if (saveBackup) { ! String backupPath = getBackupPath(destPath); File backup = new File(backupPath); deleteFile(backup); *************** *** 269,272 **** --- 269,280 ---- } + private static String getBackupPath(String destPath) { + String backupPath = destPath; + do { + backupPath += ".bak"; + } while(new File(backupPath).exists()); + return backupPath; + } + /** * Sets datasource heartbeat to a new value. |
From: Sasa M. <sa...@us...> - 2004-07-12 14:01:49
|
Update of /cvsroot/jrobin/ant In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv22049 Modified Files: build.xml Log Message: modifed to ignore org.jrobin.cmd.* classes (for some time) Index: build.xml =================================================================== RCS file: /cvsroot/jrobin/ant/build.xml,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** build.xml 9 Jun 2004 12:14:28 -0000 1.2 --- build.xml 12 Jul 2004 14:01:41 -0000 1.3 *************** *** 181,185 **** </tarfileset> <tarfileset dir="${cwd}/${src}" prefix="${prefix}/${src}"> ! <exclude name="**/test/**/*"/> <include name="**/*.java"/> </tarfileset> --- 181,186 ---- </tarfileset> <tarfileset dir="${cwd}/${src}" prefix="${prefix}/${src}"> ! <exclude name="**/dev/**/*"/> ! <exclude name="**/cmd/**/*"/> <include name="**/*.java"/> </tarfileset> |
From: Sasa M. <sa...@us...> - 2004-07-12 13:54:12
|
Update of /cvsroot/jrobin/src/org/jrobin/cmd In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv20571/org/jrobin/cmd Modified Files: RrdCommander.java Log Message: minor changes in main() Index: RrdCommander.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/cmd/RrdCommander.java,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** RrdCommander.java 12 Jul 2004 13:35:16 -0000 1.1 --- RrdCommander.java 12 Jul 2004 13:54:03 -0000 1.2 *************** *** 120,131 **** public static void main(String[] args) { BufferedReader r = new BufferedReader(new InputStreamReader(System.in)); while (true) { try { String s = r.readLine(); ! if(s.equals(".")) { System.exit(0); } ! System.out.println(execute(s)); } catch (IOException e) { System.err.println(e); --- 120,137 ---- public static void main(String[] args) { + 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("================================"); BufferedReader r = new BufferedReader(new InputStreamReader(System.in)); while (true) { try { + System.out.print("$ "); String s = r.readLine(); ! if(s.startsWith(".")) { System.exit(0); } ! execute(s); } catch (IOException e) { System.err.println(e); |
From: Sasa M. <sa...@us...> - 2004-07-12 13:37:58
|
Update of /cvsroot/jrobin/src/org/jrobin/cmd In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv17813/org/jrobin/cmd Modified Files: RrdFetchCmd.java Log Message: add file header to RrdFetchCmd Index: RrdFetchCmd.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/cmd/RrdFetchCmd.java,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** RrdFetchCmd.java 12 Jul 2004 13:35:17 -0000 1.1 --- RrdFetchCmd.java 12 Jul 2004 13:37:50 -0000 1.2 *************** *** 1,2 **** --- 1,27 ---- + /* ============================================================ + * JRobin : Pure java implementation of RRDTool's functionality + * ============================================================ + * + * Project Info: http://www.jrobin.org + * Project Lead: Sasa Markovic (sa...@jr...); + * + * (C) Copyright 2003, by Sasa Markovic. + * + * 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; |
From: Sasa M. <sa...@us...> - 2004-07-12 13:35:26
|
Update of /cvsroot/jrobin/src/org/jrobin/cmd In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv17030/org/jrobin/cmd Added Files: RrdCmdScanner.java RrdCommander.java RrdCreateCmd.java RrdDumpCmd.java RrdFetchCmd.java RrdLastCmd.java RrdToolCmd.java RrdUpdateCommand.java TimeParser.java TimeScanner.java TimeSpec.java TimeToken.java Log Message: RRDTool like command parser added. So far, supported RRDTool commands are: - create - dump - update - fetch - last Also, some minor improvements to core FILE and NIO backends. --- NEW FILE: TimeSpec.java --- /* ============================================================ * JRobin : Pure java implementation of RRDTool's functionality * ============================================================ * * Project Info: http://www.jrobin.org * Project Lead: Sasa Markovic (sa...@jr...); * * (C) Copyright 2003, by Sasa Markovic. * * Developers: Sasa Markovic (sa...@jr...) * Arne Vandamme (cob...@jr...) * * This library is free software; you can redistribute it and/or modify it under the terms * of the GNU Lesser General Public License as published by the Free Software Foundation; * either version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with this * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, * Boston, MA 02111-1307, USA. */ package org.jrobin.cmd; import org.jrobin.core.RrdException; import org.jrobin.core.Util; import java.util.GregorianCalendar; import java.util.Date; import java.util.Calendar; class TimeSpec { public static final int TYPE_ABSOLUTE = 0; public static final int TYPE_START = 1; public 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; public 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; } 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 + ")"; } 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() }; } 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]) }; } } --- NEW FILE: RrdFetchCmd.java --- 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 java.io.IOException; class RrdFetchCmd extends RrdToolCmd { static final String DEFAULT_START = "end-1day"; static final String DEFAULT_END = "now"; public RrdFetchCmd(RrdCmdScanner cmdScanner) { super(cmdScanner); } String getCmdType() { return "fetch"; } Object execute() throws RrdException, IOException { // --start String startStr = cmdScanner.getOptionValue("s", "start", DEFAULT_START); TimeSpec spec1 = new TimeParser(startStr).parse(); // --end String endStr = cmdScanner.getOptionValue("e", "end", DEFAULT_END); TimeSpec spec2 = new TimeParser(endStr).parse(); long[] timestamps = TimeSpec.getTimestamps(spec1, spec2); // --resolution String resolutionStr = cmdScanner.getOptionValue("r", "resolution"); long resolution = 1; if(resolutionStr != null) { resolution = parseLong(resolutionStr); } // other words String[] tokens = cmdScanner.getRemainingWords(); if(tokens.length != 3) { throw new RrdException("Invalid rrdfetch syntax"); } String path = tokens[1]; String consolFun = tokens[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); } } } --- NEW FILE: RrdCreateCmd.java --- /* ============================================================ * JRobin : Pure java implementation of RRDTool's functionality * ============================================================ * * Project Info: http://www.jrobin.org * Project Lead: Sasa Markovic (sa...@jr...); * * (C) Copyright 2003, by Sasa Markovic. * * Developers: Sasa Markovic (sa...@jr...) * Arne Vandamme (cob...@jr...) * * This library is free software; you can redistribute it and/or modify it under the terms * of the GNU Lesser General Public License as published by the Free Software Foundation; * either version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with this * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, * Boston, MA 02111-1307, USA. */ package org.jrobin.cmd; import org.jrobin.core.RrdException; import org.jrobin.core.RrdDef; import org.jrobin.core.RrdDb; import java.io.IOException; class RrdCreateCmd extends RrdToolCmd { static final String DEFAULT_START = "now-10s"; static final String DEFAULT_STEP = "300"; private RrdDef rrdDef; public RrdCreateCmd(RrdCmdScanner cmdScanner) { super(cmdScanner); } String getCmdType() { return "create"; } Object execute() throws RrdException, IOException { String startStr = cmdScanner.getOptionValue("b", "start", DEFAULT_START); TimeSpec spec = new TimeParser(startStr).parse(); long start = spec.getTimestamp(); String stepStr = cmdScanner.getOptionValue("s", "step", DEFAULT_STEP); long step = parseLong(stepStr); String[] words = cmdScanner.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 word in the 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(); } } --- NEW FILE: RrdCommander.java --- /* ============================================================ * JRobin : Pure java implementation of RRDTool's functionality * ============================================================ * * Project Info: http://www.jrobin.org * Project Lead: Sasa Markovic (sa...@jr...); * * (C) Copyright 2003, by Sasa Markovic. * * Developers: Sasa Markovic (sa...@jr...) * Arne Vandamme (cob...@jr...) * * This library is free software; you can redistribute it and/or modify it under the terms * of the GNU Lesser General Public License as published by the Free Software Foundation; * either version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with this * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, * Boston, MA 02111-1307, USA. */ package org.jrobin.cmd; import org.jrobin.core.RrdException; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; /** * Class to be used to execute various RRDTool commands (original syntax of RRDTool must be used). */ public class RrdCommander { /** * 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. * </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 { RrdCmdScanner cmdScanner = new RrdCmdScanner(command); RrdToolCmd[] commanders = { new RrdCreateCmd(cmdScanner), new RrdLastCmd(cmdScanner), new RrdUpdateCommand(cmdScanner), new RrdDumpCmd(cmdScanner), new RrdFetchCmd(cmdScanner) }; for(int i = 0; i < commanders.length; i++) { Object result = commanders[i].go(); if(result != null) { return result; } } throw new RrdException("Unknown RRDTool command: " + command); } public static void main(String[] args) { BufferedReader r = new BufferedReader(new InputStreamReader(System.in)); while (true) { try { String s = r.readLine(); if(s.equals(".")) { System.exit(0); } System.out.println(execute(s)); } catch (IOException e) { System.err.println(e); } catch (RrdException e) { System.err.println(e); } } } } --- NEW FILE: TimeToken.java --- /* ============================================================ * JRobin : Pure java implementation of RRDTool's functionality * ============================================================ * * Project Info: http://www.jrobin.org * Project Lead: Sasa Markovic (sa...@jr...); * * (C) Copyright 2003, by Sasa Markovic. * * Developers: Sasa Markovic (sa...@jr...) * Arne Vandamme (cob...@jr...) * * This library is free software; you can redistribute it and/or modify it under the terms * of the GNU Lesser General Public License as published by the Free Software Foundation; * either version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with this * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, * Boston, MA 02111-1307, USA. */ package org.jrobin.cmd; 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 + "]"; } } --- NEW FILE: RrdDumpCmd.java --- /* ============================================================ * JRobin : Pure java implementation of RRDTool's functionality * ============================================================ * * Project Info: http://www.jrobin.org * Project Lead: Sasa Markovic (sa...@jr...); * * (C) Copyright 2003, by Sasa Markovic. * * Developers: Sasa Markovic (sa...@jr...) * Arne Vandamme (cob...@jr...) * * This library is free software; you can redistribute it and/or modify it under the terms * of the GNU Lesser General Public License as published by the Free Software Foundation; * either version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with this * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, * Boston, MA 02111-1307, USA. */ package org.jrobin.cmd; import org.jrobin.core.RrdException; import org.jrobin.core.RrdDb; import java.io.IOException; class RrdDumpCmd extends RrdToolCmd { RrdDumpCmd(RrdCmdScanner cmdScanner) { super(cmdScanner); } String getCmdType() { return "dump"; } Object execute() throws RrdException, IOException { String[] words = cmdScanner.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); } } } --- NEW FILE: RrdLastCmd.java --- /* ============================================================ * JRobin : Pure java implementation of RRDTool's functionality * ============================================================ * * Project Info: http://www.jrobin.org * Project Lead: Sasa Markovic (sa...@jr...); * * (C) Copyright 2003, by Sasa Markovic. * * Developers: Sasa Markovic (sa...@jr...) * Arne Vandamme (cob...@jr...) * * This library is free software; you can redistribute it and/or modify it under the terms * of the GNU Lesser General Public License as published by the Free Software Foundation; * either version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with this * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, * Boston, MA 02111-1307, USA. */ package org.jrobin.cmd; import org.jrobin.core.RrdException; import org.jrobin.core.RrdDb; import java.io.IOException; class RrdLastCmd extends RrdToolCmd { RrdLastCmd(RrdCmdScanner cmdScanner) { super(cmdScanner); } String getCmdType() { return "last"; } Object execute() throws RrdException, IOException { String[] words = cmdScanner.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); } } } --- NEW FILE: RrdToolCmd.java --- /* ============================================================ * JRobin : Pure java implementation of RRDTool's functionality * ============================================================ * * Project Info: http://www.jrobin.org * Project Lead: Sasa Markovic (sa...@jr...); * * (C) Copyright 2003, by Sasa Markovic. * * Developers: Sasa Markovic (sa...@jr...) * Arne Vandamme (cob...@jr...) * * This library is free software; you can redistribute it and/or modify it under the terms * of the GNU Lesser General Public License as published by the Free Software Foundation; * either version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with this * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, * Boston, MA 02111-1307, USA. */ package org.jrobin.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 { 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; } RrdCmdScanner cmdScanner; RrdToolCmd(RrdCmdScanner cmdScanner) { this.cmdScanner = cmdScanner; } abstract String getCmdType(); Object go() throws IOException, RrdException { if(!getCmdType().equals(cmdScanner.getCmdType())) { return null; } return execute(); } abstract Object execute() throws RrdException, IOException; 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(); } } } --- NEW FILE: TimeScanner.java --- /* ============================================================ * JRobin : Pure java implementation of RRDTool's functionality * ============================================================ * * Project Info: http://www.jrobin.org * Project Lead: Sasa Markovic (sa...@jr...); * * (C) Copyright 2003, by Sasa Markovic. * * Developers: Sasa Markovic (sa...@jr...) * Arne Vandamme (cob...@jr...) * * This library is free software; you can redistribute it and/or modify it under the terms * of the GNU Lesser General Public License as published by the Free Software Foundation; * either version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with this * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, * Boston, MA 02111-1307, USA. */ package org.jrobin.cmd; 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("sun", TimeToken.SUN), new TimeToken("monday", TimeToken.MON), new TimeToken("mon", TimeToken.MON), new TimeToken("tuesday", TimeToken.TUE), new TimeToken("tue", TimeToken.TUE), new TimeToken("wednesday", TimeToken.WED), new TimeToken("wed", TimeToken.WED), new TimeToken("thursday", TimeToken.THU), new TimeToken("thu", TimeToken.THU), new TimeToken("friday", TimeToken.FRI), new TimeToken("fri", TimeToken.FRI), new TimeToken("saturday", TimeToken.SAT), new TimeToken("sat", TimeToken.SAT), new TimeToken(null, 0) /*** SENTINEL ***/ }; static TimeToken[] MULTIPLIERS = { new TimeToken("second", TimeToken.SECONDS), /* seconds multiplier */ new TimeToken("seconds", TimeToken.SECONDS), /* (pluralized) */ new TimeToken("sec", TimeToken.SECONDS), /* (generic) */ new TimeToken("s", TimeToken.SECONDS), /* (short generic) */ new TimeToken("minute", TimeToken.MINUTES), /* minutes multiplier */ new TimeToken("minutes", TimeToken.MINUTES), /* (pluralized) */ new TimeToken("min", TimeToken.MINUTES), /* (generic) */ new TimeToken("m", TimeToken.MONTHS_MINUTES), /* (short generic) */ new TimeToken("hour", TimeToken.HOURS), /* hours ... */ new TimeToken("hours", TimeToken.HOURS), /* (pluralized) */ new TimeToken("hr", TimeToken.HOURS), /* (generic) */ new TimeToken("h", TimeToken.HOURS), /* (short generic) */ new TimeToken("day", TimeToken.DAYS), /* days ... */ new TimeToken("days", TimeToken.DAYS), /* (pluralized) */ new TimeToken("d", TimeToken.DAYS), /* (short generic) */ new TimeToken("week", TimeToken.WEEKS), /* week ... */ new TimeToken("weeks", TimeToken.WEEKS), /* (pluralized) */ new TimeToken("wk", TimeToken.WEEKS), /* (generic) */ new TimeToken("w", TimeToken.WEEKS), /* (short generic) */ new TimeToken("month", TimeToken.MONTHS), /* week ... */ new TimeToken("months", TimeToken.MONTHS), /* (pluralized) */ new TimeToken("mon", TimeToken.MONTHS), /* (generic) */ new TimeToken("year", TimeToken.YEARS), /* year ... */ new TimeToken("years", TimeToken.YEARS), /* (pluralized) */ new TimeToken("yr", TimeToken.YEARS), /* (generic) */ new TimeToken("y", TimeToken.YEARS), /* (short generic) */ new TimeToken(null, 0) /*** SENTINEL ***/ }; TimeToken[] specials = WORDS; public TimeScanner(String dateString) { this.dateString = dateString; } void setContext(boolean parsingWords) { specials = parsingWords? WORDS: MULTIPLIERS; } TimeToken nextToken() { StringBuffer buffer = new StringBuffer(""); while (pos < dateString.length()) { char c = dateString.charAt(pos++); if (Character.isWhitespace(c) || c == '_' || c == ',') { continue; } buffer.append(c); if (Character.isDigit(c)) { // pick as many digits as possible while (pos < dateString.length()) { char next = dateString.charAt(pos); if (Character.isDigit(next)) { buffer.append(next); pos++; } else { break; } } String value = buffer.toString(); return token = new TimeToken(value, TimeToken.NUMBER); } if (Character.isLetter(c)) { // pick as many letters as possible while (pos < dateString.length()) { char next = dateString.charAt(pos); if (Character.isLetter(next)) { buffer.append(next); pos++; } else { break; } } String value = buffer.toString(); return token = new TimeToken(value, parseToken(value)); } switch (c) { case ':': return token = new TimeToken(":", TimeToken.COLON); case '.': return token = new TimeToken(".", TimeToken.DOT); case '+': return token = new TimeToken("+", TimeToken.PLUS); case '-': return token = new TimeToken("-", TimeToken.MINUS); case '/': return token = new TimeToken("/", TimeToken.SLASH); default: pos--; return token = new TimeToken(null, TimeToken.EOF); } } return token = new TimeToken(null, TimeToken.EOF); } TimeToken resolveMonthsMinutes(int newId) { assert token.id == TimeToken.MONTHS_MINUTES; assert newId == TimeToken.MONTHS || newId == TimeToken.MINUTES; return token = new TimeToken(token.value, newId); } void saveState() { token_save = token; pos_save = pos; } TimeToken restoreState() { pos = pos_save; return token = token_save; } private int parseToken(String arg) { for (int i = 0; specials[i].value != null; i++) { if (specials[i].value.equalsIgnoreCase(arg)) { return specials[i].id; } } return TimeToken.ID; } } --- NEW FILE: TimeParser.java --- /* ============================================================ * JRobin : Pure java implementation of RRDTool's functionality * ============================================================ * * Project Info: http://www.jrobin.org * Project Lead: Sasa Markovic (sa...@jr...); * * (C) Copyright 2003, by Sasa Markovic. * * Developers: Sasa Markovic (sa...@jr...) * Arne Vandamme (cob...@jr...) * * This library is free software; you can redistribute it and/or modify it under the terms * of the GNU Lesser General Public License as published by the Free Software Foundation; * either version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with this * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, * Boston, MA 02111-1307, USA. */ /* * Java port of Tobi's original parsetime.c routine */ package org.jrobin.cmd; import org.jrobin.core.RrdException; import org.jrobin.core.Util; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; class TimeParser { public static final int PREVIOUS_OP = -1; TimeToken token; TimeScanner scanner; TimeSpec spec; int op = TimeToken.PLUS; int prev_multiplier = -1; 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; } } 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); } } } } --- NEW FILE: RrdCmdScanner.java --- /* ============================================================ * JRobin : Pure java implementation of RRDTool's functionality * ============================================================ * * Project Info: http://www.jrobin.org * Project Lead: Sasa Markovic (sa...@jr...); * * (C) Copyright 2003, by Sasa Markovic. * * Developers: Sasa Markovic (sa...@jr...) * Arne Vandamme (cob...@jr...) * * This library is free software; you can redistribute it and/or modify it under the terms * of the GNU Lesser General Public License as published by the Free Software Foundation; * either version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with this * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, * Boston, MA 02111-1307, USA. */ package org.jrobin.cmd; import org.jrobin.core.RrdException; import java.util.LinkedList; import java.util.regex.Pattern; import java.util.regex.Matcher; class RrdCmdScanner { private static final Pattern PATTERN = Pattern.compile("([^\"\\s]*\"[^\"]*\")|([^\"\\s]+)"); private LinkedList words = new LinkedList(); private String cmdType; RrdCmdScanner(String[] cmdWords) { for(int i = 0; i < cmdWords.length; i++) { words.add(cmdWords[i]); if(words.size() == 1) { cmdType = cmdWords[i]; } } } RrdCmdScanner(String command) { parseWords(command); } private void parseWords(String command) { Matcher m = PATTERN.matcher(command); while(m.find()) { String word = m.group(); word = word.replaceAll("\"", ""); // System.out.println("Adding: [" + word + "]"); words.add(word); if(words.size() == 1) { cmdType = word; } } } String getCmdType() { return cmdType; } String getOptionValue(String shortForm, String longForm) throws RrdException { for(int i = 0; i < words.size(); i++) { String word = (String) words.get(i); if((shortForm != null && word.equals("-" + shortForm)) || (longForm != null && word.equals("--" + longForm))) { // match found if(i < words.size() - 1) { // value available String value = (String) words.get(i + 1); words.remove(i + 1); words.remove(i); return value; } else { throw new RrdException("Option found but value is not available"); } } } return null; } String getOptionValue(String shortForm, String longForm, String defaultValue) throws RrdException { String value = getOptionValue(shortForm, longForm); return value != null? value: defaultValue; } boolean getBooleanOption(String shortForm, String longForm) throws RrdException { for(int i = 0; i < words.size(); i++) { String word = (String) words.get(i); if((shortForm != null && word.equals("-" + shortForm)) || (longForm != null && word.equals("--" + longForm))) { // match found words.remove(i); return true; } } return false; } String[] getRemainingWords() { return (String[]) words.toArray(new String[0]); } } --- NEW FILE: RrdUpdateCommand.java --- /* ============================================================ * JRobin : Pure java implementation of RRDTool's functionality * ============================================================ * * Project Info: http://www.jrobin.org * Project Lead: Sasa Markovic (sa...@jr...); * * (C) Copyright 2003, by Sasa Markovic. * * Developers: Sasa Markovic (sa...@jr...) * Arne Vandamme (cob...@jr...) * * This library is free software; you can redistribute it and/or modify it under the terms * of the GNU Lesser General Public License as published by the Free Software Foundation; * either version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with this * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, * Boston, MA 02111-1307, USA. */ package org.jrobin.cmd; import org.jrobin.core.*; import java.io.IOException; class RrdUpdateCommand extends RrdToolCmd { private String[] dsNames; RrdUpdateCommand(RrdCmdScanner cmdScanner) { super(cmdScanner); } String getCmdType() { return "update"; } Object execute() throws RrdException, IOException { String template = cmdScanner.getOptionValue("t", "template"); if (template != null) { dsNames = template.split(":"); } String[] words = cmdScanner.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); } } } |
From: Sasa M. <sa...@us...> - 2004-07-12 13:35:25
|
Update of /cvsroot/jrobin/src/org/jrobin/core In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv17030/org/jrobin/core Modified Files: FetchData.java RrdFileBackend.java RrdNioBackend.java Util.java Log Message: RRDTool like command parser added. So far, supported RRDTool commands are: - create - dump - update - fetch - last Also, some minor improvements to core FILE and NIO backends. Index: FetchData.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/core/FetchData.java,v retrieving revision 1.7 retrieving revision 1.8 diff -C2 -d -r1.7 -r1.8 *** FetchData.java 10 Jul 2004 00:06:29 -0000 1.7 --- FetchData.java 12 Jul 2004 13:35:16 -0000 1.8 *************** *** 30,33 **** --- 30,34 ---- import java.io.FileOutputStream; import java.io.ByteArrayOutputStream; + import java.text.DecimalFormat; /** *************** *** 235,238 **** --- 236,276 ---- /** + * Returns string representing fetched data in a RRDTool-like form. + * @return Fetched data as a string in a rrdfetch-like output form. + */ + public String toString() { + final DecimalFormat df = new DecimalFormat("+0.0000000000E00"); + // print header row + StringBuffer buff = new StringBuffer(); + buff.append(padWithBlanks("", 10)); + buff.append(" "); + for(int i = 0; i < dsNames.length; i++) { + buff.append(padWithBlanks(dsNames[i], 18)); + } + buff.append("\n \n"); + for(int i = 0; i < timestamps.length; i++) { + buff.append(padWithBlanks("" + timestamps[i], 10)); + buff.append(":"); + for(int j = 0; j < dsNames.length; j++) { + double value = values[j][i]; + String valueStr = Double.isNaN(value)? "nan": df.format(value); + buff.append(padWithBlanks(valueStr, 18)); + } + buff.append("\n"); + } + return buff.toString(); + } + + private static String padWithBlanks(String input, int width) { + StringBuffer buff = new StringBuffer(""); + int diff = width - input.length(); + while(diff-- > 0) { + buff.append(' '); + } + buff.append(input); + return buff.toString(); + } + + /** * Returns aggregated value from the fetched data for a single datasource. * @param dsName Datasource name Index: RrdNioBackend.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/core/RrdNioBackend.java,v retrieving revision 1.8 retrieving revision 1.9 diff -C2 -d -r1.8 -r1.9 *** RrdNioBackend.java 29 Jun 2004 09:02:22 -0000 1.8 --- RrdNioBackend.java 12 Jul 2004 13:35:16 -0000 1.9 *************** *** 49,53 **** FileChannel.MapMode mapMode = readOnly? FileChannel.MapMode.READ_ONLY: FileChannel.MapMode.READ_WRITE; ! this.byteBuffer = file.getChannel().map(mapMode, 0, getLength()); if(syncMode == RrdNioBackendFactory.SYNC_BACKGROUND && !readOnly) { createSyncTask(syncPeriod); --- 49,53 ---- FileChannel.MapMode mapMode = readOnly? FileChannel.MapMode.READ_ONLY: FileChannel.MapMode.READ_WRITE; ! this.byteBuffer = channel.map(mapMode, 0, getLength()); if(syncMode == RrdNioBackendFactory.SYNC_BACKGROUND && !readOnly) { createSyncTask(syncPeriod); *************** *** 108,111 **** --- 108,112 ---- } super.close(); // calls sync() + byteBuffer = null; } Index: Util.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/core/Util.java,v retrieving revision 1.17 retrieving revision 1.18 diff -C2 -d -r1.17 -r1.18 *** Util.java 9 Jul 2004 12:20:11 -0000 1.17 --- Util.java 12 Jul 2004 13:35:16 -0000 1.18 *************** *** 67,71 **** /** * Returns current timestamp in seconds (without milliseconds). Returned timestamp ! * is obtained with the following expression: * * <code>(System.currentTimeMillis() + 500L) / 1000L</code> --- 67,71 ---- /** * Returns current timestamp in seconds (without milliseconds). Returned timestamp ! * is obtained with the following expression: <p> * * <code>(System.currentTimeMillis() + 500L) / 1000L</code> *************** *** 76,79 **** --- 76,95 ---- } + /** + * Just an alias for {@link #getTime()} method. + * @return Current timestamp (without milliseconds) + */ + public static long getTimestamp() { + return getTime(); + } + + /** + * Rounds the given timestamp to the nearest whole "step" by evaluating + * the following expression:<p> + * <code>timestamp - timestamp % step;</code> + * @param timestamp Timestamp in seconds + * @param step Step in seconds + * @return "Rounded" timestamp + */ public static long normalize(long timestamp, long step) { return timestamp - timestamp % step; Index: RrdFileBackend.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/core/RrdFileBackend.java,v retrieving revision 1.6 retrieving revision 1.7 diff -C2 -d -r1.6 -r1.7 *** RrdFileBackend.java 29 Jun 2004 12:20:55 -0000 1.6 --- RrdFileBackend.java 12 Jul 2004 13:35:16 -0000 1.7 *************** *** 45,60 **** protected RandomAccessFile file; protected FileLock fileLock; protected RrdFileBackend(String path, boolean readOnly, int lockMode) throws IOException { super(path); - if(!readOnly) { - registerWriter(path); - } file = new RandomAccessFile(path, readOnly? "r": "rw"); ! // We'll try to lock the file only in "rw" mode ! // locks are meaningless for read-only access if(!readOnly) { lockFile(lockMode); } } --- 45,59 ---- protected RandomAccessFile file; + protected FileChannel channel; protected FileLock fileLock; protected RrdFileBackend(String path, boolean readOnly, int lockMode) throws IOException { super(path); file = new RandomAccessFile(path, readOnly? "r": "rw"); ! channel = file.getChannel(); if(!readOnly) { lockFile(lockMode); + // We'll try to lock the file only in "rw" mode + registerWriter(path); } } *************** *** 73,79 **** private void lockFile(int lockMode) throws IOException { if(lockMode == RrdDb.WAIT_IF_LOCKED || lockMode == RrdDb.EXCEPTION_IF_LOCKED) { - FileChannel fileChannel = file.getChannel(); do { ! fileLock = fileChannel.tryLock(); if(fileLock == null) { // could not obtain lock --- 72,77 ---- private void lockFile(int lockMode) throws IOException { if(lockMode == RrdDb.WAIT_IF_LOCKED || lockMode == RrdDb.EXCEPTION_IF_LOCKED) { do { ! fileLock = channel.tryLock(); if(fileLock == null) { // could not obtain lock *************** *** 101,107 **** public void close() throws IOException { super.close(); // calls sync() unlockFile(); file.close(); - unregisterWriter(getPath()); } --- 99,106 ---- public void close() throws IOException { super.close(); // calls sync() + unregisterWriter(getPath()); unlockFile(); + channel.close(); file.close(); } |
From: Sasa M. <sa...@us...> - 2004-07-12 13:32:41
|
Update of /cvsroot/jrobin/src/org/jrobin/cmd In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv16604/cmd Log Message: Directory /cvsroot/jrobin/src/org/jrobin/cmd added to the repository |
From: Arne V. <cob...@us...> - 2004-07-11 22:45:07
|
Update of /cvsroot/jrobin/src/org/jrobin/demo/graph In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv14605/org/jrobin/demo/graph Modified Files: GraphTemplate.java Added Files: ExportTemplate.java Log Message: JRobin 1.4.0 - Added ExportTemplate demo application Index: GraphTemplate.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/demo/graph/GraphTemplate.java,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** GraphTemplate.java 11 Jul 2004 22:06:45 -0000 1.1 --- GraphTemplate.java 11 Jul 2004 22:44:59 -0000 1.2 *************** *** 36,40 **** /** * <p>Simple command line application that allows you to generate a graph ! * from a RrdGraphDefTemplate. Pretty straightforward use.</p> * * @author Arne Vandamme (cob...@jr...) --- 36,40 ---- /** * <p>Simple command line application that allows you to generate a graph ! * from a RrdGraphDefTemplate. Pretty straightforward in use.</p> * * @author Arne Vandamme (cob...@jr...) *************** *** 112,115 **** --- 112,116 ---- RrdGraphDefTemplate template = new RrdGraphDefTemplate( new File(templateFile) ); + // -- Set the parameters (if there are any) System.out.println( ">>> Setting template variables" ); if ( template.hasVariables() ) *************** *** 126,129 **** --- 127,131 ---- long start = System.currentTimeMillis(); + // -- Generate the actual graph RrdGraph graph = new RrdGraph( template.getRrdGraphDef() ); --- NEW FILE: ExportTemplate.java --- /* ============================================================ * JRobin : Pure java implementation of RRDTool's functionality * ============================================================ * * Project Info: http://www.jrobin.org * Project Lead: Sasa Markovic (sa...@jr...); * * (C) Copyright 2003, by Sasa Markovic. * * Developers: Sasa Markovic (sa...@jr...) * Arne Vandamme (cob...@jr...) * * This library is free software; you can redistribute it and/or modify it under the terms * of the GNU Lesser General Public License as published by the Free Software Foundation; * either version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with this * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, * Boston, MA 02111-1307, USA. */ package org.jrobin.demo.graph; import org.jrobin.graph.RrdExport; import org.jrobin.graph.RrdExportDefTemplate; import org.jrobin.graph.ExportData; import org.jrobin.core.RrdException; import java.io.BufferedReader; import java.io.IOException; import java.io.File; import java.io.InputStreamReader; /** * <p>Simple command line application that allows you to export RRD data by means * of a RrdGraphDefTemplate. Pretty straightforward in use.</p> * * @author Arne Vandamme (cob...@jr...) */ public class ExportTemplate { private static int maxRows = 400; // Maximum number of rows private static String templateFile, dumpFile; private static void die( String msg ) { System.err.println( msg ); System.exit( -1 ); } private static void parseArguments( String[] args ) { int rpos = args.length - 1; // Last argument should be the templateFile templateFile = args[rpos]; // Remaining number of parameters should be even if ( rpos % 2 > 0 ) die( "Invalid number of arguments." ); for ( int i = 0; i < rpos; i += 2 ) { String arg = args[i]; String val = args[i + 1]; try { if ( arg.equalsIgnoreCase("-m") ) maxRows = Integer.parseInt(val); else if ( arg.equalsIgnoreCase("-f") ) dumpFile = val; } catch ( Exception e ) { die( "Error with option '" + arg + "': " + e.getMessage() ); } } } private static String readVariable( BufferedReader in, String name ) throws IOException { System.out.print( "Variable '" + name + "' = " ); return in.readLine(); } public static void main( String[] args ) { if ( args.length < 2 ) { System.out.println( "Usage: ExportTemplate [-m width] [-f <dump_file>] <template_file>" ); System.exit(0); } parseArguments( args ); try { // -- Read the RrdGraphDefTemplate (XML format) System.out.println( ">>> Reading XML template" ); RrdExportDefTemplate template = new RrdExportDefTemplate( new File(templateFile) ); // -- Set the parameters (if there are any) System.out.println( ">>> Setting template variables" ); if ( template.hasVariables() ) { BufferedReader in = new BufferedReader( new InputStreamReader(System.in) ); String[] variables = template.getVariables(); for ( int i = 0; i < variables.length; i++ ) template.setVariable( variables[i], readVariable( in, variables[i] ) ); } System.out.println( ">>> Exporting data..." ); long start = System.currentTimeMillis(); // -- Generate the actual graph RrdExport export = new RrdExport( template.getRrdExportDef() ); ExportData data = export.fetch( maxRows ); if ( dumpFile != null ) data.exportXml( dumpFile ); else data.exportXml( System.out ); long stop = System.currentTimeMillis(); System.out.println( ">>> Data exported in " + (stop - start) + " milliseconds" ); } catch ( RrdException rrde ) { die( "RrdException occurred: " + rrde.getMessage() ); } catch ( IOException ioe ) { die( "IOException occurred: " + ioe.getMessage() ); } } } |
From: Arne V. <cob...@us...> - 2004-07-11 22:07:04
|
Update of /cvsroot/jrobin/src/org/jrobin/demo/graph In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv7621/org/jrobin/demo/graph Added Files: GraphTemplate.java SwingDemo.java SwingDemoPanel.java Log Message: JRobin 1.4.0 - Added SwingDemo demo application - Added GraphTemplate demo application --- NEW FILE: SwingDemo.java --- /* ============================================================ * JRobin : Pure java implementation of RRDTool's functionality * ============================================================ * * Project Info: http://www.jrobin.org * Project Lead: Sasa Markovic (sa...@jr...); * * (C) Copyright 2003, by Sasa Markovic. * * Developers: Sasa Markovic (sa...@jr...) * Arne Vandamme (cob...@jr...) * * This library is free software; you can redistribute it and/or modify it under the terms * of the GNU Lesser General Public License as published by the Free Software Foundation; * either version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with this * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, * Boston, MA 02111-1307, USA. */ package org.jrobin.demo.graph; import org.jrobin.core.*; import org.jrobin.graph.RrdGraphDef; import org.jrobin.graph.RrdGraph; import javax.swing.*; import java.io.IOException; import java.awt.*; import java.util.Date; /** * <p>Swing demonstration of the minmax graph.</p> * * @author Arne Vandamme (cob...@jr...) */ public class SwingDemo { static JFrame frame = null; static JPanel demoPanel = null; static RrdGraph graph = null; static RrdGraphDef gDef = null; static final String rrd = "SwingDemo.rrd"; static final long START = Util.getTimestamp( 2004, 1, 1 ); static Date end = new Date(START); static void prepareRrd() throws IOException, RrdException { RrdDef rrdDef = new RrdDef( rrd, START - 300, 300 ); rrdDef.addDatasource("a", "GAUGE", 600, Double.NaN, Double.NaN); rrdDef.addArchive("AVERAGE", 0.5, 1, 300); rrdDef.addArchive("MIN", 0.5, 6, 300); rrdDef.addArchive("MAX", 0.5, 6, 300); RrdDb rrdDb = new RrdDb( rrdDef, RrdBackendFactory.getFactory("MEMORY") ); rrdDb.close(); } static void prepareFrame() throws RrdException { gDef = new RrdGraphDef(); gDef.setImageBorder( Color.WHITE, 0 ); gDef.setTitle("JRobin Swing minmax demo"); gDef.setVerticalLabel( "value" ); gDef.setTimeAxisLabel( "time" ); gDef.datasource("a", rrd, "a", "AVERAGE", "MEMORY" ); gDef.datasource("b", rrd, "a", "MIN", "MEMORY" ); gDef.datasource("c", rrd, "a", "MAX", "MEMORY"); gDef.datasource( "avg", "a", "AVERAGE" ); gDef.area("a", Color.decode("0xb6e4"), "real"); gDef.line("b", Color.decode("0x22e9"), "min", 2 ); gDef.line("c", Color.decode("0xee22"), "max", 2 ); gDef.line("avg", Color.RED, "Average" ); gDef.time( "@l@lTime period: @t", "MMM dd, yyyy HH:mm:ss", START ); gDef.time( "to @t@l", "HH:mm:ss", end ); gDef.time("@l@lGenerated: @t@c", "HH:mm:ss" ); // create graph finally graph = new RrdGraph(gDef); // Create JFrame frame = new JFrame( "JRobin Swing Demo" ); frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); demoPanel = new SwingDemoPanel( graph ); frame.getContentPane().add( demoPanel ); frame.pack(); frame.setBounds( 10, 10, 504, 303 ); frame.show(); } public static void main( String[] args ) throws Exception { prepareRrd(); prepareFrame(); // Let's update the RRD and generate the graphs many times RrdDb rrdDb = new RrdDb( rrd, RrdBackendFactory.getFactory("MEMORY") ); Sample sample = rrdDb.createSample(); long t = 0, start, stop, generationTime; // First we do 2 hours worth of 5 minute updates for ( int i = 1; i < 25; i++ ) { start = System.currentTimeMillis(); t = START + i*300; // Update the rrd sample.setTime( t ); sample.setValue("a", Math.sin(t / 3000.0) * 50 + 50); sample.update(); // Set custom graph settings gDef.setTimePeriod( START, t ); end.setTime( t *1000 ); // Regenerate the graph frame.repaint(); stop = System.currentTimeMillis(); generationTime = stop - start; // Sleep if necessary, don't update more than once per second if ( generationTime < 1000 ) Thread.sleep( 1000 - generationTime ); } // Now we do some more updates, but we move per hour for ( int i = 0; i < 22; i++ ) { start = System.currentTimeMillis(); for ( int j = 1; j < 13; j++ ) { t = t + 300; // Update the rrd sample.setTime( t ); sample.setValue("a", Math.sin(t / 3000.0) * 50 + 50); sample.update(); } // Set custom graph settings gDef.setTimePeriod( START, t ); end.setTime( t * 1000 ); // Regenerate the graph frame.repaint(); stop = System.currentTimeMillis(); generationTime = stop - start; // Sleep if necessary, don't update more than once per second if ( generationTime < 1000 ) Thread.sleep( 1000 - generationTime ); } } } --- NEW FILE: GraphTemplate.java --- /* ============================================================ * JRobin : Pure java implementation of RRDTool's functionality * ============================================================ * * Project Info: http://www.jrobin.org * Project Lead: Sasa Markovic (sa...@jr...); * * (C) Copyright 2003, by Sasa Markovic. * * Developers: Sasa Markovic (sa...@jr...) * Arne Vandamme (cob...@jr...) * * This library is free software; you can redistribute it and/or modify it under the terms * of the GNU Lesser General Public License as published by the Free Software Foundation; * either version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with this * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, * Boston, MA 02111-1307, USA. */ package org.jrobin.demo.graph; import org.jrobin.graph.RrdGraphDefTemplate; import org.jrobin.graph.RrdGraph; import org.jrobin.core.RrdException; import java.io.File; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; /** * <p>Simple command line application that allows you to generate a graph * from a RrdGraphDefTemplate. Pretty straightforward use.</p> * * @author Arne Vandamme (cob...@jr...) */ public class GraphTemplate { private static String format = "gif"; private static int width = 0; // Auto scale private static int height = 0; // Auto scale private static float quality = 1.0f; // JPEG quality private static String templateFile, imageName; private static void die( String msg ) { System.err.println( msg ); System.exit( -1 ); } private static void parseArguments( String[] args ) { int rpos = args.length - 1; // Last two arguments should be templateFile and imageName imageName = args[rpos--]; templateFile = args[rpos]; // Remaining number of parameters should be even if ( rpos % 2 > 0 ) die( "Invalid number of arguments." ); for ( int i = 0; i < rpos; i += 2 ) { String arg = args[i]; String val = args[i + 1]; try { if ( arg.equalsIgnoreCase("-img") ) format = val; else if ( arg.equalsIgnoreCase("-w") ) width = Integer.parseInt(val); else if ( arg.equalsIgnoreCase("-h") ) height = Integer.parseInt(val); else if ( arg.equalsIgnoreCase("-q") ) quality = Float.parseFloat(val); } catch ( Exception e ) { die( "Error with option '" + arg + "': " + e.getMessage() ); } } } private static String readVariable( BufferedReader in, String name ) throws IOException { System.out.print( "Variable '" + name + "' = " ); return in.readLine(); } public static void main( String[] args ) { if ( args.length < 2 ) { System.out.println( "Usage: GraphTemplate [-img (png|gif|jpg)] [-w width] [-h height] [-q jpegQuality] <template_file> <image_name>" ); System.exit(0); } parseArguments( args ); try { // -- Read the RrdGraphDefTemplate (XML format) System.out.println( ">>> Reading XML template" ); RrdGraphDefTemplate template = new RrdGraphDefTemplate( new File(templateFile) ); System.out.println( ">>> Setting template variables" ); if ( template.hasVariables() ) { BufferedReader in = new BufferedReader( new InputStreamReader(System.in) ); String[] variables = template.getVariables(); for ( int i = 0; i < variables.length; i++ ) template.setVariable( variables[i], readVariable( in, variables[i] ) ); } System.out.println( ">>> Generating graph..." ); long start = System.currentTimeMillis(); RrdGraph graph = new RrdGraph( template.getRrdGraphDef() ); if ( format.equalsIgnoreCase("png") ) graph.saveAsPNG( imageName, width, height ); else if ( format.equalsIgnoreCase("gif") ) graph.saveAsGIF( imageName, width, height ); else if ( format.equalsIgnoreCase("jpg") ) graph.saveAsJPEG( imageName, width, height, quality ); long stop = System.currentTimeMillis(); System.out.println( ">>> Graph generated and saved in " + (stop - start) + " milliseconds" ); } catch ( RrdException rrde ) { die( "RrdException occurred: " + rrde.getMessage() ); } catch ( IOException ioe ) { die( "IOException occurred: " + ioe.getMessage() ); } } } --- NEW FILE: SwingDemoPanel.java --- /* ============================================================ * JRobin : Pure java implementation of RRDTool's functionality * ============================================================ * * Project Info: http://www.jrobin.org * Project Lead: Sasa Markovic (sa...@jr...); * * (C) Copyright 2003, by Sasa Markovic. * * Developers: Sasa Markovic (sa...@jr...) * Arne Vandamme (cob...@jr...) * * This library is free software; you can redistribute it and/or modify it under the terms * of the GNU Lesser General Public License as published by the Free Software Foundation; * either version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with this * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, * Boston, MA 02111-1307, USA. */ package org.jrobin.demo.graph; import javax.swing.*; import java.awt.*; import org.jrobin.graph.RrdGraph; /** * <p>Extended JPanel for use in the GUI demo application.</p> * * @author Arne Vandamme (cob...@jr...) */ public class SwingDemoPanel extends JPanel { private RrdGraph graph; SwingDemoPanel( RrdGraph graph ) { this.graph = graph; } public void paintComponent( Graphics g ) { try { // Render the image directly on the Graphics object of the JPanel // Width and height of 0 means autoscale the graph graph.renderImage( (Graphics2D) g, 0, 0 ); } catch ( Exception e ) { e.printStackTrace(); } } } |
From: Arne V. <cob...@us...> - 2004-07-11 22:05:09
|
Update of /cvsroot/jrobin/src/org/jrobin/demo/graph In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv7282/graph Log Message: Directory /cvsroot/jrobin/src/org/jrobin/demo/graph added to the repository |
From: Arne V. <cob...@us...> - 2004-07-11 22:04:23
|
Update of /cvsroot/jrobin/src/org/jrobin/graph In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv7100/org/jrobin/graph Modified Files: ExportData.java Gprint.java RrdExportDef.java RrdExporter.java RrdGraphDef.java RrdGraphDefTemplate.java Sdef.java Source.java Added Files: Print.java RrdExportDefTemplate.java TimeText.java Log Message: JRobin 1.4.0 - Several tweaks - Added print() option to ExportData - Added time() option to RrdGraphDef - Added variables options to XmlTemplate - Added RrdExportDefTemplate --- NEW FILE: TimeText.java --- /* ============================================================ * JRobin : Pure java implementation of RRDTool's functionality * ============================================================ * * Project Info: http://www.jrobin.org * Project Lead: Sasa Markovic (sa...@jr...) * * Developers: Sasa Markovic (sa...@jr...) * Arne Vandamme (cob...@jr...) * * (C) Copyright 2003, by Sasa Markovic. * * This library is free software; you can redistribute it and/or modify it under the terms * of the GNU Lesser General Public License as published by the Free Software Foundation; * either version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with this * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, * Boston, MA 02111-1307, USA. */ package org.jrobin.graph; import org.jrobin.core.RrdException; import org.jrobin.core.Util; import org.jrobin.core.XmlWriter; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.Calendar; /** * <p>Comment object containing a formatted timestamp (current time of timestamp given).</p> */ public class TimeText extends Comment { private static final String TIME_MARKER = "@t"; private Date textDate = null; private DateFormat dateFormat; private ArrayList parsedList; TimeText( String text, String pattern ) throws RrdException { this( text, new SimpleDateFormat( pattern ) ); } TimeText( String text, DateFormat dateFormat ) throws RrdException { super( text ); this.dateFormat = dateFormat; // Check if we can locate the placeholder for the timestamp (@t) if ( text.indexOf(TIME_MARKER) < 0 ) throw new RrdException( "Could not find where to place timestamp. No @t placeholder found."); } TimeText( String text, String pattern, long timestamp ) throws RrdException { this( text, new SimpleDateFormat( pattern ), new Date( timestamp * 1000 ) ); } TimeText( String text, DateFormat dateFormat, long timestamp ) throws RrdException { this( text, dateFormat, new Date( timestamp * 1000 ) ); } TimeText( String text, String pattern, Date date ) throws RrdException { this( text, new SimpleDateFormat( pattern ), date ); } TimeText( String text, DateFormat dateFormat, Date date ) throws RrdException { super( text ); this.textDate = date; this.dateFormat = dateFormat; // Check if we can locate the placeholder for the timestamp (@t) if ( text.indexOf(TIME_MARKER) < 0 ) throw new RrdException( "Could not find where to place timestamp. No @t placeholder found."); } TimeText( String text, String pattern, Calendar cal ) throws RrdException { this( text, new SimpleDateFormat( pattern ), cal.getTime() ); } TimeText( String text, DateFormat dateFormat, Calendar cal ) throws RrdException { this( text, dateFormat, cal.getTime() ); } ArrayList getTokens() { parsedList = new ArrayList( oList ); // Create time string String timeStr = dateFormat.format( (textDate != null ? textDate : new Date()) ); // Replace all values for (int i = 0; i < oList.size(); i += 2 ) { String str = (String) oList.get(i); str = str.replaceAll(TIME_MARKER, timeStr); parsedList.set( i, str ); } return parsedList; } void exportXmlTemplate(XmlWriter xml) { xml.startTag("time"); xml.writeTag( "format", text ); if ( dateFormat instanceof SimpleDateFormat ) xml.writeTag( "pattern", ((SimpleDateFormat) dateFormat).toPattern()); else xml.writeTag( "pattern", "" ); // A custom DateFormat can't be exported if ( textDate != null ) xml.writeTag( "value", Util.getTimestamp(textDate) ); xml.closeTag(); } } Index: Gprint.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/graph/Gprint.java,v retrieving revision 1.6 retrieving revision 1.7 diff -C2 -d -r1.6 -r1.7 *** Gprint.java 9 Jun 2004 07:35:36 -0000 1.6 --- Gprint.java 11 Jul 2004 22:04:13 -0000 1.7 *************** *** 79,84 **** super.parseComment(); ! this.commentType = Comment.CMT_GPRINT; ! this.sourceName = sourceName; if ( consolFunc.equalsIgnoreCase("AVERAGE") || consolFunc.equalsIgnoreCase("AVG") ) --- 79,84 ---- super.parseComment(); ! this.commentType = Comment.CMT_GPRINT; ! this.sourceName = sourceName; if ( consolFunc.equalsIgnoreCase("AVERAGE") || consolFunc.equalsIgnoreCase("AVG") ) *************** *** 116,120 **** } - // ================================================================ // -- Protected methods --- 116,119 ---- *************** *** 138,142 **** // See if we need to use a specific value for the formatting double oldBase = vFormat.getBase(); ! if ( baseValue != -1 ) vFormat.setBase( baseValue ); --- 137,141 ---- // See if we need to use a specific value for the formatting double oldBase = vFormat.getBase(); ! if ( baseValue != -1 && baseValue != vFormat.getBase() ) vFormat.setBase( baseValue ); Index: Sdef.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/graph/Sdef.java,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** Sdef.java 9 Jul 2004 12:22:15 -0000 1.2 --- Sdef.java 11 Jul 2004 22:04:14 -0000 1.3 *************** *** 84,87 **** --- 84,88 ---- values = new double[ numPoints ]; this.aggregatePoints = aggregatePoints; + calculated = false; } Index: Source.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/graph/Source.java,v retrieving revision 1.10 retrieving revision 1.11 diff -C2 -d -r1.10 -r1.11 *** Source.java 10 Jul 2004 00:07:03 -0000 1.10 --- Source.java 11 Jul 2004 22:04:14 -0000 1.11 *************** *** 57,64 **** --- 57,66 ---- protected long step = 0; + private long lastPreciseTime = 0; // Last time requested private long lastTime = 0; private long totalTime = 0; private int stPos = 0; + private int lastStPos = 0; // Last value position requested // ================================================================ *************** *** 120,126 **** { // Return the next value if we fetched it before ! if ( !Double.isInfinite(nextValue) ) return nextValue; // Try to fetch the next value for ( int i = pos + 1; i < values.length; i++ ) --- 122,130 ---- { // 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++ ) *************** *** 142,145 **** --- 146,151 ---- nextValue = Double.POSITIVE_INFINITY; + lastStPos = pos; + return values[pos]; } *************** *** 147,152 **** double get( long preciseTime, long[] reducedTimestamps ) { ! long t = Util.normalize( preciseTime, step ); ! t = ( t < preciseTime ? t + step : t ); while ( stPos < reducedTimestamps.length - 1 ) --- 153,163 ---- 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 prolly in a new iteration ! stPos = 0; ! ! lastPreciseTime = preciseTime; while ( stPos < reducedTimestamps.length - 1 ) Index: RrdGraphDefTemplate.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/graph/RrdGraphDefTemplate.java,v retrieving revision 1.7 retrieving revision 1.8 diff -C2 -d -r1.7 -r1.8 *** RrdGraphDefTemplate.java 30 May 2004 19:49:56 -0000 1.7 --- RrdGraphDefTemplate.java 11 Jul 2004 22:04:14 -0000 1.8 *************** *** 345,349 **** private void resolveGraphElements(Node graphNode) throws RrdException { validateTagsOnlyOnce(graphNode, new String[] { ! "area*", "line*", "stack*", "gprint*", "hrule*", "vrule*", "comment*" }); Node[] childs = getChildNodes(graphNode); --- 345,349 ---- private void resolveGraphElements(Node graphNode) throws RrdException { validateTagsOnlyOnce(graphNode, new String[] { ! "area*", "line*", "stack*", "gprint*", "hrule*", "vrule*", "comment*", "time*" }); Node[] childs = getChildNodes(graphNode); *************** *** 379,382 **** --- 379,390 ---- rrdGraphDef.gprint( datasource, consolFun, format, getChildValueAsDouble(childs[i], "base") ); } + else if(nodeName.equals("time")) { + validateTagsOnlyOnce(childs[i], new String[] { "format", "pattern", "value" }); + String format = getChildValue(childs[i], "format", false ); + String pattern = getChildValue(childs[i], "pattern"); + String timestamp = getChildValue(childs[i], "value"); + + rrdGraphDef.time( format, pattern, Util.getGregorianCalendar(timestamp) ); + } else if(nodeName.equals("hrule")) { validateTagsOnlyOnce(childs[i], new String[] { "value", "color", "legend", "width" }); *************** *** 482,493 **** Node[] nodes = getChildNodes(datasourceNode, "def"); for(int i = 0; i < nodes.length; i++) { ! if(hasChildNode(nodes[i], "rrd")) { // RRD datasource ! validateTagsOnlyOnce(nodes[i], new String[] {"name", "rrd", "source", "cf"}); ! String name = getChildValue(nodes[i], "name"); ! String rrd = getChildValue(nodes[i], "rrd"); ! String dsName = getChildValue(nodes[i], "source"); String consolFun = getChildValue(nodes[i], "cf"); ! rrdGraphDef.datasource(name, rrd, dsName, consolFun); } else if(hasChildNode(nodes[i], "rpn")) { --- 490,509 ---- Node[] nodes = getChildNodes(datasourceNode, "def"); for(int i = 0; i < nodes.length; i++) { ! if(hasChildNode(nodes[i], "rrd")) ! { // RRD datasource ! validateTagsOnlyOnce(nodes[i], new String[] {"name", "rrd", "source", "cf", "backend"}); ! String name = getChildValue(nodes[i], "name"); ! String rrd = getChildValue(nodes[i], "rrd"); ! String dsName = getChildValue(nodes[i], "source"); String consolFun = getChildValue(nodes[i], "cf"); ! ! if ( Util.Xml.hasChildNode(nodes[i], "backend") ) ! { ! String backend = getChildValue( nodes[i], "backend" ); ! rrdGraphDef.datasource( name, rrd, dsName, consolFun, backend ); ! } ! else ! rrdGraphDef.datasource(name, rrd, dsName, consolFun); } else if(hasChildNode(nodes[i], "rpn")) { Index: ExportData.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/graph/ExportData.java,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** ExportData.java 10 Jul 2004 00:07:03 -0000 1.2 --- ExportData.java 11 Jul 2004 22:04:13 -0000 1.3 *************** *** 50,53 **** --- 50,54 ---- private Source[] sources; + private Print printer; // ================================================================ *************** *** 296,299 **** --- 297,357 ---- /** + * <p>Calculate the chosen consolidation function <code>consolFun</code> over + * the <code>sourceName</code> and returns the result as a string using the + * specified <code>format</code>.</p> + * + * <p>In the format string there should be a + * <code>@n.d</code> marker (replace <code>n</code> with the total number of spaces the + * value should at minimum take up, and replace <code>d</code> with the desired number of decimals) + * in the place where the number should be printed. If an additional <code>@s</code> is + * found in the format, the value will be scaled and an appropriate SI magnitude + * unit will be printed in place of the <code>@s</code> marker. If you specify + * <code>@S</code> instead of <code>@s</code>, the value will be scaled with the scale + * factor used in the last gprint directive (uniform value scaling).</p> + * + * @param sourceName Source name + * @param consolFun Consolidation function to be used for calculation ("AVERAGE", + * "MIN", "MAX", "LAST" or "TOTAL" (since 1.3.1) + * @param format Format string. For example: "speed is @5.2 @sbits/sec@c", + * "temperature = @0 degrees" + * @throws RrdException Thrown in case of JRobin specific error + */ + public String print( String sourceName, String consolFun, String format ) throws RrdException { + return print( sourceName, consolFun, format, ValueFormatter.DEFAULT_BASE ); + } + + /** + * <p>Calculate the chosen consolidation function <code>consolFun</code> over + * the <code>sourceName</code> and returns the result as a string using the + * specified <code>format</code>.</p> + * + * <p>In the format string there should be a + * <code>@n.d</code> marker (replace <code>n</code> with the total number of spaces the + * value should at minimum take up, and replace <code>d</code> with the desired number of decimals) + * in the place where the number should be printed. If an additional <code>@s</code> is + * found in the format, the value will be scaled and an appropriate SI magnitude + * unit will be printed in place of the <code>@s</code> marker. If you specify + * <code>@S</code> instead of <code>@s</code>, the value will be scaled with the scale + * factor used in the last gprint directive (uniform value scaling).</p> + * + * @param sourceName Source name + * @param consolFun Consolidation function to be used for calculation ("AVERAGE", + * "MIN", "MAX", "LAST" or "TOTAL" (since 1.3.1) + * @param format Format string. For example: "speed is @5.2 @sbits/sec@c", + * "temperature = @0 degrees" + * @param base Base value used to calculate the appriopriate scaling SI magnitude. + * @throws RrdException Thrown in case of JRobin specific error + */ + public String print( String sourceName, String consolFun, String format, double base ) throws RrdException + { + double value = getAggregate( sourceName, consolFun ); + + if ( printer == null ) + printer = new Print( base, ValueFormatter.NO_SCALE ); + + return printer.getFormattedString( value, format, base ); + } + + /** * Imports a export XML string and maps it back to this ExportData object. * The XML can be from either a JRobin or RRDtool export. *************** *** 398,403 **** for ( int i = 0; i < sources.length; i++ ) sourceByName.put( sources[i].getName(), sources[i] ); - - } --- 456,459 ---- Index: RrdExportDef.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/graph/RrdExportDef.java,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** RrdExportDef.java 10 Jul 2004 00:07:03 -0000 1.2 --- RrdExportDef.java 11 Jul 2004 22:04:13 -0000 1.3 *************** *** 25,29 **** package org.jrobin.graph; ! import java.io.Serializable; import java.util.ArrayList; import java.util.Date; --- 25,29 ---- package org.jrobin.graph; ! import java.io.*; import java.util.ArrayList; import java.util.Date; *************** *** 32,35 **** --- 32,36 ---- import org.jrobin.core.Util; import org.jrobin.core.RrdException; + import org.jrobin.core.XmlWriter; /** *************** *** 367,370 **** --- 368,465 ---- } + /** + * Exports RrdExportDef (export definition) object in XML format to output stream. + * Generated code can be parsed with {@link RrdExportDefTemplate} class. + * + * @param stream Output stream to send XML code to. + */ + public void exportXmlTemplate( OutputStream stream ) + { + XmlWriter xml = new XmlWriter( stream ); + + xml.startTag("rrd_export_def"); + + // SPAN + xml.startTag("span"); + xml.writeTag("start", getStartTime() ); + xml.writeTag("end", getEndTime() ); + xml.closeTag(); // span + + // OPTIONS + xml.startTag( "options" ); + if ( resolution > 1 ) + xml.writeTag( "resolution", resolution ); + xml.writeTag( "strict_export", ( strict == STRICT_IMPLICIT_ON || strict == STRICT_EXPLICIT_ON ? "true" : "false" ) ); + xml.closeTag(); + + // DATASOURCES + xml.startTag("datasources"); + // defs + for ( int i = 0; i < fetchSources.size(); i++ ) + fetchSources.get( i ).exportXml(xml); + // cdefs and sdefs + for (int i = 0; i < cdefList.size(); i++ ) + { + Cdef cdef = (Cdef) cdefList.get(i); + cdef.exportXml(xml); + } + xml.closeTag(); // datasources + + // EXPORTS + xml.startTag("exports"); + String[][] list = getExportDatasources(); + for ( int i = 0; i < list.length; i++ ) + { + xml.startTag( "export" ); + xml.writeTag( "datasource", list[i][0] ); + xml.writeTag( "legend", list[i][1] ); + xml.closeTag(); + } + xml.closeTag(); // exports + + xml.closeTag(); // rrd_export_def + xml.flush(); + + xml.flush(); + } + + /** + * Exports RrdExportDef (export definition) object in XML format to string. + * Generated code can be parsed with {@link RrdExportDefTemplate} class, see + * {@link RrdExportDef#exportXmlTemplate()}. + * + * @return String representing graph definition in XML format. + */ + public String getXmlTemplate() + { + return exportXmlTemplate(); + } + + /** + * Exports RrdExportDef (export definition) object in XML format to string. + * Generated code can be parsed with {@link RrdExportDefTemplate} class. + * + * @return String representing graph definition in XML format. + */ + public String exportXmlTemplate() + { + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + exportXmlTemplate(outputStream); + return outputStream.toString(); + } + + /** + * Exports RrdExportDef (export definition) object in XML format to file. + * Generated code can be parsed with {@link RrdExportDefTemplate} class. + * + * @param filePath destination file + */ + public void exportXmlTemplate(String filePath) throws IOException + { + FileOutputStream outputStream = new FileOutputStream(filePath, false); + exportXmlTemplate(outputStream); + outputStream.close(); + } + // ================================================================ // -- Protected (package) methods Index: RrdExporter.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/graph/RrdExporter.java,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** RrdExporter.java 10 Jul 2004 00:07:03 -0000 1.2 --- RrdExporter.java 11 Jul 2004 22:04:13 -0000 1.3 *************** *** 147,150 **** --- 147,151 ---- long requestedStep = (long) (endTime - startTime) / maxRows; + if ( requestedStep <= 0 ) requestedStep = 1; // Shift start and endTime *************** *** 172,175 **** --- 173,177 ---- requestedStep = (long) (endTime - startTime) / maxRows; + if ( requestedStep <= 0 ) requestedStep = 1; } *************** *** 462,465 **** --- 464,470 ---- protected ExportData createExportData() throws RrdException { + if ( sources == null) + throw new RrdException( "Sources not calculated, no data to return." ); + // Now create a RrdDataSet object containing the results Source[] sourceSet; --- NEW FILE: Print.java --- package org.jrobin.graph; import org.jrobin.core.RrdException; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * <p>This is a simplified version of the Gprint class, used for simple value formatting * with scaling.</p> * * @author Arne Vandamme (cob...@jr...) */ class Print { // ================================================================ // -- Members // ================================================================ private static final String SCALE_MARKER = "@s"; private static final String UNIFORM_SCALE_MARKER = "@S"; private static final String VALUE_MARKER = "@([0-9]*\\.[0-9]{1}|[0-9]{1}|\\.[0-9]{1})"; private static final Pattern VALUE_PATTERN = Pattern.compile(VALUE_MARKER); private int numDec = 3; // Show 3 decimal values by default private int strLen = -1; private boolean normalScale = false; private boolean uniformScale = false; private ValueFormatter vFormat; // ================================================================ // -- Constructor // ================================================================ Print( double defaultBase, int scaleIndex ) { vFormat = new ValueFormatter( defaultBase, scaleIndex ); } // ================================================================ // -- Protected methods // ================================================================ String getFormattedString( double value, String format, double baseValue ) throws RrdException { // -- Parse the format checkValuePlacement( format ); // -- Generate the formatted string double oldBase = vFormat.getBase(); vFormat.setBase( baseValue ); vFormat.setFormat( value, numDec, strLen ); vFormat.setScaling( normalScale, uniformScale ); String valueStr = vFormat.getFormattedValue(); String prefix = vFormat.getPrefix(); vFormat.setBase( oldBase ); String str = format; str = str.replaceAll(VALUE_MARKER, valueStr); if ( normalScale ) str = str.replaceAll(SCALE_MARKER, prefix); if ( uniformScale ) str = str.replaceAll(UNIFORM_SCALE_MARKER, prefix); return str; } private void checkValuePlacement( String text ) throws RrdException { Matcher m = VALUE_PATTERN.matcher(text); if ( m.find() ) { normalScale = (text.indexOf(SCALE_MARKER) >= 0); uniformScale = (text.indexOf(UNIFORM_SCALE_MARKER) >= 0); if ( normalScale && uniformScale ) throw new RrdException( "Can't specify normal scaling and uniform scaling at the same time." ); String[] group = m.group(1).split("\\."); strLen = -1; numDec = 0; if ( group.length > 1 ) { if ( group[0].length() > 0 ) { strLen = Integer.parseInt(group[0]); numDec = Integer.parseInt(group[1]); } else numDec = Integer.parseInt(group[1]); } else numDec = Integer.parseInt(group[0]); } else throw new RrdException( "Could not find where to place value. No @ placeholder found." ); } } --- NEW FILE: RrdExportDefTemplate.java --- /* ============================================================ * JRobin : Pure java implementation of RRDTool's functionality * ============================================================ * * Project Info: http://www.jrobin.org * Project Lead: Sasa Markovic (sa...@jr...) * * Developers: Sasa Markovic (sa...@jr...) * Arne Vandamme (cob...@jr...) * * (C) Copyright 2003, by Sasa Markovic. * * This library is free software; you can redistribute it and/or modify it under the terms * of the GNU Lesser General Public License as published by the Free Software Foundation; * either version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with this * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, * Boston, MA 02111-1307, USA. */ package org.jrobin.graph; import org.xml.sax.InputSource; import org.jrobin.core.RrdException; import org.jrobin.core.XmlTemplate; import org.jrobin.core.Util; import org.w3c.dom.Node; import java.io.IOException; import java.io.File; import java.util.GregorianCalendar; /** * <p>Class used to create an arbitrary number of RrdExportDef (export) objects * from a single XML template. XML template can be supplied as an XML InputSource, * XML file or XML formatted string.<p> * * @author Arne Vandamme (arn...@jr...) */ public class RrdExportDefTemplate extends XmlTemplate { private RrdExportDef def; /** * Creates template object from any parsable XML source * @param inputSource XML source * @throws java.io.IOException thrown in case of I/O error * @throws org.jrobin.core.RrdException usually thrown in case of XML related error */ public RrdExportDefTemplate(InputSource inputSource) throws IOException, RrdException { super(inputSource); } /** * Creates template object from the file containing XML template code * @param xmlFile file containing XML template * @throws IOException thrown in case of I/O error * @throws RrdException usually thrown in case of XML related error */ public RrdExportDefTemplate(File xmlFile) throws IOException, RrdException { super(xmlFile); } /** * Creates template object from the string containing XML template code * @param xmlString string containing XML template * @throws IOException thrown in case of I/O error * @throws RrdException usually thrown in case of XML related error */ public RrdExportDefTemplate(String xmlString) throws IOException, RrdException { super(xmlString); } /** * Creates RrdExportDef object which can be used to create RrdExport * object (actual JRobin export). Before this method is called, all template variables (if any) * must be resolved (replaced with real values). * See {@link XmlTemplate#setVariable(String, String) setVariable()} method information to * understand how to supply values for template variables. * * @return Export definition which can be used to create RrdExport object (actual JRobin export) * @throws RrdException Thrown if parsed XML template contains invalid (unrecognized) tags */ public RrdExportDef getRrdExportDef() throws RrdException { // basic check if( !root.getTagName().equals("rrd_export_def") ) throw new RrdException("XML definition must start with <rrd_export_def>"); validateTagsOnlyOnce( root, new String[] {"span", "options", "datasources", "exports"} ); def = new RrdExportDef(); // traverse all nodes Node[] childs = getChildNodes(root); for(int i = 0; i < childs.length; i++) { // SPAN String nodeName = childs[i].getNodeName(); if(nodeName.equals("span")) { resolveSpan(childs[i]); } // OPTIONS else if(nodeName.equals("options")) { resolveOptions(childs[i]); } // DATASOURCES else if(nodeName.equals("datasources")) { resolveDatasources(childs[i]); } // EXPORTS else if(nodeName.equals("exports")) { resolveExports(childs[i]); } } return def; } private void resolveExports(Node datasourceNode) throws RrdException { validateTagsOnlyOnce(datasourceNode, new String[] { "export*" }); Node[] nodes = getChildNodes(datasourceNode, "export"); for( int i = 0; i < nodes.length; i++ ) { validateTagsOnlyOnce( nodes[i], new String[] { "datasource", "legend" } ); String ds = getChildValue( nodes[i], "datasource" ); String legend = getChildValue( nodes[i], "legend" ); def.export( ds, legend ); } } private void resolveDatasources(Node datasourceNode) throws RrdException { validateTagsOnlyOnce(datasourceNode, new String[] { "def*" }); Node[] nodes = getChildNodes(datasourceNode, "def"); for(int i = 0; i < nodes.length; i++) { if(hasChildNode(nodes[i], "rrd")) { // RRD datasource validateTagsOnlyOnce(nodes[i], new String[] {"name", "rrd", "source", "cf", "backend"}); String name = getChildValue(nodes[i], "name"); String rrd = getChildValue(nodes[i], "rrd"); String dsName = getChildValue(nodes[i], "source"); String consolFun = getChildValue(nodes[i], "cf"); if ( Util.Xml.hasChildNode(nodes[i], "backend") ) { String backend = getChildValue( nodes[i], "backend" ); def.datasource( name, rrd, dsName, consolFun, backend ); } else def.datasource(name, rrd, dsName, consolFun); } else if(hasChildNode(nodes[i], "rpn")) { // RPN datasource validateTagsOnlyOnce(nodes[i], new String[] {"name", "rpn"}); String name = getChildValue(nodes[i], "name"); String rpn = getChildValue(nodes[i], "rpn"); def.datasource(name, rpn); } else if ( hasChildNode( nodes[i], "cf" ) || hasChildNode( nodes[i], "datasource" ) ) { // STATIC AGGREGATED DATASOURCE validateTagsOnlyOnce( nodes[i], new String[] {"name", "datasource", "cf"} ); String name = getChildValue(nodes[i], "name"); String ds = getChildValue(nodes[i], "datasource"); String cf = getChildValue(nodes[i], "cf"); def.datasource( name, ds, cf ); } else { throw new RrdException("Unrecognized <def> format"); } } } private void resolveOptions(Node rootOptionNode) throws RrdException { validateTagsOnlyOnce( rootOptionNode, new String[] { "resolution", "strict_export" }); Node[] optionNodes = getChildNodes(rootOptionNode); for( int i = 0; i < optionNodes.length; i++ ) { String option = optionNodes[i].getNodeName(); Node optionNode = optionNodes[i]; if(option.equals("strict_export")) // STRICT EXPORT def.setStrictExport( getValueAsBoolean(optionNode) ); else if(option.equals("resolution")) // RESOLUTION def.setResolution( getValueAsInt(optionNode) ); } } private void resolveSpan(Node spanNode) throws RrdException { validateTagsOnlyOnce(spanNode, new String[] {"start", "end"}); String startStr = getChildValue(spanNode, "start"); String endStr = getChildValue(spanNode, "end"); GregorianCalendar gc1 = Util.getGregorianCalendar(startStr); GregorianCalendar gc2 = Util.getGregorianCalendar(endStr); def.setTimePeriod(gc1, gc2); } } Index: RrdGraphDef.java =================================================================== RCS file: /cvsroot/jrobin/src/org/jrobin/graph/RrdGraphDef.java,v retrieving revision 1.18 retrieving revision 1.19 diff -C2 -d -r1.18 -r1.19 *** RrdGraphDef.java 10 Jul 2004 00:07:03 -0000 1.18 --- RrdGraphDef.java 11 Jul 2004 22:04:13 -0000 1.19 *************** *** 31,34 **** --- 31,35 ---- import java.util.*; import java.text.SimpleDateFormat; + import java.text.DateFormat; import org.jrobin.core.RrdException; *************** *** 75,79 **** private boolean showLegend = true; // show legend and comments (default: yes) private boolean drawSignature = true; // show JRobin url signature (default: yes) - private boolean useExportDataFlag = false; // use ExportData instead of normal datasources private Color backColor = new Color( 245, 245, 245 ); // variation of light gray --- 76,79 ---- *************** *** 742,745 **** --- 742,746 ---- * Adds a vertical rule to the graph definition. The legend allows for the same * alignment options as <code>gprint</code> or <code>comment</code>. + * * @param timestamp Rule position (specific moment in time) * @param color Rule color. *************** *** 761,764 **** --- 762,766 ---- * marker at the very end of the string. By putting a <code>@g</code> marker instead all * whitespace inside the string at very beginning or end will be removed also. + * * @param text Comment * @throws RrdException Thrown in case of JRobin specific error. *************** *** 767,770 **** --- 769,886 ---- addComment( new Comment(text) ); } + + /** + * Adds a comment that will contain the current time, to the graph definition. Normal comment codes + * apply, but a special marker <code>@t</code> should be present for the location of the timestamp. + * The actual format of the printed timestamp is determined by the pattern parameter, for information + * on possible patterns, see <em>java.text.SimpleDateFormat</em>. + * + * @param text Comment text (must contain @t marker). + * @param pattern SimpleDateFormat pattern to format the timestamp with. + * @throws RrdException Thrown in case of JRobin specific error. + */ + public void time( String text, String pattern ) throws RrdException { + addComment( new TimeText( text, pattern ) ); + } + + /** + * Adds a comment that will contain the current time, to the graph definition. Normal comment codes + * apply, but a special marker <code>@t</code> should be present for the location of the timestamp. + * The actual format of the printed timestamp is determined by the DateFormat passed as a parameter. + * + * @param text Comment text (must contain @t marker). + * @param format DateFormat object to format the timestamp with. + * @throws RrdException Thrown in case of JRobin specific error. + */ + public void time( String text, DateFormat format ) throws RrdException { + addComment( new TimeText( text, format ) ); + } + + /** + * Adds a comment that will contain the given timestamp, to the graph definition. Normal comment codes + * apply, but a special marker <code>@t</code> should be present for the location of the timestamp. + * The actual format of the printed timestamp is determined by the pattern parameter, for information + * on possible patterns, see <em>java.text.SimpleDateFormat</em>. + * + * @param text Comment text (must contain @t marker). + * @param pattern SimpleDateFormat pattern to format the timestamp with. + * @param timestamp Timestamp (in seconds) that should be formatted. + * @throws RrdException Thrown in case of JRobin specific error. + */ + public void time( String text, String pattern, long timestamp ) throws RrdException { + addComment( new TimeText( text, pattern, timestamp ) ); + } + + /** + * Adds a comment that will contain the given timestamp, to the graph definition. Normal comment codes + * apply, but a special marker <code>@t</code> should be present for the location of the timestamp. + * The actual format of the printed timestamp is determined by the DateFormat passed as a parameter. + * + * @param text Comment text (must contain @t marker). + * @param format DateFormat object to format the timestamp with. + * @param timestamp Timestamp (in seconds) that should be formatted. + * @throws RrdException Thrown in case of JRobin specific error. + */ + public void time( String text, DateFormat format, long timestamp ) throws RrdException { + addComment( new TimeText( text, format, timestamp ) ); + } + + /** + * Adds a comment that will contain the given timestamp, to the graph definition. Normal comment codes + * apply, but a special marker <code>@t</code> should be present for the location of the timestamp. + * The actual format of the printed timestamp is determined by the pattern parameter, for information + * on possible patterns, see <em>java.text.SimpleDateFormat</em>. + * + * @param text Comment text (must contain @t marker). + * @param pattern SimpleDateFormat pattern to format the timestamp with. + * @param date Timestamp (as Date object) that should be formatted. + * @throws RrdException Thrown in case of JRobin specific error. + */ + public void time( String text, String pattern, Date date ) throws RrdException { + addComment( new TimeText( text, pattern, date ) ); + } + + /** + * Adds a comment that will contain the given timestamp, to the graph definition. Normal comment codes + * apply, but a special marker <code>@t</code> should be present for the location of the timestamp. + * The actual format of the printed timestamp is determined by the DateFormat passed as a parameter. + * + * @param text Comment text (must contain @t marker). + * @param format DateFormat object to format the timestamp with. + * @param date Timestamp (as Date object) that should be formatted. + * @throws RrdException Thrown in case of JRobin specific error. + */ + public void time( String text, DateFormat format, Date date ) throws RrdException { + addComment( new TimeText( text, format, date ) ); + } + + /** + * Adds a comment that will contain the given timestamp, to the graph definition. Normal comment codes + * apply, but a special marker <code>@t</code> should be present for the location of the timestamp. + * The actual format of the printed timestamp is determined by the pattern parameter, for information + * on possible patterns, see <em>java.text.SimpleDateFormat</em>. + * + * @param text Comment text (must contain @t marker). + * @param pattern SimpleDateFormat pattern to format the timestamp with. + * @param cal Timestamp (as Calendar) that should be formatted. + * @throws RrdException Thrown in case of JRobin specific error. + */ + public void time( String text, String pattern, Calendar cal) throws RrdException { + addComment( new TimeText( text, pattern, cal ) ); + } + + /** + * Adds a comment that will contain the given timestamp, to the graph definition. Normal comment codes + * apply, but a special marker <code>@t</code> should be present for the location of the timestamp. + * The actual format of the printed timestamp is determined by the DateFormat passed as a parameter. + * + * @param text Comment text (must contain @t marker). + * @param format DateFormat object to format the timestamp with. + * @param cal Timestamp (as Calendar) that should be formatted. + * @throws RrdException Thrown in case of JRobin specific error. + */ + public void time( String text, DateFormat format, Calendar cal) throws RrdException { + addComment( new TimeText( text, format, cal ) ); + } /** *************** *** 928,966 **** } - /** - * Exports RrdGraphDef (graph definition) object in XML format to string. - * Generated code can be parsed with {@link RrdGraphDefTemplate} class, see - * {@link RrdGraphDef#exportXmlTemplate()}. - * - * @return String representing graph definition in XML format - */ - public String getXmlTemplate() { - return exportXmlTemplate(); - } - - /** - * Exports RrdGraphDef (graph definition) object in XML format to string. - * Generated code can be parsed with {@link RrdGraphDefTemplate} class. - * - * @return String representing graph definition in XML format - */ - public String exportXmlTemplate() { - ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); - exportXmlTemplate(outputStream); - return outputStream.toString(); - } - - /** - * Exports RrdGraphDef (graph definition) object in XML format to file. - * Generated code can be parsed with {@link RrdGraphDefTemplate} class. - * - * @param filePath destination file - */ - public void exportXmlTemplate(String filePath) throws IOException { - FileOutputStream outputStream = new FileOutputStream(filePath, false); - exportXmlTemplate(outputStream); - outputStream.close(); - } - // ================================================================ // -- Protected (package) methods --- 1044,1047 ---- |