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: <cob...@us...> - 2003-10-30 16:21:16
|
Update of /cvsroot/jrobin/src/jrobin/mrtg/server In directory sc8-pr-cvs1:/tmp/cvs-serv20325/src/jrobin/mrtg/server Modified Files: Grapher.java Log Message: Graph lib 1.2.0 Almost final to final... Minor fixes, minor tweaking Added option to disable spacer between comments Index: Grapher.java =================================================================== RCS file: /cvsroot/jrobin/src/jrobin/mrtg/server/Grapher.java,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** Grapher.java 3 Oct 2003 08:07:51 -0000 1.3 --- Grapher.java 30 Oct 2003 16:21:13 -0000 1.4 *************** *** 47,50 **** --- 47,52 ---- try { return graph.getPNGBytes(GRAPH_WIDTH, GRAPH_HEIGHT); + } catch (RrdException e) { + throw new MrtgException(e); } catch (IOException e) { throw new MrtgException(e); *************** *** 59,64 **** gDef.setTimePeriod(start, stop); gDef.setTitle(ifDescr + "@" + host); ! gDef.setTimeAxisLabel("time"); ! gDef.setValueAxisLabel("transfer speed [bits/sec]"); gDef.datasource("in", filename, "in", "AVERAGE"); gDef.datasource("out", filename, "out", "AVERAGE"); --- 61,65 ---- gDef.setTimePeriod(start, stop); gDef.setTitle(ifDescr + "@" + host); ! gDef.setVerticalLabel("transfer speed [bits/sec]"); gDef.datasource("in", filename, "in", "AVERAGE"); gDef.datasource("out", filename, "out", "AVERAGE"); |
From: <cob...@us...> - 2003-10-30 16:21:16
|
Update of /cvsroot/jrobin/src/jrobin/core In directory sc8-pr-cvs1:/tmp/cvs-serv20325/src/jrobin/core Modified Files: Util.java Log Message: Graph lib 1.2.0 Almost final to final... Minor fixes, minor tweaking Added option to disable spacer between comments Index: Util.java =================================================================== RCS file: /cvsroot/jrobin/src/jrobin/core/Util.java,v retrieving revision 1.8 retrieving revision 1.9 diff -C2 -d -r1.8 -r1.9 *** Util.java 23 Oct 2003 23:16:36 -0000 1.8 --- Util.java 30 Oct 2003 16:21:13 -0000 1.9 *************** *** 29,34 **** import java.util.GregorianCalendar; - import java.util.LinkedList; - /** * Class defines various utility functions used in JRobin. --- 29,32 ---- *************** *** 38,45 **** public class Util { - static long s1 = System.currentTimeMillis(); - static long s2; - public static LinkedList timeList = new LinkedList(); - // pattern RRDTool uses to format doubles in XML files static final String PATTERN = "0.0000000000E00"; --- 36,39 ---- *************** *** 172,191 **** } return value; - } - - // Arne - timing of methods - public static void time() - { - time(-10); - } - - public static void time( int str ) - { - s2 = System.currentTimeMillis(); - if ( str >= 0 ) { - timeList.addLast( str + "_" + (s2 - s1)); - //System.err.println( "[" + str + "] --- " + (s2 - s1) + " ms"); - } - s1 = s2; } --- 166,169 ---- |
Update of /cvsroot/jrobin/src/jrobin/graph2 In directory sc8-pr-cvs1:/tmp/cvs-serv20325/src/jrobin/graph2 Removed Files: FetchSource.java RpnCalculator.java Cdef.java Source.java ValueGrid.java CustomLine.java GridRange.java TimeMarker.java Stack.java TimeAxisUnit.java ValueExtractor.java CustomArea.java ValueFormatter.java ValueAxisUnit.java Title.java Area.java ChartGraphics.java RrdGraphDef.java Gprint.java RrdGraph.java Comment.java TimeGrid.java ChartPanel.java JpegImageWriteParam.java Legend.java ValueMarker.java LegendMarker.java Grapher.java Def.java PlotDef.java Line.java Log Message: Graph lib 1.2.0 Almost final to final... Minor fixes, minor tweaking Added option to disable spacer between comments --- FetchSource.java DELETED --- --- RpnCalculator.java DELETED --- --- Cdef.java DELETED --- --- Source.java DELETED --- --- ValueGrid.java DELETED --- --- CustomLine.java DELETED --- --- GridRange.java DELETED --- --- TimeMarker.java DELETED --- --- Stack.java DELETED --- --- TimeAxisUnit.java DELETED --- --- ValueExtractor.java DELETED --- --- CustomArea.java DELETED --- --- ValueFormatter.java DELETED --- --- ValueAxisUnit.java DELETED --- --- Title.java DELETED --- --- Area.java DELETED --- --- ChartGraphics.java DELETED --- --- RrdGraphDef.java DELETED --- --- Gprint.java DELETED --- --- RrdGraph.java DELETED --- --- Comment.java DELETED --- --- TimeGrid.java DELETED --- --- ChartPanel.java DELETED --- --- JpegImageWriteParam.java DELETED --- --- Legend.java DELETED --- --- ValueMarker.java DELETED --- --- LegendMarker.java DELETED --- --- Grapher.java DELETED --- --- Def.java DELETED --- --- PlotDef.java DELETED --- --- Line.java DELETED --- |
From: <sa...@us...> - 2003-10-28 14:55:30
|
Update of /cvsroot/jrobin/src/jrobin/demo In directory sc8-pr-cvs1:/tmp/cvs-serv28252/jrobin/demo Modified Files: JRobinDemo.java Log Message: GIF Encoder Index: JRobinDemo.java =================================================================== RCS file: /cvsroot/jrobin/src/jrobin/demo/JRobinDemo.java,v retrieving revision 1.8 retrieving revision 1.9 diff -C2 -d -r1.8 -r1.9 *** JRobinDemo.java 15 Oct 2003 14:16:00 -0000 1.8 --- JRobinDemo.java 28 Oct 2003 14:51:39 -0000 1.9 *************** *** 105,108 **** --- 105,109 ---- String pngPath = getFullPath(FILE + ".png"); String jpegPath = getFullPath(FILE + ".jpeg"); + String gifPath = getFullPath(FILE + ".gif"); String logPath = getFullPath(FILE + ".log"); PrintWriter pw = new PrintWriter( *************** *** 155,162 **** println(request.dump()); pw.println(request.dump()); ! FetchPoint[] points = request.fetch(); ! println("==Data fetched. " + points.length + " points obtained"); ! for(int i = 0; i < points.length; i++) { ! println(points[i].dump()); } println("==Fetch completed"); --- 156,163 ---- println(request.dump()); pw.println(request.dump()); ! FetchData fetchData = request.fetchData(); ! println("==Data fetched. " + fetchData.getRowCount() + " points obtained"); ! for(int i = 0; i < fetchData.getRowCount(); i++) { ! println(fetchData.getRow(i).dump()); } println("==Fetch completed"); *************** *** 209,212 **** --- 210,215 ---- println("==Saving graph as JPEG file " + jpegPath); graph.saveAsJPEG(jpegPath, 400, 250, 0.5F); + println("==Saving graph as GIF file " + gifPath); + graph.saveAsGIF(gifPath, 400, 250); // demo ends |
From: <sa...@us...> - 2003-10-28 14:54:11
|
Update of /cvsroot/jrobin/src/jrobin/graph In directory sc8-pr-cvs1:/tmp/cvs-serv28252/jrobin/graph Modified Files: Grapher.java RrdGraph.java Added Files: GifEncoder.java Log Message: GIF Encoder --- NEW FILE: GifEncoder.java --- package jrobin.graph; import java.awt.*; import java.awt.image.PixelGrabber; import java.io.*; import java.util.Vector; // thanks to J. M. G. Elliott // http://jmge.net/java/gifenc/ class Gif89Encoder { private Dimension dispDim = new Dimension(0, 0); private GifColorTable colorTable; private int bgIndex = 0; private int loopCount = 1; private String theComments; private Vector vFrames = new Vector(); Gif89Encoder() { colorTable = new GifColorTable(); } Gif89Encoder(Image static_image) throws IOException { this(); addFrame(static_image); } Gif89Encoder(Color[] colors) { colorTable = new GifColorTable(colors); } Gif89Encoder(Color[] colors, int width, int height, byte ci_pixels[]) throws IOException { this(colors); addFrame(width, height, ci_pixels); } int getFrameCount() { return vFrames.size(); } Gif89Frame getFrameAt(int index) { return isOk(index) ? (Gif89Frame) vFrames.elementAt(index) : null; } void addFrame(Gif89Frame gf) throws IOException { accommodateFrame(gf); vFrames.addElement(gf); } void addFrame(Image image) throws IOException { addFrame(new DirectGif89Frame(image)); } void addFrame(int width, int height, byte ci_pixels[]) throws IOException { addFrame(new IndexGif89Frame(width, height, ci_pixels)); } void insertFrame(int index, Gif89Frame gf) throws IOException { accommodateFrame(gf); vFrames.insertElementAt(gf, index); } void setTransparentIndex(int index) { colorTable.setTransparent(index); } void setLogicalDisplay(Dimension dim, int background) { dispDim = new Dimension(dim); bgIndex = background; } void setLoopCount(int count) { loopCount = count; } void setComments(String comments) { theComments = comments; } void setUniformDelay(int interval) { for (int i = 0; i < vFrames.size(); ++i) ((Gif89Frame) vFrames.elementAt(i)).setDelay(interval); } void encode(OutputStream out) throws IOException { int nframes = getFrameCount(); boolean is_sequence = nframes > 1; colorTable.closePixelProcessing(); Put.ascii("GIF89a", out); writeLogicalScreenDescriptor(out); colorTable.encode(out); if (is_sequence && loopCount != 1) writeNetscapeExtension(out); if (theComments != null && theComments.length() > 0) writeCommentExtension(out); for (int i = 0; i < nframes; ++i) ((Gif89Frame) vFrames.elementAt(i)).encode( out, is_sequence, colorTable.getDepth(), colorTable.getTransparent() ); out.write((int) ';'); out.flush(); } private void accommodateFrame(Gif89Frame gf) throws IOException { dispDim.width = Math.max(dispDim.width, gf.getWidth()); dispDim.height = Math.max(dispDim.height, gf.getHeight()); colorTable.processPixels(gf); } private void writeLogicalScreenDescriptor(OutputStream os) throws IOException { Put.leShort(dispDim.width, os); Put.leShort(dispDim.height, os); os.write(0xf0 | colorTable.getDepth() - 1); os.write(bgIndex); os.write(0); } private void writeNetscapeExtension(OutputStream os) throws IOException { os.write((int) '!'); os.write(0xff); os.write(11); Put.ascii("NETSCAPE2.0", os); os.write(3); os.write(1); Put.leShort(loopCount > 1 ? loopCount - 1 : 0, os); os.write(0); } private void writeCommentExtension(OutputStream os) throws IOException { os.write((int) '!'); os.write(0xfe); int remainder = theComments.length() % 255; int nsubblocks_full = theComments.length() / 255; int nsubblocks = nsubblocks_full + (remainder > 0 ? 1 : 0); int ibyte = 0; for (int isb = 0; isb < nsubblocks; ++isb) { int size = isb < nsubblocks_full ? 255 : remainder; os.write(size); Put.ascii(theComments.substring(ibyte, ibyte + size), os); ibyte += size; } os.write(0); } private boolean isOk(int frame_index) { return frame_index >= 0 && frame_index < vFrames.size(); } } class DirectGif89Frame extends Gif89Frame { private int[] argbPixels; DirectGif89Frame(Image img) throws IOException { PixelGrabber pg = new PixelGrabber(img, 0, 0, -1, -1, true); String errmsg = null; try { if (!pg.grabPixels()) errmsg = "can't grab pixels from image"; } catch (InterruptedException e) { errmsg = "interrupted grabbing pixels from image"; } if (errmsg != null) throw new IOException(errmsg + " (" + getClass().getName() + ")"); theWidth = pg.getWidth(); theHeight = pg.getHeight(); argbPixels = (int[]) pg.getPixels(); ciPixels = new byte[argbPixels.length]; } DirectGif89Frame(int width, int height, int argb_pixels[]) { theWidth = width; theHeight = height; argbPixels = new int[theWidth * theHeight]; System.arraycopy(argb_pixels, 0, argbPixels, 0, argbPixels.length); ciPixels = new byte[argbPixels.length]; } Object getPixelSource() { return argbPixels; } } class GifColorTable { private int[] theColors = new int[256]; private int colorDepth; private int transparentIndex = -1; private int ciCount = 0; private ReverseColorMap ciLookup; GifColorTable() { ciLookup = new ReverseColorMap(); } GifColorTable(Color[] colors) { int n2copy = Math.min(theColors.length, colors.length); for (int i = 0; i < n2copy; ++i) theColors[i] = colors[i].getRGB(); } int getDepth() { return colorDepth; } int getTransparent() { return transparentIndex; } void setTransparent(int color_index) { transparentIndex = color_index; } void processPixels(Gif89Frame gf) throws IOException { if (gf instanceof DirectGif89Frame) filterPixels((DirectGif89Frame) gf); else trackPixelUsage((IndexGif89Frame) gf); } void closePixelProcessing() { colorDepth = computeColorDepth(ciCount); } void encode(OutputStream os) throws IOException { int palette_size = 1 << colorDepth; for (int i = 0; i < palette_size; ++i) { os.write(theColors[i] >> 16 & 0xff); os.write(theColors[i] >> 8 & 0xff); os.write(theColors[i] & 0xff); } } private void filterPixels(DirectGif89Frame dgf) throws IOException { if (ciLookup == null) throw new IOException("RGB frames require palette autodetection"); int[] argb_pixels = (int[]) dgf.getPixelSource(); byte[] ci_pixels = dgf.getPixelSink(); int npixels = argb_pixels.length; for (int i = 0; i < npixels; ++i) { int argb = argb_pixels[i]; if ((argb >>> 24) < 0x80) if (transparentIndex == -1) transparentIndex = ciCount; else if (argb != theColors[transparentIndex]) { ci_pixels[i] = (byte) transparentIndex; continue; } int color_index = ciLookup.getPaletteIndex(argb & 0xffffff); if (color_index == -1) { if (ciCount == 256) throw new IOException("can't encode as GIF (> 256 colors)"); theColors[ciCount] = argb; ciLookup.put(argb & 0xffffff, ciCount); ci_pixels[i] = (byte) ciCount; ++ciCount; } else ci_pixels[i] = (byte) color_index; } } private void trackPixelUsage(IndexGif89Frame igf) { byte[] ci_pixels = (byte[]) igf.getPixelSource(); int npixels = ci_pixels.length; for (int i = 0; i < npixels; ++i) if (ci_pixels[i] >= ciCount) ciCount = ci_pixels[i] + 1; } private int computeColorDepth(int colorcount) { if (colorcount <= 2) return 1; if (colorcount <= 4) return 2; if (colorcount <= 16) return 4; return 8; } } class ReverseColorMap { private static class ColorRecord { int rgb; int ipalette; ColorRecord(int rgb, int ipalette) { this.rgb = rgb; this.ipalette = ipalette; } } private static final int HCAPACITY = 2053; private ColorRecord[] hTable = new ColorRecord[HCAPACITY]; int getPaletteIndex(int rgb) { ColorRecord rec; for (int itable = rgb % hTable.length; (rec = hTable[itable]) != null && rec.rgb != rgb; itable = ++itable % hTable.length ) ; if (rec != null) return rec.ipalette; return -1; } void put(int rgb, int ipalette) { int itable; for (itable = rgb % hTable.length; hTable[itable] != null; itable = ++itable % hTable.length ) ; hTable[itable] = new ColorRecord(rgb, ipalette); } } abstract class Gif89Frame { static final int DM_UNDEFINED = 0; static final int DM_LEAVE = 1; static final int DM_BGCOLOR = 2; static final int DM_REVERT = 3; int theWidth = -1; int theHeight = -1; byte[] ciPixels; private Point thePosition = new Point(0, 0); private boolean isInterlaced; private int csecsDelay; private int disposalCode = DM_LEAVE; void setPosition(Point p) { thePosition = new Point(p); } void setInterlaced(boolean b) { isInterlaced = b; } void setDelay(int interval) { csecsDelay = interval; } void setDisposalMode(int code) { disposalCode = code; } Gif89Frame() { } abstract Object getPixelSource(); int getWidth() { return theWidth; } int getHeight() { return theHeight; } byte[] getPixelSink() { return ciPixels; } void encode(OutputStream os, boolean epluribus, int color_depth, int transparent_index) throws IOException { writeGraphicControlExtension(os, epluribus, transparent_index); writeImageDescriptor(os); new GifPixelsEncoder( theWidth, theHeight, ciPixels, isInterlaced, color_depth ).encode(os); } private void writeGraphicControlExtension(OutputStream os, boolean epluribus, int itransparent) throws IOException { int transflag = itransparent == -1 ? 0 : 1; if (transflag == 1 || epluribus) { os.write((int) '!'); os.write(0xf9); os.write(4); os.write((disposalCode << 2) | transflag); Put.leShort(csecsDelay, os); os.write(itransparent); os.write(0); } } private void writeImageDescriptor(OutputStream os) throws IOException { os.write((int) ','); Put.leShort(thePosition.x, os); Put.leShort(thePosition.y, os); Put.leShort(theWidth, os); Put.leShort(theHeight, os); os.write(isInterlaced ? 0x40 : 0); } } class GifPixelsEncoder { private static final int EOF = -1; private int imgW, imgH; private byte[] pixAry; private boolean wantInterlaced; private int initCodeSize; private int countDown; private int xCur, yCur; private int curPass; GifPixelsEncoder(int width, int height, byte[] pixels, boolean interlaced, int color_depth) { imgW = width; imgH = height; pixAry = pixels; wantInterlaced = interlaced; initCodeSize = Math.max(2, color_depth); } void encode(OutputStream os) throws IOException { os.write(initCodeSize); countDown = imgW * imgH; xCur = yCur = curPass = 0; compress(initCodeSize + 1, os); os.write(0); } private void bumpPosition() { ++xCur; if (xCur == imgW) { xCur = 0; if (!wantInterlaced) ++yCur; else switch (curPass) { case 0: yCur += 8; if (yCur >= imgH) { ++curPass; yCur = 4; } break; case 1: yCur += 8; if (yCur >= imgH) { ++curPass; yCur = 2; } break; case 2: yCur += 4; if (yCur >= imgH) { ++curPass; yCur = 1; } break; case 3: yCur += 2; break; } } } private int nextPixel() { if (countDown == 0) return EOF; --countDown; byte pix = pixAry[yCur * imgW + xCur]; bumpPosition(); return pix & 0xff; } static final int BITS = 12; static final int HSIZE = 5003; int n_bits; int maxbits = BITS; int maxcode; int maxmaxcode = 1 << BITS; final int MAXCODE(int n_bits) { return (1 << n_bits) - 1; } int[] htab = new int[HSIZE]; int[] codetab = new int[HSIZE]; int hsize = HSIZE; int free_ent = 0; boolean clear_flg = false; int g_init_bits; int ClearCode; int EOFCode; void compress(int init_bits, OutputStream outs) throws IOException { int fcode; int i /* = 0 */; int c; int ent; int disp; int hsize_reg; int hshift; g_init_bits = init_bits; clear_flg = false; n_bits = g_init_bits; maxcode = MAXCODE(n_bits); ClearCode = 1 << (init_bits - 1); EOFCode = ClearCode + 1; free_ent = ClearCode + 2; char_init(); ent = nextPixel(); hshift = 0; for (fcode = hsize; fcode < 65536; fcode *= 2) ++hshift; hshift = 8 - hshift; hsize_reg = hsize; cl_hash(hsize_reg); output(ClearCode, outs); outer_loop: while ((c = nextPixel()) != EOF) { fcode = (c << maxbits) + ent; i = (c << hshift) ^ ent; if (htab[i] == fcode) { ent = codetab[i]; continue; } else if (htab[i] >= 0) { disp = hsize_reg - i; if (i == 0) disp = 1; do { if ((i -= disp) < 0) i += hsize_reg; if (htab[i] == fcode) { ent = codetab[i]; continue outer_loop; } } while (htab[i] >= 0); } output(ent, outs); ent = c; if (free_ent < maxmaxcode) { codetab[i] = free_ent++; htab[i] = fcode; } else cl_block(outs); } output(ent, outs); output(EOFCode, outs); } int cur_accum = 0; int cur_bits = 0; int masks[] = {0x0000, 0x0001, 0x0003, 0x0007, 0x000F, 0x001F, 0x003F, 0x007F, 0x00FF, 0x01FF, 0x03FF, 0x07FF, 0x0FFF, 0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF}; void output(int code, OutputStream outs) throws IOException { cur_accum &= masks[cur_bits]; if (cur_bits > 0) cur_accum |= (code << cur_bits); else cur_accum = code; cur_bits += n_bits; while (cur_bits >= 8) { char_out((byte) (cur_accum & 0xff), outs); cur_accum >>= 8; cur_bits -= 8; } if (free_ent > maxcode || clear_flg) { if (clear_flg) { maxcode = MAXCODE(n_bits = g_init_bits); clear_flg = false; } else { ++n_bits; if (n_bits == maxbits) maxcode = maxmaxcode; else maxcode = MAXCODE(n_bits); } } if (code == EOFCode) { while (cur_bits > 0) { char_out((byte) (cur_accum & 0xff), outs); cur_accum >>= 8; cur_bits -= 8; } flush_char(outs); } } void cl_block(OutputStream outs) throws IOException { cl_hash(hsize); free_ent = ClearCode + 2; clear_flg = true; output(ClearCode, outs); } void cl_hash(int hsize) { for (int i = 0; i < hsize; ++i) htab[i] = -1; } int a_count; void char_init() { a_count = 0; } byte[] accum = new byte[256]; void char_out(byte c, OutputStream outs) throws IOException { accum[a_count++] = c; if (a_count >= 254) flush_char(outs); } void flush_char(OutputStream outs) throws IOException { if (a_count > 0) { outs.write(a_count); outs.write(accum, 0, a_count); a_count = 0; } } } class IndexGif89Frame extends Gif89Frame { IndexGif89Frame(int width, int height, byte ci_pixels[]) { theWidth = width; theHeight = height; ciPixels = new byte[theWidth * theHeight]; System.arraycopy(ci_pixels, 0, ciPixels, 0, ciPixels.length); } Object getPixelSource() { return ciPixels; } } final class Put { static void ascii(String s, OutputStream os) throws IOException { byte[] bytes = new byte[s.length()]; for (int i = 0; i < bytes.length; ++i) bytes[i] = (byte) s.charAt(i); os.write(bytes); } static void leShort(int i16, OutputStream os) throws IOException { os.write(i16 & 0xff); os.write(i16 >> 8 & 0xff); } } Index: Grapher.java =================================================================== RCS file: /cvsroot/jrobin/src/jrobin/graph/Grapher.java,v retrieving revision 1.10 retrieving revision 1.11 diff -C2 -d -r1.10 -r1.11 *** Grapher.java 21 Oct 2003 19:41:59 -0000 1.10 --- Grapher.java 28 Oct 2003 14:51:39 -0000 1.11 *************** *** 133,137 **** // Create the buffered image, get the graphics handle ! BufferedImage bImg = new BufferedImage( imgWidth, imgHeight, BufferedImage.TYPE_INT_RGB ); Graphics2D graphics = (Graphics2D) bImg.getGraphics(); --- 133,138 ---- // Create the buffered image, get the graphics handle ! // BufferedImage bImg = new BufferedImage( imgWidth, imgHeight, BufferedImage.TYPE_INT_RGB); ! BufferedImage bImg = new BufferedImage( imgWidth, imgHeight, BufferedImage.TYPE_BYTE_INDEXED); Graphics2D graphics = (Graphics2D) bImg.getGraphics(); Index: RrdGraph.java =================================================================== RCS file: /cvsroot/jrobin/src/jrobin/graph/RrdGraph.java,v retrieving revision 1.8 retrieving revision 1.9 diff -C2 -d -r1.8 -r1.9 *** RrdGraph.java 27 Oct 2003 21:03:33 -0000 1.8 --- RrdGraph.java 28 Oct 2003 14:51:39 -0000 1.9 *************** *** 29,36 **** import java.util.*; ! import java.io.ByteArrayOutputStream; ! import java.io.File; ! import java.io.IOException; ! import java.io.Serializable; import jrobin.core.Util; --- 29,33 ---- import java.util.*; ! import java.io.*; import jrobin.core.Util; *************** *** 43,47 **** * is an excellent free Java library for generating charts and graphs.</p> */ ! public class RrdGraph implements Serializable { private Grapher grapher; --- 40,44 ---- * is an excellent free Java library for generating charts and graphs.</p> */ ! public class RrdGraph implements Serializable { private Grapher grapher; *************** *** 54,62 **** * @throws RrdException Thrown in case of JRobin specific error. */ ! public RrdGraph(RrdGraphDef graphDef) throws IOException, RrdException { grapher = new Grapher( graphDef ); } ! /** --- 51,59 ---- * @throws RrdException Thrown in case of JRobin specific error. */ ! public RrdGraph(RrdGraphDef graphDef) throws IOException, RrdException { grapher = new Grapher( graphDef ); } ! /** *************** *** 68,74 **** // Check, if width/height has changed since last generation // Regenerate the graph ! public BufferedImage getBufferedImage(int width, int height) { ! try { if ( img != null ) --- 65,71 ---- // Check, if width/height has changed since last generation // Regenerate the graph ! public BufferedImage getBufferedImage(int width, int height) { ! try { if ( img != null ) *************** *** 83,87 **** e.printStackTrace(); } ! return null; } --- 80,84 ---- e.printStackTrace(); } ! return null; } *************** *** 94,98 **** * @throws IOException Thrown in case of I/O error. */ ! public void saveAsPNG(String path, int width, int height) throws IOException { Util.time(); --- 91,95 ---- * @throws IOException Thrown in case of I/O error. */ ! public void saveAsPNG(String path, int width, int height) throws IOException { Util.time(); *************** *** 101,107 **** ImageIO.write( r, "png", new File(path) ); Util.time(5); ! } ! /** * Saves graph in JPEG format --- 98,104 ---- ImageIO.write( r, "png", new File(path) ); Util.time(5); ! } ! /** * Saves graph in JPEG format *************** *** 112,116 **** * @throws IOException Thrown in case of I/O error. */ ! public void saveAsJPEG(String path, int width, int height, float quality) throws IOException { // Based on http://javaalmanac.com/egs/javax.imageio/JpegWrite.html?l=rel --- 109,113 ---- * @throws IOException Thrown in case of I/O error. */ ! public void saveAsJPEG(String path, int width, int height, float quality) throws IOException { // Based on http://javaalmanac.com/egs/javax.imageio/JpegWrite.html?l=rel *************** *** 119,123 **** BufferedImage gImage = getBufferedImage(width, height); RenderedImage rndImage = (RenderedImage) gImage; ! // Find a jpeg writer ImageWriter writer = null; --- 116,120 ---- BufferedImage gImage = getBufferedImage(width, height); RenderedImage rndImage = (RenderedImage) gImage; ! // Find a jpeg writer ImageWriter writer = null; *************** *** 143,151 **** writer.dispose(); ios.close(); ! } catch (Exception e) { e.printStackTrace(); } } --- 140,172 ---- writer.dispose(); ios.close(); ! } catch (Exception e) { e.printStackTrace(); } + } + + public void saveAsGIF(String path, int width, int height) { + BufferedImage image = getBufferedImage(width, height); + try { + Gif89Encoder gifEncoder = new Gif89Encoder(image); + FileOutputStream stream = new FileOutputStream(path, false); + gifEncoder.encode(stream); + stream.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + public byte[] getGIFBytes(int width, int height) { + BufferedImage image = getBufferedImage(width, height); + ByteArrayOutputStream bStream = new ByteArrayOutputStream(); + try { + Gif89Encoder gifEncoder = new Gif89Encoder(image); + gifEncoder.encode(bStream); + } catch (IOException e) { + e.printStackTrace(); + } + return bStream.toByteArray(); } |
From: <cob...@us...> - 2003-10-27 21:06:31
|
Update of /cvsroot/jrobin/src/jrobin/graph In directory sc8-pr-cvs1:/tmp/cvs-serv17805/src/jrobin/graph Modified Files: RrdGraph.java Log Message: New graph lib Finetuning Javadoc Added RrdDbPool Added JRobinComplexDemo Index: RrdGraph.java =================================================================== RCS file: /cvsroot/jrobin/src/jrobin/graph/RrdGraph.java,v retrieving revision 1.7 retrieving revision 1.8 diff -C2 -d -r1.7 -r1.8 *** RrdGraph.java 21 Oct 2003 19:41:59 -0000 1.7 --- RrdGraph.java 27 Oct 2003 21:03:33 -0000 1.8 *************** *** 20,24 **** * Boston, MA 02111-1307, USA. */ - package jrobin.graph; --- 20,23 ---- |
Update of /cvsroot/jrobin/src/jrobin/graph2 In directory sc8-pr-cvs1:/tmp/cvs-serv17805/src/jrobin/graph2 Modified Files: FetchSource.java RpnCalculator.java ValueAxisUnit.java Title.java Area.java ChartGraphics.java RrdGraphDef.java Gprint.java RrdGraph.java Comment.java Cdef.java TimeGrid.java Source.java ValueGrid.java CustomLine.java GridRange.java TimeMarker.java Stack.java TimeAxisUnit.java Legend.java ValueMarker.java ValueExtractor.java Grapher.java CustomArea.java LegendMarker.java Def.java PlotDef.java Line.java ValueFormatter.java Added Files: ChartPanel.java JpegImageWriteParam.java Log Message: New graph lib Finetuning Javadoc Added RrdDbPool Added JRobinComplexDemo --- NEW FILE: ChartPanel.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 jrobin.graph2; import java.awt.Graphics; import java.awt.image.BufferedImage; import javax.swing.JPanel; /** * <p>JPanel containing the graph.</p> * * @author Arne Vandamme (cob...@jr...) */ public class ChartPanel extends JPanel { private BufferedImage chart; void setChart( BufferedImage chart ) { this.chart = chart; } public void paintComponent( Graphics g ) { if ( chart != null ) g.drawImage( chart, 0, 0, null ); } } --- NEW FILE: JpegImageWriteParam.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 jrobin.graph2; /** * <i>Based on http://javaalmanac.com/egs/javax.imageio/JpegWrite.html?l=rel</i> * <p>JPEG creation parameters.</p> * @author Arne Vandamme (cob...@jr...) */ import java.util.Locale; import javax.imageio.plugins.jpeg.JPEGImageWriteParam;; public class JpegImageWriteParam extends JPEGImageWriteParam { public JpegImageWriteParam() { super(Locale.getDefault()); } // This method accepts quality levels between 0 (lowest) and 1 (highest) and simply converts // it to a range between 0 and 256 public void setCompressionQuality( float quality ) { if (quality < 0.0F || quality > 1.0F) { throw new IllegalArgumentException("Quality out-of-bounds!"); } this.compressionQuality = (quality * 256); } } Index: FetchSource.java =================================================================== RCS file: /cvsroot/jrobin/src/jrobin/graph2/FetchSource.java,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** FetchSource.java 23 Oct 2003 23:16:35 -0000 1.2 --- FetchSource.java 27 Oct 2003 21:03:32 -0000 1.3 *************** *** 34,66 **** /** ! * <p>Class used to group datasources per RRD db, for faster fetching.</p> * ! * @author Arne Vandamme (arn...@jr...) */ class FetchSource { ! static final int AVG = 0; ! static final int MAX = 1; ! static final int MIN = 2; ! static final int LAST = 3; ! static final int MAX_CF = 4; ! static final String[] cfNames = new String[] { "AVERAGE", "MAX", "MIN", "LAST" }; private String rrdFile; // Holds the name of the RRD file ! private int numSources = 0; ! private Vector[] datasources = new Vector[MAX_CF]; protected FetchSource( String rrdFile ) { this.rrdFile = rrdFile; ! // Initialization for (int i = 0; i < datasources.length; i++) datasources[i] = new Vector(); } ! protected FetchSource( String rrdFile, String consolFunc, String dsName, String name ) throws RrdException { this( rrdFile ); --- 34,90 ---- /** ! * <p>Class used to group datasources per RRD db, for faster fetching. ! * A FetchSource represents one RRD database file, and will take care of all datasource ! * fetching using objects of the <code>core</code> package. Fetching will be done in such ! * a way that all datasources per consolidation function are fetched with the minimum possible ! * file reads.</p> * ! * @author Arne Vandamme (cob...@jr...) */ class FetchSource { ! // ================================================================ ! // -- Members ! // ================================================================ ! protected static final int AVG = 0; ! protected static final int MAX = 1; ! protected static final int MIN = 2; ! protected static final int LAST = 3; ! protected static final int MAX_CF = 4; ! protected static final String[] cfNames = new String[] { "AVERAGE", "MAX", "MIN", "LAST" }; private String rrdFile; // Holds the name of the RRD file ! private int numSources = 0; ! private Vector[] datasources = new Vector[MAX_CF]; ! + // ================================================================ + // -- Constructors + // ================================================================ + /** + * Constructs a FetchSource object based on a RRD file name. + * @param rrdFile Name of the RRD file holding all datasources. + */ protected FetchSource( String rrdFile ) { this.rrdFile = rrdFile; ! // Initialization of datasource lists per CF for (int i = 0; i < datasources.length; i++) datasources[i] = new Vector(); } ! /** ! * Constructs a FetchSource object based on a RRD file name, and ! * adds a given datasource to the datasources list. ! * @param rrdFile Name of the RRD file holding all datasources. ! * @param consolFunc Consolidation function of the datasource to fetch. ! * @param dsName Internal name of the datasource in the RRD file. ! * @param name Variable name of the datasource in the graph definition. ! * @throws RrdException Thrown in case of a JRobin specific error. ! */ ! FetchSource( String rrdFile, String consolFunc, String dsName, String name ) throws RrdException { this( rrdFile ); *************** *** 68,71 **** --- 92,106 ---- } + + // ================================================================ + // -- Protected methods + // ================================================================ + /** + * Adds a given datasource to the datasources list for this FetchSource. + * @param consolFunc Consolidation function of the datasource to fetch. + * @param dsName Internal name of the datasource in the RRD file. + * @param name Variable name of the datasource in the graph definition. + * @throws RrdException Thrown in case of a JRobin specific error. + */ protected void addSource( String consolFunc, String dsName, String name ) throws RrdException { *************** *** 84,91 **** } ! protected String getRrdFile() { ! return rrdFile; ! } ! protected ValueExtractor fetch ( RrdDb rrd, long startTime, long endTime ) throws IOException, RrdException { --- 119,131 ---- } ! /** ! * Fetches all datavalues for a given timespan out of the provided RRD file. ! * @param rrd An open <code>RrdDb</code> object holding the necessary datasources. ! * @param startTime Start time of the given timespan. ! * @param endTime End time of the given timespan. ! * @return A <code>ValueExtractor</code> object holding all fetched data. ! * @throws IOException Thrown in case of fetching I/O error. ! * @throws RrdException Thrown in case of a JRobin specific error. ! */ protected ValueExtractor fetch ( RrdDb rrd, long startTime, long endTime ) throws IOException, RrdException { *************** *** 104,108 **** for (int j = 0; j < dsNames.length; j++ ) { ! String[] spair = (String[])datasources[i].elementAt(j); dsNames[j] = spair[0]; vNames[j] = spair[1]; --- 144,148 ---- for (int j = 0; j < dsNames.length; j++ ) { ! String[] spair = (String[]) datasources[i].elementAt(j); dsNames[j] = spair[0]; vNames[j] = spair[1]; *************** *** 125,128 **** return new ValueExtractor( names, result ); } ! } --- 165,171 ---- return new ValueExtractor( names, result ); } ! ! protected String getRrdFile() { ! return rrdFile; ! } } Index: RpnCalculator.java =================================================================== RCS file: /cvsroot/jrobin/src/jrobin/graph2/RpnCalculator.java,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** RpnCalculator.java 22 Oct 2003 21:06:53 -0000 1.2 --- RpnCalculator.java 27 Oct 2003 21:03:32 -0000 1.3 *************** *** 33,41 **** * <p>Used to calculate result of an RPN expression.</p> * ! * @author Arne Vandamme (arn...@jr...) * @author Sasa Markovic (sa...@jr...) */ public class RpnCalculator { // Token definitions public static final byte TKN_CONSTANT = 0; --- 33,44 ---- * <p>Used to calculate result of an RPN expression.</p> * ! * @author Arne Vandamme (cob...@jr...) * @author Sasa Markovic (sa...@jr...) */ public class RpnCalculator { + // ================================================================ + // -- Members + // ================================================================ // Token definitions public static final byte TKN_CONSTANT = 0; *************** *** 80,85 **** private Source[] sources; ! ArrayList stack = new ArrayList(); RpnCalculator( Source[] sources ) { --- 83,96 ---- private Source[] sources; ! private ArrayList stack = new ArrayList(); ! + // ================================================================ + // -- Constructors + // ================================================================ + /** + * Constructs a RPN calculator object by providing the source array to use for value lookups. + * @param sources Table containing all retrieved datasources of the graph definition. + */ RpnCalculator( Source[] sources ) { *************** *** 87,97 **** } ! double evaluate( Cdef cdef, int row, long timestamp ) throws RrdException { stack.clear(); ! byte[] tokens = cdef.tokens; ! int[] dsIndices = cdef.dsIndices; ! double[] constants = cdef.constants; double x1, x2, x3; --- 98,120 ---- } ! ! // ================================================================ ! // -- Public methods ! // ================================================================ ! /** ! * Evaluates a Cdef RPN expression into a single value. ! * @param cdef Cdef object representing the parsed RPN expression. ! * @param row Row index in the source table to retrieve all necessary values. ! * @param timestamp Timestamp of the datapoint for which the value should be calculated. ! * @return Calculated double value of the requested datapoint. ! * @throws RrdException Thrown in case of a JRobin specific error. ! */ ! public double evaluate( Cdef cdef, int row, long timestamp ) throws RrdException { stack.clear(); ! byte[] tokens = cdef.getTokens(); ! int[] dsIndices = cdef.getDsIndices(); ! double[] constants = cdef.getConstants(); double x1, x2, x3; *************** *** 298,301 **** --- 321,332 ---- } + + // ================================================================ + // -- Private methods + // ================================================================ + /** + * Pushes as a double value on the internal stack. + * @param value Value to push on the stack. + */ private void push( double value ) { *************** *** 303,306 **** --- 334,342 ---- } + /** + * Pops a double value off the internal stack. + * @return Value popped off the stack. + * @throws RrdException Thrown in case of a JRobin specific error. + */ private double pop() throws RrdException { Index: ValueAxisUnit.java =================================================================== RCS file: /cvsroot/jrobin/src/jrobin/graph2/ValueAxisUnit.java,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** ValueAxisUnit.java 24 Oct 2003 21:15:33 -0000 1.2 --- ValueAxisUnit.java 27 Oct 2003 21:03:32 -0000 1.3 *************** *** 31,41 **** /** ! * @author cbld ! * ! * To change the template for this generated type comment go to ! * Window - Preferences - Java - Code Generation - Code and Comments */ ! public class ValueAxisUnit { private double labelStep = 2; private double markStep = 1; --- 31,43 ---- /** ! * <p>Class used to determine the chart grid shown on the Y (value) axis.</p> ! * ! * @author Arne Vandamme (cob...@jr...) */ ! class ValueAxisUnit { + // ================================================================ + // -- Members + // ================================================================ private double labelStep = 2; private double markStep = 1; *************** *** 45,48 **** --- 47,61 ---- private double mGridStep = 10; + + // ================================================================ + // -- Constructors + // ================================================================ + /** + * Creates a ValueAxisUnit based on a minor and major grid step. + * Minor grid lines appear at <code>gridStep</code>, major grid lines accompanied by a label + * will appear every <code>labelStep</code> value. + * @param gridStep Value step on which a minor grid line will appear. + * @param labelStep Value step on which a major grid line with value label will appear. + */ ValueAxisUnit( double gridStep, double labelStep ) { *************** *** 51,65 **** } - private double round( double value ) - { - return round( value, 14 ); // Big precision - } ! private double round( double value, int numDecs ) ! { ! return new java.math.BigDecimal(value).setScale(numDecs , java.math.BigDecimal.ROUND_HALF_EVEN).doubleValue(); ! } ! ! protected ValueMarker[] getValueMarkers( double lower, double upper ) { double minPoint = 0.0d; --- 64,79 ---- } ! // ================================================================ ! // -- Protected methods ! // ================================================================ ! /** ! * Returns a set of markers making up the grid for the Y axis. ! * All markers are situated in a given value range. ! * @param lower Lower value of the value range. ! * @param upper Upper value of the value range. ! * @return List of markers as a ValueMarker array. ! */ ! ValueMarker[] getValueMarkers( double lower, double upper ) { double minPoint = 0.0d; *************** *** 119,124 **** return (ValueMarker[]) markerList.toArray( new ValueMarker[0] ); } ! ! public double getNiceLower( double ovalue ) { // Add some checks --- 133,144 ---- return (ValueMarker[]) markerList.toArray( new ValueMarker[0] ); } ! ! /** ! * Gets a rounded value that's slightly below the given exact value. ! * The rounding is based on the given grid specifications of the axis. ! * @param ovalue Original exact value. ! * @return Rounded value lower than the given exact value. ! */ ! double getNiceLower( double ovalue ) { // Add some checks *************** *** 174,178 **** } ! public double getNiceHigher( double ovalue ) { // Add some checks --- 194,204 ---- } ! /** ! * Gets a rounded value that's slightly above the given exact value. ! * The rounding is based on the given grid specifications of the axis. ! * @param ovalue Original exact value. ! * @return Rounded value higher than the given exact value. ! */ ! double getNiceHigher( double ovalue ) { // Add some checks *************** *** 219,222 **** --- 245,274 ---- return ovalue; + } + + + // ================================================================ + // -- Private methods + // ================================================================ + /** + * Rounds a specific double value to 14 decimals. This is used to avoid strange double values due to the + * internal double representation of the JVM. + * @param value Original value to round. + * @return Value rounded to 14 decimals. + */ + private double round( double value ) + { + return round( value, 14 ); // Big precision + } + + /** + * Rounds a specific double value to a given number of decimals. + * @param value Original value to round. + * @param numDecs Number of decimals to round the value to. + * @return Value rounded to given number of decimals. + */ + private double round( double value, int numDecs ) + { + return new java.math.BigDecimal(value).setScale(numDecs , java.math.BigDecimal.ROUND_HALF_EVEN).doubleValue(); } } Index: Title.java =================================================================== RCS file: /cvsroot/jrobin/src/jrobin/graph2/Title.java,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** Title.java 21 Oct 2003 19:41:58 -0000 1.1 --- Title.java 27 Oct 2003 21:03:32 -0000 1.2 *************** *** 28,38 **** /** ! * <p>description</p> * ! * @author Arne Vandamme (arn...@jr...) ! * @author Sasa Markovic (sa...@jr...) */ class Title extends Comment { Title( String text ) throws RrdException { --- 28,46 ---- /** ! * <p>Represents the Title used in the graph. The title object has the same alignment ! * possibilities as all other text/comment objects in a graph.</p> * ! * @author Arne Vandamme (cob...@jr...) */ class Title extends Comment { + // ================================================================ + // -- Constructors + // ================================================================ + /** + * Constructs a Title object based on a text string. + * @param text Text string with alignment markers representing the title. + * @throws RrdException Thrown in case of a JRobin specific error. + */ Title( String text ) throws RrdException { Index: Area.java =================================================================== RCS file: /cvsroot/jrobin/src/jrobin/graph2/Area.java,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** Area.java 22 Oct 2003 21:06:53 -0000 1.2 --- Area.java 27 Oct 2003 21:03:32 -0000 1.3 *************** *** 28,52 **** /** ! * <p>description</p> * ! * @author Arne Vandamme (arn...@jr...) */ class Area extends PlotDef { ! Area( String sourceName, Color c ) { ! super( sourceName, c ); this.plotType = PlotDef.PLOT_AREA; } ! Area( Source source, Color c, boolean stacked, boolean visible ) { ! super( source, c, stacked, visible ); } void draw( ChartGraphics g, int[] xValues, int[] stackValues, int lastPlotType ) { g.setColor( color ); int ax = 0, ay = 0, py; int nx = 0, ny = 0, last = -1; --- 28,82 ---- /** ! * <p>Class used to represent a datasource plotted as an area in a graph.</p> * ! * @author Arne Vandamme (cob...@jr...) */ class Area extends PlotDef { ! // ================================================================ ! // -- Constructors ! // ================================================================ ! /** ! * Constructs a <code>Area</code> PlotDef object based on a datasource name and a graph color. ! * @param sourceName Name of the graph definition <code>Source</code> containing the datapoints. ! * @param color Color of the resulting area, if no color is specified, the Area will not be drawn. ! */ ! Area( String sourceName, Color color ) { ! super( sourceName, color ); this.plotType = PlotDef.PLOT_AREA; } ! /** ! * Constructs a <code>Area</code> object based on a Source containing all necessary datapoints and ! * a color to draw the resulting graph in. The last two parameters define if the ! * Area should be drawn, and if it is stacked onto a previous PlotDef yes or no. ! * @param source Source containing all datapoints for this Area. ! * @param color Color of the resulting graphed area. ! * @param stacked True if this PlotDef is stacked on the previous one, false if not. ! * @param visible True if this PlotDef should be graphed, false if not. ! */ ! Area( Source source, Color color, boolean stacked, boolean visible ) { ! super( source, color, stacked, visible ); } + + // ================================================================ + // -- Protected methods + // ================================================================ + /** + * Draws the actual Area on the chart. + * @param g ChartGraphics object representing the graphing area. + * @param xValues List of relative chart area X positions corresponding to the datapoints. + * @param stackValues Datapoint values of previous PlotDefs, used to stack on if necessary. + * @param lastPlotType Type of the previous PlotDef, used to determine PlotDef type of a stack. + */ void draw( ChartGraphics g, int[] xValues, int[] stackValues, int lastPlotType ) { g.setColor( color ); + double[] values = source.getValues(); + int ax = 0, ay = 0, py; int nx = 0, ny = 0, last = -1; *************** *** 57,61 **** nx = xValues[i]; ! ny = g.getY( source.values[i] ); if ( stacked ) { --- 87,91 ---- nx = xValues[i]; ! ny = g.getY( values[i] ); if ( stacked ) { Index: ChartGraphics.java =================================================================== RCS file: /cvsroot/jrobin/src/jrobin/graph2/ChartGraphics.java,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** ChartGraphics.java 22 Oct 2003 21:06:53 -0000 1.2 --- ChartGraphics.java 27 Oct 2003 21:03:32 -0000 1.3 *************** *** 30,40 **** /** ! * <p>description</p> * ! * @author Arne Vandamme (arn...@jr...) */ public class ChartGraphics { ! Graphics2D g; private int width, height; --- 30,45 ---- /** ! * <p>Represent a specific Graphics object holding all specifications of the chart area of the entire graph, ! * including a handle to a Graphics2D context. This class is a wrapper around the graphics context, taking ! * care of some coordinate calculations and translations automatically.</p> * ! * @author Arne Vandamme (cob...@jr...) */ public class ChartGraphics { ! // ================================================================ ! // -- Members ! // ================================================================ ! private Graphics2D g; private int width, height; *************** *** 42,47 **** private double yStart, yEnd; ! double widthDelta = 1.0d, heightDelta = 3.0d; ChartGraphics( Graphics2D graphics ) { --- 47,60 ---- private double yStart, yEnd; ! private double widthDelta = 1.0d, heightDelta = 3.0d; + + // ================================================================ + // -- Constructors + // ================================================================ + /** + * Creates a new <code>ChartGraphics</code> object based on a graphics handle. + * @param graphics Handle of a Graphics2D context to use. + */ ChartGraphics( Graphics2D graphics ) { *************** *** 49,52 **** --- 62,77 ---- } + + // ================================================================ + // -- Protected methods + // ================================================================ + /** + * Draws a line on the graphics context. The line is specified by + * providing begin and end point. + * @param x1 X coordinate of the begin point. + * @param y1 Y coordinate of the begin point. + * @param x2 X coordinate of the end point. + * @param y2 Y coordinate of the end point. + */ void drawLine(int x1, int y1, int x2, int y2) { *************** *** 54,57 **** --- 79,92 ---- } + /** + * Draws a filled rectangle on the graphics context. The rectangle is specified + * by providing two points, bottom-left corner and upper-right corner. This is contrary + * to the general Graphics <code>fillRect</code> method, where the rectangle is specified + * using a single point and a rectangle height and width. + * @param x1 X coordinate of the bottom-left corner. + * @param y1 Y coordinate of the bottom-left corner. + * @param x2 X coordinate of the upper-right corner. + * @param y2 Y coordinate of the upper-right corner. + */ // Contrary to Graphics2D fillRect, this method uses boundary points void fillRect(int x1, int y1, int x2, int y2) *************** *** 60,63 **** --- 95,103 ---- } + /** + * Sets the color of the current brush on the graphics context. + * The next items drawn will be in this color. + * @param c Color to use. + */ void setColor( Color c ) { *************** *** 65,69 **** } ! void setMeasurements( int width, int height ) { this.width = width; --- 105,114 ---- } ! /** ! * Sets the absolute (pixel) dimensions of the chart area to which this object applies. ! * @param width Width of the chart area in pixels. ! * @param height Height of the chart area in pixels. ! */ ! void setDimensions( int width, int height ) { this.width = width; *************** *** 71,74 **** --- 116,124 ---- } + /** + * Sets the timerange specified for the chart, used for scaling down timestamps to fit in the X axis pixel range. + * @param start Start timestamp (in seconds) of the timespan. + * @param end End timestamp (in seconds) of the timespan. + */ void setXRange( long start, long end ) { *************** *** 82,85 **** --- 132,140 ---- } + /** + * Sets the valuerange specified for the chart, used for scaling down values to fit in the Y axis pixel range. + * @param lower Lower value of the range. + * @param upper Upper value of the range. + */ void setYRange( double lower, double upper ) { *************** *** 93,96 **** --- 148,156 ---- } + /** + * Calculates the pixel position on the X axis for a specific timestamp (in seconds). + * @param timestamp Timestamp for which to calculate the corresponding X coordinate. + * @return X coordinate on the horizontal chart axis. + */ int getX( long timestamp ) { *************** *** 98,101 **** --- 158,166 ---- } + /** + * Calculates the pixel position on the Y axis for a specific double value. + * @param value Value for which to calculate the corresponding Y coordinate. + * @return Y coordinate on the horizontal chart axis. + */ int getY( double value ) { *************** *** 107,110 **** --- 172,179 ---- } + /** + * Sets the Stroke to use for graphing on the graphics context. + * @param s Specified <code>Stroke</code> to use. + */ void setStroke( Stroke s ) { *************** *** 112,115 **** --- 181,188 ---- } + /** + * Retrieves the lowest X coordinate of the chart area. + * @return Lowest X coordinate of the chart area. + */ int getMinX() { *************** *** 117,120 **** --- 190,197 ---- } + /** + * Retrieves the highest X coordinate of the chart area. + * @return Highest X coordinate of the chart area. + */ int getMaxX() { *************** *** 122,125 **** --- 199,206 ---- } + /** + * Retrieves the lowest Y coordinate of the chart area. + * @return Lowest Y coordinate of the chart area. + */ int getMinY() { *************** *** 127,133 **** --- 208,227 ---- } + /** + * Retrieves the highest Y coordinate of the chart area. + * @return Highest Y coordinate of the chart area. + */ int getMaxY() { return 0 + height; + } + + /** + * Retrieves the handle of the Graphics2D context for this object. + * @return Handle to the internal Graphics2D context. + */ + Graphics2D getGraphics() + { + return g; } } Index: RrdGraphDef.java =================================================================== RCS file: /cvsroot/jrobin/src/jrobin/graph2/RrdGraphDef.java,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** RrdGraphDef.java 24 Oct 2003 21:15:33 -0000 1.4 --- RrdGraphDef.java 27 Oct 2003 21:03:32 -0000 1.5 *************** *** 646,651 **** * * @param sourceName Graph source name. ! * @param color Line collor to be used. * @param legend Legend to be printed on the graph. * @throws RrdException Thrown if invalid graph source name is supplied. */ --- 646,652 ---- * * @param sourceName Graph source name. ! * @param color Line color to be used. * @param legend Legend to be printed on the graph. + * @param lineWidth Width of the line in pixels. * @throws RrdException Thrown if invalid graph source name is supplied. */ *************** *** 656,659 **** --- 657,671 ---- } + /** + * + * @param t1 + * @param v1 + * @param t2 + * @param v2 + * @param color Line color to be used. + * @param legend Legend to be printed on the graph. + * @param lineWidth Width of the line in pixels. + * @throws RrdException Thrown if invalid graph source name is supplied. + */ public void line( GregorianCalendar t1, double v1, GregorianCalendar t2, double v2, Color color, String legend, int lineWidth ) throws RrdException { *************** *** 680,683 **** --- 692,705 ---- } + /** + * + * @param t1 + * @param v1 + * @param t2 + * @param v2 + * @param color + * @param legend + * @throws RrdException + */ public void area( GregorianCalendar t1, double v1, GregorianCalendar t2, double v2, Color color, String legend ) throws RrdException { Index: Gprint.java =================================================================== RCS file: /cvsroot/jrobin/src/jrobin/graph2/Gprint.java,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** Gprint.java 21 Oct 2003 19:41:58 -0000 1.1 --- Gprint.java 27 Oct 2003 21:03:32 -0000 1.2 *************** *** 32,41 **** /** ! * <p>description</p> * ! * @author Arne Vandamme (arn...@jr...) */ class Gprint extends Comment { private static final String SCALE_MARKER = "@s"; private static final String UNIFORM_SCALE_MARKER = "@S"; --- 32,45 ---- /** ! * <p>Represents a piece of aligned text (containing a retrieved datasource value) to be drawn on the graph.</p> * ! * @author Arne Vandamme (cob...@jr...) ! * @author Sasa Markovic (sa...@jr...) */ class Gprint extends Comment { + // ================================================================ + // -- Members + // ================================================================ private static final String SCALE_MARKER = "@s"; private static final String UNIFORM_SCALE_MARKER = "@S"; *************** *** 50,53 **** --- 54,71 ---- private boolean uniformScale = false; + + // ================================================================ + // -- Constructors + // ================================================================ + /** + * Constructs a Gprint object based on a string of text (with a specific placement + * marker in), a source from which to retrieve a value, and a consolidation function that + * specifies which value to retrieve. Possible consolidation functions are <code>AVERAGE, MAX, MIN, FIRST</code> + * and <code>LAST</code>. + * @param sourceName Name of the datasource from which to retrieve the consolidated value. + * @param consolFunc Consolidation function to use. + * @param text String of text with a placement marker for the resulting value. + * @throws RrdException Thrown in case of a JRobin specific error. + */ Gprint( String sourceName, String consolFunc, String text ) throws RrdException { *************** *** 73,76 **** --- 91,108 ---- } + + // ================================================================ + // -- Protected methods + // ================================================================ + /** + * Sets the consolidated value based on the internal sourceName and consolFunc, and the + * provided list of datasources with lookup table. The retrieved value will be formatted + * to a string using a <code>ValueFormatter</code> object. + * @param sources Source table containing all datasources necessary to create the final graph. + * @param sourceIndex HashMap containing the sourcename - index keypairs, to retrieve the index + * in the Source table based on the sourcename. + * @param vFormat ValueFormatter object used to retrieve a formatted string of the requested value. + * @throws RrdException Thrown in case of a JRobin specific error. + */ void setValue( Source[] sources, HashMap sourceIndex, ValueFormatter vFormat ) throws RrdException { *************** *** 102,112 **** } /** ! * Check value placement by finding placeholder. ! * Check for uniform or regular scaling. ! * Check for the number of decimals and the complete value string length. ! * @throws RrdException */ ! protected void checkValuePlacement() throws RrdException { Matcher m = VALUE_PATTERN.matcher(text); --- 134,147 ---- } + + // ================================================================ + // -- Private methods + // ================================================================ /** ! * Checks value placement by finding placeholder, checks for uniform or regular scaling and ! * checks for the number of decimals to allow and the complete value string length. ! * @throws RrdException Thrown in case of a JRobin specific error. */ ! private void checkValuePlacement() throws RrdException { Matcher m = VALUE_PATTERN.matcher(text); *************** *** 120,126 **** 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 ) --- 155,161 ---- 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 ) *************** *** 131,138 **** } else ! numDec = Integer.parseInt(group[1]); } else ! numDec = Integer.parseInt(group[0]); } else --- 166,173 ---- } else ! numDec = Integer.parseInt(group[1]); } else ! numDec = Integer.parseInt(group[0]); } else Index: RrdGraph.java =================================================================== RCS file: /cvsroot/jrobin/src/jrobin/graph2/RrdGraph.java,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** RrdGraph.java 24 Oct 2003 21:15:33 -0000 1.3 --- RrdGraph.java 27 Oct 2003 21:03:32 -0000 1.4 *************** *** 27,39 **** import javax.swing.JPanel; import java.util.ArrayList; import java.io.File; import java.io.IOException; import java.io.Serializable; import javax.imageio.ImageIO; import java.awt.image.RenderedImage; import java.awt.image.BufferedImage; - import jrobin.core.RrdDb; import jrobin.core.Util; import jrobin.core.RrdException; --- 27,46 ---- import javax.swing.JPanel; import java.util.ArrayList; + import java.util.Iterator; import java.io.File; import java.io.IOException; import java.io.Serializable; + import java.io.ByteArrayOutputStream; import javax.imageio.ImageIO; + import javax.imageio.IIOImage; + import javax.imageio.ImageWriter; + import javax.imageio.ImageWriteParam; + import javax.imageio.stream.ImageOutputStream; import java.awt.image.RenderedImage; import java.awt.image.BufferedImage; import jrobin.core.Util; + import jrobin.core.RrdDb; + import jrobin.core.RrdDbPool; import jrobin.core.RrdException; *************** *** 41,45 **** * <p>Class to represent JRobin graphs. This class needs an appropriate RrdGraphDef to generate graphs.</p> * ! * @author Arne Vandamme (arn...@jr...) * @author Sasa Markovic (sa...@jr...) */ --- 48,52 ---- * <p>Class to represent JRobin graphs. This class needs an appropriate RrdGraphDef to generate graphs.</p> * ! * @author Arne Vandamme (cob...@jr...) * @author Sasa Markovic (sa...@jr...) */ *************** *** 54,57 **** --- 61,66 ---- private BufferedImage img; private ArrayList rrdDbPool; + + private RrdDbPool pool; private int maxPoolSize = DEFAULT_POOLSIZE; *************** *** 62,70 **** // ================================================================ /** ! * Constructs a new JRobin graph object. */ public RrdGraph() { - this( DEFAULT_POOLSIZE ); } --- 71,78 ---- // ================================================================ /** ! * Constructs a new JRobin graph object, without a shared database pool. */ public RrdGraph() { } *************** *** 73,80 **** * @param poolSize Maximum number of concurrent open rrd files in the RrdGraph object. */ ! public RrdGraph( int poolSize ) { ! maxPoolSize = poolSize; ! rrdDbPool = new ArrayList( poolSize ); } --- 81,87 ---- * @param poolSize Maximum number of concurrent open rrd files in the RrdGraph object. */ ! public RrdGraph( RrdDbPool pool ) { ! this.pool = pool; } *************** *** 87,91 **** public RrdGraph( RrdGraphDef graphDef ) throws IOException, RrdException { ! this( graphDef, DEFAULT_POOLSIZE ); } --- 94,98 ---- public RrdGraph( RrdGraphDef graphDef ) throws IOException, RrdException { ! this( graphDef, null ); } *************** *** 97,105 **** * @throws RrdException Thrown in case of JRobin specific error. */ ! public RrdGraph( RrdGraphDef graphDef, int poolSize ) throws IOException, RrdException { ! maxPoolSize = poolSize; ! rrdDbPool = new ArrayList( poolSize ); ! grapher = new Grapher( graphDef, this ); } --- 104,110 ---- * @throws RrdException Thrown in case of JRobin specific error. */ ! public RrdGraph( RrdGraphDef graphDef, RrdDbPool pool ) throws IOException, RrdException { ! this.pool = pool; grapher = new Grapher( graphDef, this ); } *************** *** 154,158 **** * @throws IOException Thrown in case of I/O error. */ ! public void saveAsJPEG( String path, float quality ) throws IOException { saveAsJPEG( path, 0, 0, quality ); --- 159,163 ---- * @throws IOException Thrown in case of I/O error. */ ! public void saveAsJPEG( String path, float quality ) throws RrdException, IOException { saveAsJPEG( path, 0, 0, quality ); *************** *** 168,174 **** * @throws IOException Thrown in case of I/O error. */ ! public void saveAsJPEG( String path, int width, int height, float quality ) throws IOException { ! System.err.println( "Method not implemented..." ); } --- 173,206 ---- * @throws IOException Thrown in case of I/O error. */ ! public void saveAsJPEG( String path, int width, int height, float quality ) throws RrdException, IOException { ! // Based on http://javaalmanac.com/egs/javax.imageio/JpegWrite.html?l=rel ! // Retrieve jpg image to be compressed ! BufferedImage gImage = getBufferedImage(width, height); ! RenderedImage rndImage = (RenderedImage) gImage; ! ! // Find a jpeg writer ! ImageWriter writer = null; ! Iterator iter = ImageIO.getImageWritersByFormatName("jpg"); ! if (iter.hasNext()) { ! writer = (ImageWriter)iter.next(); ! } ! ! // Prepare output file ! ImageOutputStream ios = ImageIO.createImageOutputStream(new File(path)); ! writer.setOutput(ios); ! ! // Set the compression quality ! ImageWriteParam iwparam = new JpegImageWriteParam(); ! iwparam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT) ; ! iwparam.setCompressionQuality(quality); ! ! // Write the image ! writer.write(null, new IIOImage(rndImage, null, null), iwparam); ! ! // Cleanup ! ios.flush(); ! writer.dispose(); ! ios.close(); } *************** *** 180,184 **** * @throws IOException Thrown in case of I/O error. */ ! public byte[] getPNGBytes() throws IOException { return getPNGBytes( 0, 0 ); --- 212,216 ---- * @throws IOException Thrown in case of I/O error. */ ! public byte[] getPNGBytes() throws IOException, RrdException { return getPNGBytes( 0, 0 ); *************** *** 192,199 **** * @throws IOException Thrown in case of I/O error. */ ! public byte[] getPNGBytes( int width, int height ) throws IOException { ! System.err.println( "Method not implemented..." ); ! return null; } --- 224,234 ---- * @throws IOException Thrown in case of I/O error. */ ! public byte[] getPNGBytes( int width, int height ) throws IOException, RrdException { ! ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ! ! ImageIO.write( (RenderedImage) getBufferedImage(width, height), "png", outputStream ); ! ! return outputStream.toByteArray(); } *************** *** 204,208 **** * @throws IOException Thrown in case of I/O error. */ ! public byte[] getJPEGBytes( float quality ) throws IOException { return getJPEGBytes( 0, 0, quality ); --- 239,243 ---- * @throws IOException Thrown in case of I/O error. */ ! public byte[] getJPEGBytes( float quality ) throws IOException, RrdException { return getJPEGBytes( 0, 0, quality ); *************** *** 217,224 **** * @throws IOException Thrown in case of I/O error. */ ! public byte[] getJPEGBytes( int width, int height, float quality ) throws IOException { ! System.err.println( "Method not implemented..." ); ! return null; } --- 252,288 ---- * @throws IOException Thrown in case of I/O error. */ ! public byte[] getJPEGBytes( int width, int height, float quality ) throws IOException, RrdException { ! ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ! ! // Retrieve jpg image to be compressed ! BufferedImage gImage = getBufferedImage(width, height); ! RenderedImage rndImage = (RenderedImage) gImage; ! ! // Find a jpeg writer ! ImageWriter writer = null; ! Iterator iter = ImageIO.getImageWritersByFormatName("jpg"); ! if (iter.hasNext()) { ! writer = (ImageWriter)iter.next(); ! } ! ! // Prepare output file ! ImageOutputStream ios = ImageIO.createImageOutputStream(outputStream); ! writer.setOutput(ios); ! ! // Set the compression quality ! ImageWriteParam iwparam = new JpegImageWriteParam(); ! iwparam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT) ; ! iwparam.setCompressionQuality(quality); ! ! // Write the image ! writer.write(null, new IIOImage(rndImage, null, null), iwparam); ! ! // Cleanup ! ios.flush(); ! writer.dispose(); ! ios.close(); ! ! return outputStream.toByteArray(); } *************** *** 227,254 **** * @return Swing JPanel object with graph embedded in panel. */ ! public JPanel getChartPanel() ! { ! System.err.println( "Method not implemented..." ); ! return null; ! } ! ! /** ! * Closes all open RRD files in the rrd database pool of the object, and removes each file from the pool. ! */ ! public void closeFiles() { ! // Close all RrdDb objects ! for (int i = 0; i < rrdDbPool.size(); i++) { ! try ! { ! ((RrdDb) rrdDbPool.get(i)).close(); ! } ! catch (IOException e) { ! // Ignore this exception, continue trying to close the next RrdDb ! } ! } ! // Empty the pool ! rrdDbPool.clear(); } --- 291,300 ---- * @return Swing JPanel object with graph embedded in panel. */ ! public JPanel getChartPanel() throws RrdException, IOException { ! ChartPanel p = new ChartPanel(); ! p.setChart( getBufferedImage(0, 0) ); ! return p; } *************** *** 258,280 **** RrdDb getRrd( String rrdFile ) throws IOException, RrdException { ! RrdDb rrd; ! ! // Look for an open rrdDb ! for (int i = 0; i < rrdDbPool.size(); i++) { ! rrd = (RrdDb) rrdDbPool.get(i); ! if ( rrd.getRrdFile().getFilePath().equalsIgnoreCase(rrdFile) ) ! return rrd; ! } ! ! // Not in the pool, create new object ! rrd = new RrdDb( rrdFile ); ! if ( rrdDbPool.size() < maxPoolSize ) ! rrdDbPool.add( rrd ); ! else if ( maxPoolSize > 1 ) { ! rrdDbPool.remove(0); // Remove the first (oldest) RrdDb ! rrdDbPool.add( rrd ); } ! ! return rrd; } --- 304,312 ---- RrdDb getRrd( String rrdFile ) throws IOException, RrdException { ! if ( pool != null ) { ! return pool.requestRrdDb( rrdFile ); } ! else ! return new RrdDb( rrdFile ); } *************** *** 282,302 **** // -- Private methods // ================================================================ ! private BufferedImage getBufferedImage(int width, int height) { ! try ! { ! if ( img != null ) ! return img; ! else ! { ! img = grapher.createImage( width, height ); ! return img; ! } ! } ! catch (Exception e) { // Temporary ! e.printStackTrace(); ! } ! return null; } } --- 314,323 ---- // -- Private methods // ================================================================ ! private BufferedImage getBufferedImage(int width, int height) throws RrdException, IOException { ! // Always regenerate graph ! img = grapher.createImage( width, height ); ! return img; } } Index: Comment.java =================================================================== RCS file: /cvsroot/jrobin/src/jrobin/graph2/Comment.java,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** Comment.java 21 Oct 2003 19:41:58 -0000 1.1 --- Comment.java 27 Oct 2003 21:03:32 -0000 1.2 *************** *** 30,68 **** /** ! * <p>description</p> * ! * @author Arne Vandamme (arn...@jr...) */ class Comment { ! static final int CMT_DEFAULT = 0; ! static final int CMT_LEGEND = 1; ! static final int CMT_GPRINT = 2; ! ! static final Byte TKN_ALF = new Byte( (byte) 1); // Align left with Linefeed ! static final Byte TKN_ARF = new Byte( (byte) 2); // Align right with linefeed ! static final Byte TKN_ACF = new Byte( (byte) 3); // Align center with linefeed ! static final Byte TKN_AL = new Byte( (byte) 4); // Align right no linefeed ! static final Byte TKN_AR = new Byte( (byte) 5); // Align left no linefeed ! static final Byte TKN_AC = new Byte( (byte) 6); // Align center no linefeed ! static final Byte TKN_NULL = null; ! String text; ! Vector oList = new Vector(); ! protected int lineCount = 0; ! protected boolean endLf = false; ! protected int commentType = CMT_DEFAULT; ! protected Byte lfToken = TKN_ALF; ! /** ! * Implicit super constructor. ! */ Comment( ) { } /** ! * ! * @param text */ Comment( String text ) throws RrdException --- 30,75 ---- /** ! * <p>Represent a piece of aligned text to be drawn on the graph.</p> * ! * @author Arne Vandamme (cob...@jr...) */ class Comment { ! // ================================================================ ! // -- Members ! // ================================================================ ! protected static final int CMT_DEFAULT = 0; ! protected static final int CMT_LEGEND = 1; ! protected static final int CMT_GPRINT = 2; ! protected static final Byte TKN_ALF = new Byte( (byte) 1); // Align left with Linefeed ! protected static final Byte TKN_ARF = new Byte( (byte) 2); // Align right with linefeed ! protected static final Byte TKN_ACF = new Byte( (byte) 3); // Align center with linefeed ! protected static final Byte TKN_AL = new Byte( (byte) 4); // Align right no linefeed ! protected static final Byte TKN_AR = new Byte( (byte) 5); // Align left no linefeed ! protected static final Byte TKN_AC = new Byte( (byte) 6); // Align center no linefeed ! protected static final Byte TKN_NULL = null; ! protected int lineCount = 0; ! protected boolean endLf = false; ! protected int commentType = CMT_DEFAULT; ! protected Byte lfToken = TKN_ALF; ! protected String text; ! protected Vector oList = new Vector(); ! ! ! // ================================================================ ! // -- Constructors ! // ================================================================ Comment( ) { } /** ! * Constructs a <code>Comment</code> object of a given text string. ! * The original text string is parsed into new string/token pairs ! * where byte tokens are used to specify alignment markers. ! * @param text Text with alignment/new-line tokens as a single string. ! * @throws RrdException Thrown in case of a JRobin specific error. */ Comment( String text ) throws RrdException *************** *** 71,78 **** parseComment(); } ! /** * Splits the string up in string/token pairs. * The tokens specify alignment or new-lines. */ protected void parseComment() throws RrdException --- 78,90 ---- parseComment(); } ! ! ! // ================================================================ ! // -- Protected methods ! // ================================================================ /** * Splits the string up in string/token pairs. * The tokens specify alignment or new-lines. + * @throws RrdException Thrown in case of a JRobin specific error. */ protected void parseComment() throws RrdException *************** *** 149,155 **** /** ! * ! * @param tokenChar ! * @return */ protected Byte getToken( char tokenChar ) --- 161,167 ---- /** ! * Retrieves the corresponding token-byte for a given token character. ! * @param tokenChar Character to retrieve corresponding bytevalue of. ! * @return Token bytevalue for the corresponding token character. */ protected Byte getToken( char tokenChar ) *************** *** 180,183 **** --- 192,199 ---- } + /** + * Used to check it a <code>Comment</code> item ends with a linefeed. + * @return True if this Comment ends with a linefeed. + */ boolean isCompleteLine() { *************** *** 185,188 **** --- 201,208 ---- } + /** + * Retrieves a <code>Vector</code> containing all string/token pairs in order of <code>String</code> - <code>Byte</code>. + * @return Vector containing all string/token pairs of this Comment. + */ Vector getTokens() { *************** *** 191,196 **** /** ! * ! * @return */ int getLineCount() --- 211,216 ---- /** ! * Counts the number of complete lines (linefeed markers) in the <code>Comment</code> object. ! * @return Number of complete lines in this Comment. */ int getLineCount() Index: Cdef.java =================================================================== RCS file: /cvsroot/jrobin/src/jrobin/graph2/Cdef.java,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** Cdef.java 21 Oct 2003 19:41:58 -0000 1.1 --- Cdef.java 27 Oct 2003 21:03:32 -0000 1.2 *************** *** 31,46 **** /** ! * <p>Represents a 'calculated' datasource for a graph.</p> * ! * @author Arne Vandamme (arn...@jr...) */ public class Cdef extends Source { private String[] strTokens; ! double[] constants; ! int[] dsIndices; ! byte[] tokens; Cdef( String name, String rpn ) { --- 31,60 ---- /** ! * <p>Represents a 'calculated' datasource for a graph. A calculated datasource is always based on a RPN ! * (Reverse Polar Notation) expression the algorithm to be used for calculating values.</p> * ! * @author Arne Vandamme (cob...@jr...) */ public class Cdef extends Source { + // ================================================================ + // -- Members + // ================================================================ private String[] strTokens; ! private double[] constants; ! private int[] dsIndices; ! private byte[] tokens; + + // ================================================================ + // -- Constructors + // ================================================================ + /** + * Constructs a new Cdef object holding a number of datapoints for a graph. + * A Cdef is always based on a RPN expression holding the calculation algorithm. + * @param name Name of the datasource in the graph definition. + * @param rpn Algorithm to use for value calculation in reverse polar notation (RPN) form. + */ Cdef( String name, String rpn ) { *************** *** 54,58 **** strTokens[i] = st.nextToken().trim(); } ! void prepare( HashMap sourceIndex, int numPoints ) throws RrdException { --- 68,83 ---- strTokens[i] = st.nextToken().trim(); } ! ! ! // ================================================================ ! // -- Protected methods ! // ================================================================ ! /** ! * Prepares the Cdef for faster value calculation by parsing the given RPN expression to ! * a better more efficient format. ! * @param sourceIndex Lookup table holding the name - index pairs for all datasources. ! * @param numPoints Number of points used as graph resolution (size of the value table). ! * @throws RrdException Thrown in case of a JRobin specific error. ! */ void prepare( HashMap sourceIndex, int numPoints ) throws RrdException { *************** *** 158,179 **** } } ! ! private boolean isNumber(String token) { try { Double.parseDouble(token); return true; } catch (NumberFormatException nfe) { ! return false; } } - - void set( int pos, long timestamp, double val ) - { - super.set( pos, timestamp, val ); - values[pos] = val; - } - } --- 183,231 ---- } } ! ! /** ! * Sets the value of a specific datapoint for this Cdef. ! * @param pos Position (index in the value table) of the new datapoint. ! * @param time Timestamp of the new datapoint in number of seconds. ! * @param val Double value of the new datapoint. ! */ ! void set( int pos, long timestamp, double val ) ! { ! super.set( pos, timestamp, val ); ! values[pos] = val; ! } ! ! byte[] getTokens() { ! return tokens; ! } ! ! double[] getConstants() { ! return constants; ! } ! ! int[] getDsIndices() { ! return dsIndices; ! } ! ! ! // ================================================================ ! // -- Private methods ! // ================================================================ ! /** ! * Checks if a given string is a number. ! * @param token String to check. ! * @return True if the token is a number, false if not. ! */ ! private boolean isNumber( String token ) { try { Double.parseDouble(token); + return true; } catch (NumberFormatException nfe) { ! return false; } } } Index: TimeGrid.java =================================================================== RCS file: /cvsroot/jrobin/src/jrobin/graph2/TimeGrid.java,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** TimeGrid.java 24 Oct 2003 21:15:33 -0000 1.1 --- TimeGrid.java 27 Oct 2003 21:03:32 -0000 1.2 *************** *** 28,32 **** /** ! * <p>description</p> * * @author Arne Vandamme (cob...@jr...) --- 28,32 ---- /** ! * <p>Holds specific information about the Time axis grid of the chart.</p> * * @author Arne Vandamme (cob...@jr...) *************** *** 34,42 **** class TimeGrid { private long startTime; private long endTime; ! TimeAxisUnit tAxis; TimeGrid( long startTime, long endTime, TimeAxisUnit tAxis ) { --- 34,57 ---- class TimeGrid { + // ================================================================ + // -- Members + // ================================================================ private long startTime; private long endTime; ! private TimeAxisUnit tAxis; ! + // ================================================================ + // -- Constructors + // ================================================================ + /** + * Creates a time grid based on a timespan and possibly a time axis + * unit specification. + * @param startTime Start time of the timespan. + * @param endTime End time of the timespan. + * @param tAxis TimeAxisUnit specified to determine the grid lines, if the given + * TimeAxisUnit is null, one will be automatically determined. + */ TimeGrid( long startTime, long endTime, TimeAxisUnit tAxis ) { *************** *** 49,52 **** --- 64,99 ---- } + + // ================================================================ + // -- Protected methods + // ================================================================ + long getStartTime() { + return startTime; + } + + long getEndTime() { + return endTime; + } + + TimeMarker[] getTimeMarkers() { + return tAxis.getTimeMarkers( startTime, endTime ); + } + + long getMajorGridWidth() { + return tAxis.getMajorGridWidth(); + } + + boolean centerLabels() { + return tAxis.centerLabels(); + } + + + // ================================================================ + // -- Private methods + // ================================================================ + /** + * Determines a good TimeAxisUnit to use for grid calculation. + * A decent grid is selected based on the timespan being used in the chart. + */ private void setTimeAxis() { *************** *** 86,90 **** tAxis = new TimeAxisUnit( TimeAxisUnit.HOUR, 3, TimeAxisUnit.HOUR, 12, new SimpleDateFormat("HH:mm"), false ); } ! else if ( days <= 7 ) { tAxis = new TimeAxisUnit( TimeAxisUnit.HOUR, 6, TimeAxisUnit.DAY, 1, new SimpleDateFormat("EEE dd"), true); } --- 133,137 ---- tAxis = new TimeAxisUnit( TimeAxisUnit.HOUR, 3, TimeAxisUnit.HOUR, 12, new SimpleDateFormat("HH:mm"), false ); } ! else if ( days < 8 ) { tAxis = new TimeAxisUnit( TimeAxisUnit.HOUR, 6, TimeAxisUnit.DAY, 1, new SimpleDateFormat("EEE dd"), true); } *************** *** 102,126 **** } } - - long getStartTime() { - return startTime; - } - - long getEndTime() { - return endTime; - } - - protected TimeMarker[] getTimeMarkers() { - return tAxis.getTimeMarkers( startTime, endTime ); - } - - protec... [truncated message content] |
Update of /cvsroot/jrobin/src/jrobin/demo In directory sc8-pr-cvs1:/tmp/cvs-serv17805/src/jrobin/demo Modified Files: JRobinComplexGraph.java ProfileGraphsOld.java ProfileGraphsNew.java JRobinGallery.java Added Files: JRobinComplexDemo.java Log Message: New graph lib Finetuning Javadoc Added RrdDbPool Added JRobinComplexDemo --- NEW FILE: JRobinComplexDemo.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 jrobin.demo; import java.awt.Color; import java.util.Date; import java.util.GregorianCalendar; import java.text.SimpleDateFormat; import jrobin.core.*; import jrobin.graph2.*; /** * <p>Extended graphing demo for JRobin.</p> * * @author Arne Vandamme (cob...@jr...) */ public class JRobinComplexDemo { static String demofile = "/complexdemo.rrd"; static void println(String msg) { System.out.println(msg); } public static void createDatabase() { try { println( "- Preparing to import complexdemo.xml" ); // Import database from XML RrdDb rrd = new RrdDb( demofile, "/complexdemo.xml" ); println( "- Database complexdemo.rrd has been succesfully imported" ); rrd.close(); } catch ( Exception e ) { println( "Error occurred while creating database: " + e.getMessage() ); } } public static void createGraphs() { GregorianCalendar start, stop; RrdDbPool pool = RrdDbPool.getInstance(); RrdGraph graph = new RrdGraph( pool ); try { // Create traffic overview of a week println( "- Creating graph 1: complexdemo1.png" ); start = new GregorianCalendar( 2003, 9, 20 ); stop = new GregorianCalendar( 2003, 9, 27 ); RrdGraphDef def = new RrdGraphDef( start, stop ); def.setImageBorder( Color.GRAY, 1 ); def.setTitle( "JRobinComplexDemo@Ldemo graph 1@r\nNetwork traffic overview" ); def.setVerticalLabel( "bits per second" ); def.datasource( "ifInOctets", demofile, "ifInOctets", "AVERAGE" ); def.datasource( "ifOutOctets", demofile, "ifOutOctets", "AVERAGE" ); def.datasource( "bitIn", "ifInOctets,8,*" ); def.datasource( "bitOut", "ifOutOctets,8,*" ); def.comment(" "); def.area( "bitIn", new Color(0x00, 0xFF, 0x00), "Incoming traffic " ); def.line( "bitOut", new Color(0x00, 0x00, 0x33), "Outgoing traffic\n\n" ); def.gprint( "bitIn", "MAX", "Max: @6.1 @sbit/s"); def.gprint( "bitOut", "MAX", " @6.1 @sbit/s\n"); def.gprint( "bitIn", "MIN", "Min: @6.1 @sbit/s"); def.gprint( "bitOut", "MIN", " @6.1 @sbit/s"); def.comment( " Connection: 100 Mbit/s\n" ); def.gprint( "bitIn", "AVG", "Avg: @6.1 @sbit/s"); def.gprint( "bitOut", "AVG", " @6.1 @sbit/s"); def.comment( " Duplex mode: FD - fixed\n\n"); def.gprint( "bitIn", "LAST", "Cur: @6.1 @sbit/s"); def.gprint( "bitOut", "LAST", " @6.1 @sbit/s\n\n"); def.comment( "[ courtesy of www.cherrymon.org ]@L" ); def.comment( "Generated: " + timestamp() + " @r" ); graph.setGraphDef( def ); graph.saveAsPNG( "/complexdemo1.png" ); // --------------------------------------------------------------- // Create server load and cpu usage of a day println( "- Creating graph 2: complexdemo2.png" ); start = new GregorianCalendar( 2003, 8, 19 ); stop = new GregorianCalendar( 2003, 8, 20 ); def = new RrdGraphDef( start, stop ); def.setImageBorder( Color.GRAY, 1 ); def.setTitle( "JRobinComplexDemo@Ldemo graph 2@r\nServer load and CPU utilization" ); def.datasource("load", demofile, "serverLoad", "AVERAGE"); def.datasource("user", demofile, "serverCPUUser", "AVERAGE"); def.datasource("nice", demofile, "serverCPUNice", "AVERAGE"); def.datasource("system", demofile, "serverCPUSystem", "AVERAGE"); def.datasource("idle", demofile, "serverCPUIdle", "AVERAGE"); def.datasource("total", "user,nice,+,system,+,idle,+"); def.datasource("busy", "user,nice,+,system,+,total,/,100,*"); def.datasource("p25t50", "busy,25,GT,busy,50,LE,load,0,IF,0,IF"); def.datasource("p50t75", "busy,50,GT,busy,75,LE,load,0,IF,0,IF"); def.datasource("p75t90", "busy,75,GT,busy,90,LE,load,0,IF,0,IF"); def.datasource("p90t100", "busy,90,GT,load,0,IF"); def.comment( "CPU utilization (%)\n " ); def.area("load", new Color(0x66,0x99,0xcc), " 0 - 25%"); def.area("p25t50", new Color(0x00,0x66,0x99), "25 - 50%"); def.comment(" "); def.gprint("busy", "MIN", "Minimum:@5.1@s%"); def.gprint("busy", "MAX", "Maximum:@5.1@s%\n "); def.area("p50t75", new Color(0x66,0x66,0x00), "50 - 75%"); def.area("p75t90", new Color(0xff,0x66,0x00), "75 - 90%"); def.area("p90t100", new Color(0xcc,0x33,0x00), "90 - 100%"); def.gprint("busy", "AVG", " Average:@5.1@s%"); def.gprint("busy", "LAST", "Current:@5.1@s%\n "); def.comment( "\nServer load\n " ); def.line("load", new Color(0x00,0x00,0x00), "Load average (5 min)@L" ); def.gprint("load", "MIN", "Minimum:@5.2@s%"); def.gprint("load", "MAX", "Maximum:@5.2@s% @r "); def.hrule( 0.7, new Color( 0xFF, 0xCC, 0x00), "Average load@L" ); def.gprint("load", "AVG", "Average:@5.2@s%"); def.gprint("load", "LAST", "Current:@5.2@s% @r"); def.comment( "\n\n[ courtesy of www.cherrymon.org ]@L" ); def.comment( "Generated: " + timestamp() + " @r" ); graph.setGraphDef( def ); graph.saveAsPNG( "/complexdemo2.png" ); println( "- Creating graph 2: complexdemo2.jpg" ); graph.saveAsJPEG( "/complexdemo2.jpg", 640, 480, 1.0f ); // --------------------------------------------------------------- // Create ftp graph for a month println( "- Creating graph 3: complexdemo3.png"); start = new GregorianCalendar( 2003, 8, 19, 12, 00 ); stop = new GregorianCalendar( 2003, 8, 20, 12, 00 ); def = new RrdGraphDef( start, stop ); def.setImageBorder( Color.GRAY, 1 ); def.setFrontGrid(false); def.setTitle( "JRobinComplexDemo@Ldemo graph 3@r\nFTP Usage" ); def.datasource( "ftp", demofile, "ftpUsers", "AVERAGE" ); def.line( "ftp", new Color(0x00, 0x00, 0x33), "FTP connections" ); def.gprint( "ftp", "AVG", "( average: @0,"); def.gprint( "ftp", "MIN", "never below: @0 )\n\n"); def.comment( " Usage spread:" ); def.area( new GregorianCalendar( 2003, 8, 19, 17, 00 ), Double.MIN_VALUE, new GregorianCalendar( 2003, 8, 19, 23, 00 ), Double.MAX_VALUE, Color.RED, "peak period" ); def.area( new GregorianCalendar( 2003, 8, 20, 5, 00 ), Double.MIN_VALUE, new GregorianCalendar( 2003, 8, 20, 8, 30 ), Double.MAX_VALUE, Color.LIGHT_GRAY, "quiet period\n" ); def.comment( " Rise/descend:" ); def.area( "ftp", new Color(0x00, 0x00, 0x33), null ); def.line( new GregorianCalendar( 2003, 8, 19, 12, 00 ), 8, new GregorianCalendar( 2003, 8, 19, 20, 30 ), 15, Color.PINK, "climb slope", 2 ); def.line( new GregorianCalendar( 2003, 8, 19, 20, 30 ), 15, new GregorianCalendar( 2003, 8, 20, 8, 00 ), 4, Color.CYAN, "fall-back slope\n", 2 ); def.vrule( new GregorianCalendar( 2003, 8, 20 ), Color.YELLOW, null ); def.comment( "\n\n[ courtesy of www.cherrymon.org ]@L" ); def.comment( "Generated: " + timestamp() + " @r" ); graph.setGraphDef( def ); graph.saveAsPNG( "/complexdemo3.png" ); println( "- Creating graph 3: complexdemo3.jpg"); graph.saveAsJPEG( "/complexdemo3.jpg", 1.0f ); // --------------------------------------------------------------- } catch ( Exception e ) { println( "Error occurred while creating the graph: " + e.getMessage() ); } } public static String timestamp() { SimpleDateFormat df = new SimpleDateFormat( "dd/MM/yyyy HH:mm" ); return df.format( new Date() ); } public static void main(String[] args) { createDatabase(); createGraphs(); println( "- Demo finished." ); } } Index: JRobinComplexGraph.java =================================================================== RCS file: /cvsroot/jrobin/src/jrobin/demo/JRobinComplexGraph.java,v retrieving revision 1.13 retrieving revision 1.14 diff -C2 -d -r1.13 -r1.14 *** JRobinComplexGraph.java 24 Oct 2003 21:15:34 -0000 1.13 --- JRobinComplexGraph.java 27 Oct 2003 21:03:33 -0000 1.14 *************** *** 160,166 **** gf.saveAsPNG("/demo_graph2.png", 0, 200); - // Wrap up - gf.closeFiles(); - // Print out timing information for the new package API long s2 = Calendar.getInstance().getTimeInMillis(); --- 160,163 ---- Index: ProfileGraphsOld.java =================================================================== RCS file: /cvsroot/jrobin/src/jrobin/demo/ProfileGraphsOld.java,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** ProfileGraphsOld.java 24 Oct 2003 21:15:34 -0000 1.3 --- ProfileGraphsOld.java 27 Oct 2003 21:03:33 -0000 1.4 *************** *** 52,56 **** // Demo sake ! private GregorianCalendar startDate = new GregorianCalendar(2002, 7, 24, 00, 00); private GregorianCalendar endDate = new GregorianCalendar(2003, 7, 25, 00, 00); --- 52,56 ---- // Demo sake ! private GregorianCalendar startDate = new GregorianCalendar(2003, 7, 24, 00, 00); private GregorianCalendar endDate = new GregorianCalendar(2003, 7, 25, 00, 00); Index: ProfileGraphsNew.java =================================================================== RCS file: /cvsroot/jrobin/src/jrobin/demo/ProfileGraphsNew.java,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** ProfileGraphsNew.java 24 Oct 2003 21:15:34 -0000 1.3 --- ProfileGraphsNew.java 27 Oct 2003 21:03:33 -0000 1.4 *************** *** 32,35 **** --- 32,36 ---- import java.util.GregorianCalendar; + import jrobin.core.RrdDbPool; import jrobin.core.RrdException; import jrobin.core.Util; *************** *** 52,56 **** // Demo sake ! private GregorianCalendar startDate = new GregorianCalendar(2002, 7, 24, 00, 30); private GregorianCalendar endDate = new GregorianCalendar(2003, 7, 25, 00, 00); --- 53,57 ---- // Demo sake ! private GregorianCalendar startDate = new GregorianCalendar(2003, 7, 24, 00, 30); private GregorianCalendar endDate = new GregorianCalendar(2003, 7, 25, 00, 00); *************** *** 80,84 **** try { ! graph = new RrdGraph(); // Default rrddb pool size createDemo1(); --- 81,85 ---- try { ! graph = new RrdGraph( RrdDbPool.getInstance() ); // Default rrddb pool size createDemo1(); *************** *** 93,98 **** createDemoEx(6); - - graph.closeFiles(); } catch ( Exception e ) --- 94,97 ---- Index: JRobinGallery.java =================================================================== RCS file: /cvsroot/jrobin/src/jrobin/demo/JRobinGallery.java,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** JRobinGallery.java 23 Oct 2003 23:16:36 -0000 1.4 --- JRobinGallery.java 27 Oct 2003 21:03:33 -0000 1.5 *************** *** 87,91 **** def.area("blank2", Color.WHITE, null); def.line("v1", Color.BLUE, null, 1); ! def.line("v2", null, null, 1); def.setTitle("Voltage measurement"); def.setVerticalLabel("[Volts]"); --- 87,91 ---- def.area("blank2", Color.WHITE, null); def.line("v1", Color.BLUE, null, 1); ! def.line("v2", Color.BLUE, null, 1); def.setTitle("Voltage measurement"); def.setVerticalLabel("[Volts]"); |
Update of /cvsroot/jrobin/src/jrobin/graph2 In directory sc8-pr-cvs1:/tmp/cvs-serv5465/src/jrobin/graph2 Modified Files: Stack.java ValueAxisUnit.java TimeAxisUnit.java RrdGraphDef.java RrdGraph.java ValueMarker.java CustomLine.java Grapher.java TimeMarker.java PlotDef.java ValueFormatter.java Added Files: TimeGrid.java ValueGrid.java Line.java Removed Files: ValueScaler.java Log Message: New graph lib Finetuning, tweaking, general clean-up --- NEW FILE: TimeGrid.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 jrobin.graph2; import java.text.SimpleDateFormat; /** * <p>description</p> * * @author Arne Vandamme (cob...@jr...) */ class TimeGrid { private long startTime; private long endTime; TimeAxisUnit tAxis; TimeGrid( long startTime, long endTime, TimeAxisUnit tAxis ) { this.startTime = startTime; this.endTime = endTime; this.tAxis = tAxis; // Set an appropriate time axis it not given yet setTimeAxis(); } private void setTimeAxis() { if ( tAxis != null ) return; double days = (endTime - startTime) / 86400.0; if ( days <= 0.75 / 24.0 ) { tAxis = new TimeAxisUnit( TimeAxisUnit.MINUTE, 1, TimeAxisUnit.MINUTE, 5, new SimpleDateFormat("HH:mm"), false ); } else if ( days <= 2.0 / 24.0 ) { tAxis = new TimeAxisUnit( TimeAxisUnit.MINUTE, 5, TimeAxisUnit.MINUTE, 10, new SimpleDateFormat("HH:mm"), false ); } else if ( days <= 3.0 / 24.0 ) { tAxis = new TimeAxisUnit( TimeAxisUnit.MINUTE, 5, TimeAxisUnit.MINUTE, 20, new SimpleDateFormat("HH:mm"), false ); } else if ( days <= 5.0 / 24.0 ) { tAxis = new TimeAxisUnit( TimeAxisUnit.MINUTE, 10, TimeAxisUnit.MINUTE, 30, new SimpleDateFormat("HH:mm"), false ); } else if ( days <= 10.0 / 24.0 ) { tAxis = new TimeAxisUnit( TimeAxisUnit.MINUTE, 15, TimeAxisUnit.HOUR, 1, new SimpleDateFormat("HH:mm"), false ); } else if ( days <= 15.0 / 24.0 ) { tAxis = new TimeAxisUnit( TimeAxisUnit.MINUTE, 30, TimeAxisUnit.HOUR, 2, new SimpleDateFormat("HH:mm"), false ); } else if ( days <= 20.0 / 24.0 ) { tAxis = new TimeAxisUnit( TimeAxisUnit.HOUR, 1, TimeAxisUnit.HOUR, 1, new SimpleDateFormat("HH"), true ); } else if ( days <= 36.0 / 24.0 ) { tAxis = new TimeAxisUnit( TimeAxisUnit.HOUR, 1, TimeAxisUnit.HOUR, 4, new SimpleDateFormat("HH:mm"), false ); } else if ( days <= 2 ) { tAxis = new TimeAxisUnit( TimeAxisUnit.HOUR, 2, TimeAxisUnit.HOUR, 6, new SimpleDateFormat("HH:mm"), false ); } else if ( days <= 3 ) { tAxis = new TimeAxisUnit( TimeAxisUnit.HOUR, 3, TimeAxisUnit.HOUR, 12, new SimpleDateFormat("HH:mm"), false ); } else if ( days <= 7 ) { tAxis = new TimeAxisUnit( TimeAxisUnit.HOUR, 6, TimeAxisUnit.DAY, 1, new SimpleDateFormat("EEE dd"), true); } else if ( days <= 14 ) { tAxis = new TimeAxisUnit( TimeAxisUnit.HOUR, 12, TimeAxisUnit.DAY, 1, new SimpleDateFormat("dd"), true ); } else if ( days <= 43 ) { tAxis = new TimeAxisUnit( TimeAxisUnit.DAY, 1, TimeAxisUnit.WEEK, 1, new SimpleDateFormat("'week' ww"), true ); } else if ( days <= 157 ) { tAxis = new TimeAxisUnit( TimeAxisUnit.WEEK, 1, TimeAxisUnit.WEEK, 1, new SimpleDateFormat("ww"), true ); } else { tAxis = new TimeAxisUnit( TimeAxisUnit.MONTH, 1, TimeAxisUnit.MONTH, 1, new SimpleDateFormat("MMM"), true ); } } long getStartTime() { return startTime; } long getEndTime() { return endTime; } protected TimeMarker[] getTimeMarkers() { return tAxis.getTimeMarkers( startTime, endTime ); } protected long getMajorGridWidth() { return tAxis.getMajorGridWidth(); } protected boolean centerLabels() { return tAxis.centerLabels(); } } --- NEW FILE: ValueGrid.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 jrobin.graph2; /** * <p>description</p> * * @author Arne Vandamme (cob...@jr...) */ class ValueGrid { private boolean rigid; private double lower; private double upper; ValueAxisUnit vAxis; ValueGrid( boolean rigid, double lower, double upper, ValueAxisUnit vAxis ) { this.rigid = rigid; this.lower = lower; this.upper = upper; this.vAxis = vAxis; // Set an appropriate value axis it not given yet setValueAxis(); if ( !rigid ) { this.lower = this.vAxis.getNiceLower( lower ); this.upper = this.vAxis.getNiceHigher( upper ); } } private void setValueAxis() { if ( vAxis != null ) return; if ( !rigid && upper == 0 && upper == lower ) upper = 0.9; // Determine nice axis grid double shifted = ( Math.abs(upper) > Math.abs(lower) ? Math.abs(upper) : Math.abs(lower) ); double mod = 1.0; while ( shifted > 10 ) { shifted /= 10; mod *= 10; } while ( shifted < 1 ) { shifted *= 10; mod /= 10; } // Create nice grid based on 'fixed' ranges if ( shifted <= 3 ) vAxis = new ValueAxisUnit( 0.2*mod, 1.0*mod ); else if ( shifted <= 5 ) vAxis = new ValueAxisUnit( 0.5*mod, 1.0*mod ); else if ( shifted <= 9 ) vAxis = new ValueAxisUnit( 0.5*mod, 2.0*mod ); else vAxis = new ValueAxisUnit( 1.0*mod, 5.0*mod ); } protected double getLowerValue() { return lower; } protected double getUpperValue() { return upper; } protected ValueMarker[] getValueMarkers() { return vAxis.getValueMarkers( lower, upper ); } } --- NEW FILE: Line.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 jrobin.graph2; import java.awt.Color; import java.awt.BasicStroke; import jrobin.core.RrdException; /** * <p>description</p> * * @author Arne Vandamme (cob...@jr...) */ class Line extends PlotDef { // ================================================================ // -- Members // ================================================================ protected int lineWidth = 1; // Default line width of 1 pixel // ================================================================ // -- Constructors // ================================================================ Line() { super(); } Line( String sourceName, Color color ) { super( sourceName, color ); } Line( String sourceName, Color color, int lineWidth ) { this( sourceName, color ); this.lineWidth = lineWidth; } Line( Source source, Color color, boolean stacked, boolean visible ) { super( source, color, stacked, visible); } // ================================================================ // -- Protected methods // ================================================================ void draw( ChartGraphics g, int[] xValues, int[] stackValues, int lastPlotType ) throws RrdException { g.setColor( color ); g.setStroke( new BasicStroke(lineWidth) ); int ax = 0, ay = 0; int nx = 0, ny = 0, last = -1; for (int i = 0; i < xValues.length; i++) { nx = xValues[i]; ny = g.getY( source.values[i] ); if ( stacked && ny != Integer.MIN_VALUE ) ny += stackValues[i]; if ( visible && ny != Double.NaN && nx != 0 && ay != Integer.MIN_VALUE && ny != Integer.MIN_VALUE ) g.drawLine( ax, ay, nx, ny ); stackValues[i] = ny; ax = nx; ay = ny; } g.setStroke( new BasicStroke() ); } int getLineWidth() { return lineWidth; } } Index: Stack.java =================================================================== RCS file: /cvsroot/jrobin/src/jrobin/graph2/Stack.java,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** Stack.java 22 Oct 2003 21:06:53 -0000 1.2 --- Stack.java 24 Oct 2003 21:15:33 -0000 1.3 *************** *** 49,53 **** { if ( lastPlotType == PlotDef.PLOT_LINE ) ! stack = new PlotDef( source, color, true, visible ); else if ( lastPlotType == PlotDef.PLOT_AREA ) stack = new Area( source, color, true, visible ); --- 49,53 ---- { if ( lastPlotType == PlotDef.PLOT_LINE ) ! stack = new Line( source, color, true, visible ); else if ( lastPlotType == PlotDef.PLOT_AREA ) stack = new Area( source, color, true, visible ); Index: ValueAxisUnit.java =================================================================== RCS file: /cvsroot/jrobin/src/jrobin/graph2/ValueAxisUnit.java,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** ValueAxisUnit.java 21 Oct 2003 19:41:58 -0000 1.1 --- ValueAxisUnit.java 24 Oct 2003 21:15:33 -0000 1.2 *************** *** 42,69 **** private int roundStep = 2; - private int gridUnit = 1; // minor grid - private double gridParts = 2d; - private int mGridUnit = 10; // major grid - private double mGridParts = 1d; - private double gridStep = 2; private double mGridStep = 10; ! ValueAxisUnit( double labelStep, double markStep, int roundStep ) ! { ! this.labelStep = labelStep; ! this.markStep = markStep; ! this.roundStep = roundStep; ! } ! ! ValueAxisUnit( int gridUnit, double gridParts, int mGridUnit, double mGridParts ) { ! this.gridUnit = gridUnit; ! this.gridParts = gridParts; ! this.mGridUnit = mGridUnit; ! this.mGridParts = mGridParts; ! ! gridStep = gridUnit * gridParts; ! mGridStep = mGridUnit * mGridParts; } --- 42,52 ---- private int roundStep = 2; private double gridStep = 2; private double mGridStep = 10; ! ValueAxisUnit( double gridStep, double labelStep ) { ! this.gridStep = gridStep; ! this.mGridStep = labelStep; } *************** *** 78,82 **** } ! public ValueMarker[] getValueMarkers( double lower, double upper, double base, int scaleIndex ) { double minPoint = 0.0d; --- 61,65 ---- } ! protected ValueMarker[] getValueMarkers( double lower, double upper ) { double minPoint = 0.0d; *************** *** 103,122 **** if ( minPoint < majPoint ) { ! markerList.add( new ValueMarker(minPoint, "", false) ); minPoint = round( minPoint + gridStep ); } else { - String str; - ValueScaler vs = new ValueScaler( majPoint, scaleIndex, base); - int ival = new Double(vs.getScaledValue()).intValue(); - if ( ival == vs.getScaledValue() ) - str = (ival + vs.getPrefix()).trim(); - else - str = (round(vs.getScaledValue(), 2) + vs.getPrefix()).trim(); - if ( minPoint == majPoint ) // Special case, but will happen most of the time { ! markerList.add( new ValueMarker(majPoint, str, true) ); minPoint = round( minPoint + gridStep ); majPoint = round( majPoint + mGridStep ); --- 86,97 ---- if ( minPoint < majPoint ) { ! markerList.add( new ValueMarker(minPoint, false) ); minPoint = round( minPoint + gridStep ); } else { if ( minPoint == majPoint ) // Special case, but will happen most of the time { ! markerList.add( new ValueMarker(majPoint, true) ); minPoint = round( minPoint + gridStep ); majPoint = round( majPoint + mGridStep ); *************** *** 124,128 **** else { ! markerList.add( new ValueMarker(majPoint, str, true) ); majPoint = round( majPoint + mGridStep ); } --- 99,103 ---- else { ! markerList.add( new ValueMarker(majPoint, true) ); majPoint = round( majPoint + mGridStep ); } *************** *** 132,136 **** while ( minPoint <= upper ) { ! markerList.add( new ValueMarker(minPoint, "", false) ); minPoint = round( minPoint + gridStep ); } --- 107,111 ---- while ( minPoint <= upper ) { ! markerList.add( new ValueMarker(minPoint, false) ); minPoint = round( minPoint + gridStep ); } *************** *** 138,171 **** while ( majPoint <= upper ) { ! String str; ! ValueScaler vs = new ValueScaler( majPoint, scaleIndex, base); ! int ival = new Double(vs.getScaledValue()).intValue(); ! if ( ival == vs.getScaledValue() ) ! str = (ival + vs.getPrefix()).trim(); ! else ! str = (vs.getScaledValue() + vs.getPrefix()).trim(); ! ! markerList.add( new ValueMarker(majPoint, str, true) ); majPoint = round( majPoint + mGridStep ); } ! return (ValueMarker[]) markerList.toArray( new ValueMarker[0] ); } ! public double getNiceLower( double ovalue ) { // Add some checks - double gridParts = this.gridParts; - double mGridParts = this.mGridParts; double gridFactor = 1.0; double mGridFactor = 1.0; ! if ( gridUnit * gridParts < 1.0 ) { ! gridParts *= 100; gridFactor = 100; } ! if ( mGridUnit * mGridParts < 1.0 ) { ! mGridParts *= 100; mGridFactor = 100; } --- 113,139 ---- while ( majPoint <= upper ) { ! markerList.add( new ValueMarker(majPoint, true) ); majPoint = round( majPoint + mGridStep ); } ! return (ValueMarker[]) markerList.toArray( new ValueMarker[0] ); } ! public double getNiceLower( double ovalue ) { // Add some checks double gridFactor = 1.0; double mGridFactor = 1.0; ! double gridStep = this.gridStep; ! double mGridStep = this.mGridStep; ! ! if ( gridStep < 1.0 ) { ! gridStep *= 100; gridFactor = 100; } ! if ( mGridStep < 1.0 ) { ! mGridStep *= 100; mGridFactor = 100; } *************** *** 173,177 **** double value = ovalue * gridFactor; int valueInt = new Double(value).intValue(); ! int roundStep = new Double(gridUnit * gridParts).intValue(); if ( roundStep == 0 ) roundStep = 1; int num = valueInt / roundStep; --- 141,145 ---- double value = ovalue * gridFactor; int valueInt = new Double(value).intValue(); ! int roundStep = new Double(gridStep).intValue(); if ( roundStep == 0 ) roundStep = 1; int num = valueInt / roundStep; *************** *** 183,191 **** if ( num == 0 && value >= 0 ) gridValue = 0.0; ! else if ( Math.abs(gridValue - value) < (gridParts * gridUnit) / 16 ) gridValue -= roundStep; value = ovalue * mGridFactor; ! roundStep = new Double(mGridUnit * mGridParts).intValue(); if ( roundStep == 0 ) roundStep = 1; num = valueInt / roundStep; --- 151,159 ---- if ( num == 0 && value >= 0 ) gridValue = 0.0; ! else if ( Math.abs(gridValue - value) < (gridStep) / 16 ) gridValue -= roundStep; value = ovalue * mGridFactor; ! roundStep = new Double(mGridStep).intValue(); if ( roundStep == 0 ) roundStep = 1; num = valueInt / roundStep; *************** *** 197,201 **** if ( value != 0.0d ) { ! if ( Math.abs(mGridValue - gridValue) < (mGridParts * mGridUnit) / 2) return mGridValue / mGridFactor; else --- 165,169 ---- if ( value != 0.0d ) { ! if ( Math.abs(mGridValue - gridValue) < (mGridStep) / 2) return mGridValue / mGridFactor; else *************** *** 209,224 **** { // Add some checks - double gridParts = this.gridParts; - double mGridParts = this.mGridParts; double gridFactor = 1.0; double mGridFactor = 1.0; ! ! if ( gridUnit * gridParts < 1.0 ) { ! gridParts *= 100; gridFactor = 100; } ! if ( mGridUnit * mGridParts < 1.0 ) { ! mGridParts *= 100; mGridFactor = 100; } --- 177,193 ---- { // Add some checks double gridFactor = 1.0; double mGridFactor = 1.0; ! ! double gridStep = this.gridStep; ! double mGridStep = this.mGridStep; ! ! if ( gridStep < 1.0 ) { ! gridStep *= 100; gridFactor = 100; } ! if ( mGridStep < 1.0 ) { ! mGridStep *= 100; mGridFactor = 100; } *************** *** 226,239 **** double value = ovalue * gridFactor; int valueInt = new Double(value).intValue(); ! int roundStep = new Double(gridUnit * gridParts).intValue(); if ( roundStep == 0 ) roundStep = 1; int num = valueInt / roundStep; int mod = valueInt % roundStep; double gridValue = (roundStep * (num + 1)) * 1.0d; ! if ( gridValue - value < (gridParts * gridUnit) / 8 ) gridValue += roundStep; value = ovalue * mGridFactor; ! roundStep = new Double(mGridUnit * mGridParts).intValue(); if ( roundStep == 0 ) roundStep = 1; num = valueInt / roundStep; --- 195,208 ---- double value = ovalue * gridFactor; int valueInt = new Double(value).intValue(); ! int roundStep = new Double(gridStep).intValue(); if ( roundStep == 0 ) roundStep = 1; int num = valueInt / roundStep; int mod = valueInt % roundStep; double gridValue = (roundStep * (num + 1)) * 1.0d; ! if ( gridValue - value < (gridStep) / 8 ) gridValue += roundStep; value = ovalue * mGridFactor; ! roundStep = new Double(mGridStep).intValue(); if ( roundStep == 0 ) roundStep = 1; num = valueInt / roundStep; *************** *** 243,247 **** if ( value != 0.0d ) { ! if ( Math.abs(mGridValue - gridValue) < (mGridParts * mGridUnit) / 2) return mGridValue / mGridFactor; else --- 212,216 ---- if ( value != 0.0d ) { ! if ( Math.abs(mGridValue - gridValue) < (mGridStep) / 2) return mGridValue / mGridFactor; else Index: TimeAxisUnit.java =================================================================== RCS file: /cvsroot/jrobin/src/jrobin/graph2/TimeAxisUnit.java,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** TimeAxisUnit.java 21 Oct 2003 19:41:58 -0000 1.1 --- TimeAxisUnit.java 24 Oct 2003 21:15:33 -0000 1.2 *************** *** 55,91 **** // Indices in the calendarUnit table ! public static final int SECOND = 0; ! public static final int MINUTE = 1; ! public static final int HOUR = 2; ! public static final int DAY = 3; ! public static final int WEEK = 4; ! public static final int MONTH = 5; ! public static final int YEAR = 6; ! ! private int gridTime = HOUR; // minor grid ! private int gridUnits = 1; ! private int mGridTime = HOUR; // major grid ! private int mGridUnits = 6; ! // By default labels are shown at the major grid ! private int unitType = HOUR; ! private int unitParts = 1; ! private SimpleDateFormat df = new SimpleDateFormat("HH:mm"); - TimeAxisUnit( int unitType, int unitParts, SimpleDateFormat df ) - { - this.unitType = unitType; - this.unitParts = unitParts; - //this.df = df; - } ! TimeAxisUnit( int gridTime, int gridUnits, int mGridTime, int mGridUnits, SimpleDateFormat df ) { ! this.gridTime = gridTime; ! this.gridUnits = gridUnits; ! this.mGridTime = mGridTime; ! this.mGridUnits = mGridUnits; ! this.df = df; } --- 55,83 ---- // Indices in the calendarUnit table ! public static final int SECOND = 0; ! public static final int MINUTE = 1; ! public static final int HOUR = 2; ! public static final int DAY = 3; ! public static final int WEEK = 4; ! public static final int MONTH = 5; ! public static final int YEAR = 6; ! private int gridTime = HOUR; // minor grid ! private int gridUnits = 1; ! private int mGridTime = HOUR; // major grid ! private int mGridUnits = 6; ! private boolean centerLabels = false; ! private SimpleDateFormat df = new SimpleDateFormat("HH:mm"); ! TimeAxisUnit( int gridTime, int gridUnits, int mGridTime, int mGridUnits, SimpleDateFormat df, boolean centerLabels ) { ! this.gridTime = gridTime; ! this.gridUnits = gridUnits; ! this.mGridTime = mGridTime; ! this.mGridUnits = mGridUnits; ! this.df = df; ! this.centerLabels = centerLabels; } *************** *** 178,181 **** --- 170,177 ---- return (c.getTimeInMillis() / 1000) - now; + } + + boolean centerLabels() { + return centerLabels; } } Index: RrdGraphDef.java =================================================================== RCS file: /cvsroot/jrobin/src/jrobin/graph2/RrdGraphDef.java,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** RrdGraphDef.java 23 Oct 2003 23:16:35 -0000 1.3 --- RrdGraphDef.java 24 Oct 2003 21:15:33 -0000 1.4 *************** *** 64,129 **** // -- Members // ================================================================ ! long endTime = Util.getTime(); // default time spam of the last 24 hours ! long startTime = Util.getTime() - 86400L; ! Title title = null; // no title ! String valueAxisLabel = null; // no vertical label ! boolean gridX = true; // hide entire X axis grid (default: no) ! boolean gridY = true; // hide entire Y axis grid (default: no) ! boolean minorGridX = true; // hide minor X axis grid (default: no) ! boolean minorGridY = true; // hide minor Y axis grid (default: no) ! boolean majorGridX = true; // hide major X axis grid with labels (default: no) ! boolean majorGridY = true; // hide major Y axis grid with labels (default: no) ! boolean frontGrid = true; // show grid in front of the chart (default: yes) ! boolean antiAliasing = true; // use anti-aliasing for the chart (default: yes) ! boolean showLegend = true; // show legend and comments (default: yes) ! boolean drawSignature = true; // show JRobin url signature (default: yes) ! Color backColor = new Color( 245, 245, 245 ); // variation of light gray ! Color canvasColor = Color.WHITE; // white ! Color borderColor = Color.LIGHT_GRAY; // light gray, only applicable with a borderStroke ! Color normalFontColor = Color.BLACK; // black ! Color titleFontColor = Color.BLACK; // black ! Color majorGridColor = new Color(130,30,30); // variation of dark red ! Color minorGridColor = new Color(140,140,140); // variation of gray ! Color axisColor = new Color(130,30,30); // variation of dark red ! Color arrowColor = Color.RED; // red ! Color frameColor = Color.LIGHT_GRAY; // light gray ! Font titleFont = null; // use default 'grapher' font ! Font normalFont = null; // use default 'grapher' font ! File background = null; // no background image by default ! File overlay = null; // no overlay image by default ! int chart_lpadding = Grapher.CHART_LPADDING; // padding space on the left of the chart area ! double baseValue = ValueFormatter.DEFAULT_BASE; // unit base value to use (default: 1000) ! int scaleIndex = ValueFormatter.NO_SCALE; // fixed units exponent value to use ! BasicStroke borderStroke = null; // defaults to standard beveled border ! TimeAxisUnit tAxis = null; // custom time axis grid, defaults to no custom ! ValueAxisUnit vAxis = null; // custom value axis grid, defaults to no custom ! GridRange gridRange = null; // custom value range definition, defaults to auto-scale // -- Non-settable members ! int numDefs = 0; // number of Def datasources added ! int commentLines = 0; // number of complete lines in the list of comment items ! int commentLineShift = 0; // modifier to add to get minimum one complete line of comments ! ! HashMap fetchSources = new HashMap(); // holds the list of FetchSources ! Vector cdefList = new Vector(); // holds the list of Cdef datasources ! Vector plotDefs = new Vector(); // holds the list of PlotDefs ! Vector comments = new Vector(); // holds the list of comment items ! - // REMOVE THESE - boolean tAxisCentered = false; - double valueGridStep = Double.NaN; - double valueLabelStep = Double.NaN; - double valueStep = 0; - // ================================================================ --- 64,121 ---- // -- Members // ================================================================ ! private long endTime = Util.getTime(); // default time spam of the last 24 hours ! private long startTime = Util.getTime() - 86400L; ! private Title title = null; // no title ! private String valueAxisLabel = null; // no vertical label ! private boolean gridX = true; // hide entire X axis grid (default: no) ! private boolean gridY = true; // hide entire Y axis grid (default: no) ! private boolean minorGridX = true; // hide minor X axis grid (default: no) ! private boolean minorGridY = true; // hide minor Y axis grid (default: no) ! private boolean majorGridX = true; // hide major X axis grid with labels (default: no) ! private boolean majorGridY = true; // hide major Y axis grid with labels (default: no) ! private boolean frontGrid = true; // show grid in front of the chart (default: yes) ! private boolean antiAliasing = true; // use anti-aliasing for the chart (default: yes) ! private boolean showLegend = true; // show legend and comments (default: yes) ! private boolean drawSignature = true; // show JRobin url signature (default: yes) ! private Color backColor = new Color( 245, 245, 245 ); // variation of light gray ! private Color canvasColor = Color.WHITE; // white ! private Color borderColor = Color.LIGHT_GRAY; // light gray, only applicable with a borderStroke ! private Color normalFontColor = Color.BLACK; // black ! private Color titleFontColor = Color.BLACK; // black ! private Color majorGridColor = new Color(130,30,30); // variation of dark red ! private Color minorGridColor = new Color(140,140,140); // variation of gray ! private Color axisColor = new Color(130,30,30); // variation of dark red ! private Color arrowColor = Color.RED; // red ! private Color frameColor = Color.LIGHT_GRAY; // light gray ! private Font titleFont = null; // use default 'grapher' font ! private Font normalFont = null; // use default 'grapher' font ! private File background = null; // no background image by default ! private File overlay = null; // no overlay image by default ! private int chart_lpadding = Grapher.CHART_LPADDING; // padding space on the left of the chart area ! private double baseValue = ValueFormatter.DEFAULT_BASE; // unit base value to use (default: 1000) ! private int scaleIndex = ValueFormatter.NO_SCALE; // fixed units exponent value to use ! private BasicStroke borderStroke = null; // defaults to standard beveled border ! private TimeAxisUnit tAxis = null; // custom time axis grid, defaults to no custom ! private ValueAxisUnit vAxis = null; // custom value axis grid, defaults to no custom ! private GridRange gridRange = null; // custom value range definition, defaults to auto-scale // -- Non-settable members ! private int numDefs = 0; // number of Def datasources added ! private int commentLines = 0; // number of complete lines in the list of comment items ! private int commentLineShift = 0; // modifier to add to get minimum one complete line of comments + private HashMap fetchSources = new HashMap(); // holds the list of FetchSources + private Vector cdefList = new Vector(); // holds the list of Cdef datasources + private Vector plotDefs = new Vector(); // holds the list of PlotDefs + private Vector comments = new Vector(); // holds the list of comment items // ================================================================ *************** *** 252,255 **** --- 244,248 ---- * Specifies the settings of the image border. * Default is sort of beveled border around the image. + * To disable the image border, just specify a pixel width of 0. * @param c Bordercolor of the image. * @param w Pixel width of the image border. *************** *** 540,545 **** public void setValueAxis( double gridStep, double labelStep ) { ! this.valueGridStep = gridStep; ! this.valueLabelStep = labelStep; } --- 533,537 ---- public void setValueAxis( double gridStep, double labelStep ) { ! vAxis = new ValueAxisUnit( gridStep, labelStep ); } *************** *** 558,562 **** * @param majGridUnitSteps Time unit steps for the major grid lines. * @param dateFormat Format string of the time labels, according to <code>java.text.SimpleDateFormat</code> specifications. ! * @param centeredLabels True if the time label should be centered in the area between two major grid lines. */ public void setTimeAxis( int minGridTimeUnit, --- 550,554 ---- * @param majGridUnitSteps Time unit steps for the major grid lines. * @param dateFormat Format string of the time labels, according to <code>java.text.SimpleDateFormat</code> specifications. ! * @param centerLabels True if the time label should be centered in the area between two major grid lines. */ public void setTimeAxis( int minGridTimeUnit, *************** *** 565,569 **** int majGridUnitSteps, String dateFormat, ! boolean centeredLabels ) { this.tAxis = new TimeAxisUnit( minGridTimeUnit, --- 557,561 ---- int majGridUnitSteps, String dateFormat, ! boolean centerLabels ) { this.tAxis = new TimeAxisUnit( minGridTimeUnit, *************** *** 571,577 **** majGridTimeUnit, majGridUnitSteps, ! new SimpleDateFormat( dateFormat ) ); - this.tAxisCentered = centeredLabels; } --- 563,569 ---- majGridTimeUnit, majGridUnitSteps, ! new SimpleDateFormat( dateFormat ), ! centerLabels ); } *************** *** 643,647 **** public void line( String sourceName, Color color, String legend ) throws RrdException { ! plotDefs.add( new PlotDef(sourceName, color) ); addLegend( legend, color ); } --- 635,639 ---- public void line( String sourceName, Color color, String legend ) throws RrdException { ! plotDefs.add( new Line(sourceName, color) ); addLegend( legend, color ); } *************** *** 660,664 **** public void line( String sourceName, Color color, String legend, int lineWidth ) throws RrdException { ! plotDefs.add( new PlotDef(sourceName, color, lineWidth) ); addLegend( legend, color ); } --- 652,656 ---- public void line( String sourceName, Color color, String legend, int lineWidth ) throws RrdException { ! plotDefs.add( new Line(sourceName, color, lineWidth) ); addLegend( legend, color ); } *************** *** 874,877 **** --- 866,877 ---- } + protected Color getBorderColor() { + return borderColor; + } + + protected BasicStroke getBorderStroke() { + return borderStroke; + } + protected boolean showMinorGridX() { return minorGridX; *************** *** 910,913 **** --- 910,917 ---- } + protected boolean isFrontGrid() { + return frontGrid; + } + protected boolean useAntiAliasing() { return antiAliasing; *************** *** 938,946 **** } ! //protected getValueAxis() ! ! //protected getTimeAxis() ! protected PlotDef[] getPlotDefs() --- 942,952 ---- } ! protected ValueAxisUnit getValueAxis() { ! return vAxis; ! } + protected TimeAxisUnit getTimeAxis() { + return tAxis; + } protected PlotDef[] getPlotDefs() Index: RrdGraph.java =================================================================== RCS file: /cvsroot/jrobin/src/jrobin/graph2/RrdGraph.java,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** RrdGraph.java 23 Oct 2003 23:16:35 -0000 1.2 --- RrdGraph.java 24 Oct 2003 21:15:33 -0000 1.3 *************** *** 142,148 **** { Util.time(); ! RenderedImage r =(RenderedImage) getBufferedImage(width, height); ! Util.time(); ! ImageIO.write( r, "png", new File(path) ); Util.time(5); } --- 142,146 ---- { Util.time(); ! ImageIO.write( (RenderedImage) getBufferedImage(width, height), "png", new File(path) ); Util.time(5); } Index: ValueMarker.java =================================================================== RCS file: /cvsroot/jrobin/src/jrobin/graph2/ValueMarker.java,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** ValueMarker.java 21 Oct 2003 19:41:58 -0000 1.1 --- ValueMarker.java 24 Oct 2003 21:15:33 -0000 1.2 *************** *** 34,52 **** * Window - Preferences - Java - Code Generation - Code and Comments */ ! public class ValueMarker { ! double value = 0; ! String text = ""; ! private boolean label = false; ! ValueMarker( double value, String text, boolean label ) { ! this.label = label; this.value = value; - this.text = text; } ! public boolean isLabel() { ! return label; } } --- 34,56 ---- * Window - Preferences - Java - Code Generation - Code and Comments */ ! class ValueMarker ! { ! private double value = 0; ! private boolean major = false; ! ValueMarker( double value, boolean major ) { ! this.major = major; this.value = value; } ! protected double getValue() { ! return value; ! } ! ! protected boolean isMajor() ! { ! return major; } } Index: CustomLine.java =================================================================== RCS file: /cvsroot/jrobin/src/jrobin/graph2/CustomLine.java,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** CustomLine.java 22 Oct 2003 21:06:53 -0000 1.1 --- CustomLine.java 24 Oct 2003 21:15:33 -0000 1.2 *************** *** 36,40 **** * @author Arne Vandamme (arn...@jr...) */ ! class CustomLine extends PlotDef { private long xVal1; --- 36,40 ---- * @author Arne Vandamme (arn...@jr...) */ ! class CustomLine extends Line { private long xVal1; Index: Grapher.java =================================================================== RCS file: /cvsroot/jrobin/src/jrobin/graph2/Grapher.java,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** Grapher.java 23 Oct 2003 23:16:35 -0000 1.3 --- Grapher.java 24 Oct 2003 21:15:34 -0000 1.4 *************** *** 29,36 **** import java.util.Vector; import java.util.HashMap; - import java.util.Calendar; import java.util.Iterator; import java.util.LinkedList; - import java.text.SimpleDateFormat; import javax.imageio.ImageIO; import java.awt.Font; --- 29,34 ---- *************** [...1336 lines suppressed...] g.drawString( sig, imgWidth / 2 - (sig.length() * 5) / 2, imgHeight - 5 ); } ! ! /** ! * Graphs a text string onto a graphics2d context, using the specified default font color. ! * @param g Handle of a Graphics2D context to draw on. ! * @param str String to draw. ! * @param x X start position of the string. ! * @param y Y start position of the string. ! */ ! private void graphString( Graphics2D g, String str, int x, int y ) ! { ! Color oc = g.getColor(); ! ! g.setColor( normalFontColor ); ! g.drawString( str, x, y ); ! ! g.setColor( oc ); ! } } Index: TimeMarker.java =================================================================== RCS file: /cvsroot/jrobin/src/jrobin/graph2/TimeMarker.java,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** TimeMarker.java 21 Oct 2003 19:41:58 -0000 1.1 --- TimeMarker.java 24 Oct 2003 21:15:34 -0000 1.2 *************** *** 30,35 **** public class TimeMarker { ! long timestamp = 0; ! String text = ""; private boolean label = false; --- 30,35 ---- public class TimeMarker { ! private long timestamp = 0; ! private String text = ""; private boolean label = false; *************** *** 44,47 **** --- 44,57 ---- { return label; + } + + long getTimestamp() + { + return timestamp / 1000; + } + + String getLabel() + { + return text; } } Index: PlotDef.java =================================================================== RCS file: /cvsroot/jrobin/src/jrobin/graph2/PlotDef.java,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** PlotDef.java 22 Oct 2003 21:06:53 -0000 1.2 --- PlotDef.java 24 Oct 2003 21:15:34 -0000 1.3 *************** *** 26,30 **** import java.awt.Color; - import java.awt.BasicStroke; import java.util.HashMap; --- 26,29 ---- *************** *** 36,57 **** * @author Arne Vandamme (arn...@jr...) */ ! class PlotDef { static final int PLOT_LINE = 0; static final int PLOT_AREA = 1; static final int PLOT_STACK = 2; - static final int PLOT_VRULE = 3; protected boolean visible = true; protected boolean stacked = false; - protected int plotType = PLOT_LINE; // Default plotdef is a line ! protected int lineWidth = 1; // Default line width of 1 pixel ! protected String sourceName = ""; protected Source source = null; protected Color color = Color.BLACK; // Default color is black ! // Implicit PlotDef() { } --- 35,59 ---- * @author Arne Vandamme (arn...@jr...) */ ! abstract class PlotDef { + // ================================================================ + // -- Members + // ================================================================ static final int PLOT_LINE = 0; static final int PLOT_AREA = 1; static final int PLOT_STACK = 2; protected boolean visible = true; protected boolean stacked = false; protected int plotType = PLOT_LINE; // Default plotdef is a line ! protected String sourceName = ""; protected Source source = null; protected Color color = Color.BLACK; // Default color is black ! ! // ================================================================ ! // -- Constructors ! // ================================================================ PlotDef() { } *************** *** 65,75 **** visible = false; } ! ! PlotDef( String sourceName, Color color, int lineWidth ) ! { ! this( sourceName, color ); ! this.lineWidth = lineWidth; ! } ! PlotDef( Source source, Color color, boolean stacked, boolean visible ) { --- 67,71 ---- visible = false; } ! PlotDef( Source source, Color color, boolean stacked, boolean visible ) { *************** *** 80,85 **** } // ================================================================ ! void setSource( Source[] sources, HashMap sourceIndex ) throws RrdException { --- 76,83 ---- } + // ================================================================ ! // -- Protected methods ! // ================================================================ void setSource( Source[] sources, HashMap sourceIndex ) throws RrdException { *************** *** 92,122 **** // Default draw is a standard line ! void draw( ChartGraphics g, int[] xValues, int[] stackValues, int lastPlotType ) throws RrdException ! { ! g.setColor( color ); ! g.setStroke( new BasicStroke(lineWidth) ); ! ! int ax = 0, ay = 0; ! int nx = 0, ny = 0, last = -1; ! ! for (int i = 0; i < xValues.length; i++) ! { ! nx = xValues[i]; ! ny = g.getY( source.values[i] ); ! ! if ( stacked && ny != Integer.MIN_VALUE ) ! ny += stackValues[i]; ! ! if ( visible && ny != Double.NaN && nx != 0 && ay != Integer.MIN_VALUE && ny != Integer.MIN_VALUE ) ! g.drawLine( ax, ay, nx, ny ); ! ! stackValues[i] = ny; ! ax = nx; ! ay = ny; ! } - g.setStroke( new BasicStroke() ); - } - double getValue( int tblPos, long[] timestamps ) { --- 90,95 ---- // Default draw is a standard line ! abstract void draw( ChartGraphics g, int[] xValues, int[] stackValues, int lastPlotType ) throws RrdException; double getValue( int tblPos, long[] timestamps ) { *************** *** 125,128 **** --- 98,103 ---- // ================================================================ + // -- Private methods + // ================================================================ Source getSource() { return source; *************** *** 139,146 **** Color getColor() { return color; - } - - int getLineWidth() { - return lineWidth; } } --- 114,117 ---- Index: ValueFormatter.java =================================================================== RCS file: /cvsroot/jrobin/src/jrobin/graph2/ValueFormatter.java,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** ValueFormatter.java 22 Oct 2003 21:06:53 -0000 1.2 --- ValueFormatter.java 24 Oct 2003 21:15:34 -0000 1.3 *************** *** 54,57 **** --- 54,58 ---- private double scaledValue; private int scaleIndex = NO_SCALE; // Last used scale index + private int fixedIndex = NO_SCALE; private String prefix; *************** *** 61,67 **** } ! ValueFormatter( double base ) { setBase( base ); } --- 62,69 ---- } ! ValueFormatter( double base, int scaleIndex ) { setBase( base ); + this.fixedIndex = scaleIndex; } *************** *** 75,81 **** void setScaling( boolean normalScale, boolean uniformScale ) { ! scale = (normalScale || uniformScale); ! if ( !uniformScale ) ! this.scaleIndex = NO_SCALE; } --- 77,89 ---- void setScaling( boolean normalScale, boolean uniformScale ) { ! if ( fixedIndex >= 0 ) { ! scale = true; ! scaleIndex = fixedIndex; ! } ! else { ! scale = (normalScale || uniformScale); ! if ( !uniformScale ) ! scaleIndex = NO_SCALE; ! } } *************** *** 103,106 **** --- 111,126 ---- } + // returns a more 'rounded' value for grid steps + String getScaledValue() + { + scaleValue( scaleIndex ); + long intVal = new Double( scaledValue ).longValue(); + + if ( intVal == scaledValue ) + return "" + intVal; + else + return "" + scaledValue; + } + private void scaleValue( int scaleIndex) { *************** *** 158,172 **** private DecimalFormat getDecimalFormat(int numDec) { ! String formatStr = "###0"; // "#,##0", removed the 'grouping' separator for(int i = 0; i < numDec; i++) { if(i == 0) { ! formatStr += "."; } ! formatStr += "0"; } ! NumberFormat nf = NumberFormat.getNumberInstance(Locale.ENGLISH); ! DecimalFormat df = (DecimalFormat) nf; ! df.applyPattern( formatStr ); return df; --- 178,192 ---- private DecimalFormat getDecimalFormat(int numDec) { ! StringBuffer formatStr = new StringBuffer("###0"); // "#,##0", removed the 'grouping' separator for(int i = 0; i < numDec; i++) { if(i == 0) { ! formatStr.append('.'); } ! formatStr.append('0'); } ! NumberFormat nf = NumberFormat.getNumberInstance(Locale.ENGLISH); ! DecimalFormat df = (DecimalFormat) nf; ! df.applyPattern( formatStr.toString() ); return df; --- ValueScaler.java DELETED --- |
From: <cob...@us...> - 2003-10-24 21:18:12
|
Update of /cvsroot/jrobin/src/jrobin/demo In directory sc8-pr-cvs1:/tmp/cvs-serv5465/src/jrobin/demo Modified Files: ProfileGraphsOld.java ProfileGraphsNew.java JRobinComplexGraph.java Log Message: New graph lib Finetuning, tweaking, general clean-up Index: ProfileGraphsOld.java =================================================================== RCS file: /cvsroot/jrobin/src/jrobin/demo/ProfileGraphsOld.java,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** ProfileGraphsOld.java 22 Oct 2003 21:06:53 -0000 1.2 --- ProfileGraphsOld.java 24 Oct 2003 21:15:34 -0000 1.3 *************** *** 52,56 **** // Demo sake ! private GregorianCalendar startDate = new GregorianCalendar(2003, 7, 24, 00, 00); private GregorianCalendar endDate = new GregorianCalendar(2003, 7, 25, 00, 00); --- 52,56 ---- // Demo sake ! private GregorianCalendar startDate = new GregorianCalendar(2002, 7, 24, 00, 00); private GregorianCalendar endDate = new GregorianCalendar(2003, 7, 25, 00, 00); Index: ProfileGraphsNew.java =================================================================== RCS file: /cvsroot/jrobin/src/jrobin/demo/ProfileGraphsNew.java,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** ProfileGraphsNew.java 22 Oct 2003 21:06:53 -0000 1.2 --- ProfileGraphsNew.java 24 Oct 2003 21:15:34 -0000 1.3 *************** *** 47,56 **** private int demoNum; ! private PrintWriter out; private RrdGraph graph; private JRobinTimeProfiler profiler; // Demo sake ! private GregorianCalendar startDate = new GregorianCalendar(2003, 7, 24, 00, 30); private GregorianCalendar endDate = new GregorianCalendar(2003, 7, 25, 00, 00); --- 47,56 ---- private int demoNum; ! private PrintWriter out; private RrdGraph graph; private JRobinTimeProfiler profiler; // Demo sake ! private GregorianCalendar startDate = new GregorianCalendar(2002, 7, 24, 00, 30); private GregorianCalendar endDate = new GregorianCalendar(2003, 7, 25, 00, 00); Index: JRobinComplexGraph.java =================================================================== RCS file: /cvsroot/jrobin/src/jrobin/demo/JRobinComplexGraph.java,v retrieving revision 1.12 retrieving revision 1.13 diff -C2 -d -r1.12 -r1.13 *** JRobinComplexGraph.java 23 Oct 2003 23:16:36 -0000 1.12 --- JRobinComplexGraph.java 24 Oct 2003 21:15:34 -0000 1.13 *************** *** 45,50 **** public static void main(String[] args) { ! GregorianCalendar start = new GregorianCalendar(2003, 7, 24, 00, 00); ! GregorianCalendar end = new GregorianCalendar(2003, 7, 25, 00, 00); try --- 45,50 ---- public static void main(String[] args) { ! GregorianCalendar start = new GregorianCalendar(2002, 7, 24, 0, 0); ! GregorianCalendar end = new GregorianCalendar(2003, 7, 25, 0, 0); try *************** *** 65,69 **** gl.setImageBorder( Color.BLACK, 1 ); gl.setDefaultFontColor( Color.WHITE ); ! gl.setTitleFontColor( Color.GREEN ); gl.setMajorGridColor(Color.YELLOW); gl.setMinorGridColor( new Color( 130, 30, 30) ); --- 65,69 ---- gl.setImageBorder( Color.BLACK, 1 ); gl.setDefaultFontColor( Color.WHITE ); ! gl.setTitleFontColor( Color.PINK ); gl.setMajorGridColor(Color.YELLOW); gl.setMinorGridColor( new Color( 130, 30, 30) ); *************** *** 75,81 **** //gl.setFrontGrid(false); gl.setShowLegend(true); //gl.setUnitsExponent(3); //gl.setAntiAliasing(false); ! gl.setGridRange( 0, 1, false ); //gl.setBackground( "/demo6.png" ); //gl.setOverlay( "/overview.gif" ); --- 75,82 ---- //gl.setFrontGrid(false); gl.setShowLegend(true); + //gl.setShowSignature(false); //gl.setUnitsExponent(3); //gl.setAntiAliasing(false); ! //gl.setGridRange( 0, 10, false ); //gl.setBackground( "/demo6.png" ); //gl.setOverlay( "/overview.gif" ); *************** *** 125,132 **** //gl.hrule( 3.0, null, "legende", 1); //gl.vrule( new GregorianCalendar(2003, 7, 24, 9, 00), Color.BLUE, "9am", 2 ); ! gl.area( new GregorianCalendar(2003, 7, 24, 9, 00), Double.MIN_VALUE, new GregorianCalendar(2003, 7, 24, 17, 00), Double.MAX_VALUE, Color.ORANGE, "deviation@r" ); ! gl.area( new GregorianCalendar(2003, 7, 24, 8, 00), Double.MIN_VALUE, new GregorianCalendar(2003, 7, 24, 10, 00), Double.MAX_VALUE, Color.PINK, null ); ! gl.area( new GregorianCalendar(2003, 7, 24, 16, 00), Double.MIN_VALUE, new GregorianCalendar(2003, 7, 24, 18, 00), 12, Color.PINK, null ); ! gl.stack("load", Color.BLUE, "hmm"); gl.comment("\n-------------------------------------------------------------------------------@c"); --- 126,133 ---- //gl.hrule( 3.0, null, "legende", 1); //gl.vrule( new GregorianCalendar(2003, 7, 24, 9, 00), Color.BLUE, "9am", 2 ); ! //gl.area( new GregorianCalendar(2003, 7, 24, 9, 00), Double.MIN_VALUE, new GregorianCalendar(2003, 7, 24, 17, 00), Double.MAX_VALUE, Color.ORANGE, "deviation@r" ); ! //gl.area( new GregorianCalendar(2003, 7, 24, 8, 00), Double.MIN_VALUE, new GregorianCalendar(2003, 7, 24, 10, 00), Double.MAX_VALUE, Color.PINK, null ); ! //gl.area( new GregorianCalendar(2003, 7, 24, 16, 00), Double.MIN_VALUE, new GregorianCalendar(2003, 7, 24, 18, 00), 12, Color.PINK, null ); ! //gl.stack("load", Color.BLUE, "hmm"); gl.comment("\n-------------------------------------------------------------------------------@c"); |
From: <cob...@us...> - 2003-10-24 17:42:11
|
Update of /cvsroot/jrobin/src/jrobin/demo In directory sc8-pr-cvs1:/tmp/cvs-serv5766/src/jrobin/demo Modified Files: JRobinGallery.java JRobinComplexGraph.java Log Message: New graph lib Switched to new FetchData method Index: JRobinGallery.java =================================================================== RCS file: /cvsroot/jrobin/src/jrobin/demo/JRobinGallery.java,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** JRobinGallery.java 22 Oct 2003 21:06:53 -0000 1.3 --- JRobinGallery.java 23 Oct 2003 23:16:36 -0000 1.4 *************** *** 16,20 **** * To change this template use Options | File Templates. */ ! public class JRobinGallery { public static void graph7() throws RrdException, IOException { RrdGraphDef def = new RrdGraphDef(); --- 16,21 ---- * To change this template use Options | File Templates. */ ! public class JRobinGallery ! { public static void graph7() throws RrdException, IOException { RrdGraphDef def = new RrdGraphDef(); Index: JRobinComplexGraph.java =================================================================== RCS file: /cvsroot/jrobin/src/jrobin/demo/JRobinComplexGraph.java,v retrieving revision 1.11 retrieving revision 1.12 diff -C2 -d -r1.11 -r1.12 *** JRobinComplexGraph.java 22 Oct 2003 21:06:53 -0000 1.11 --- JRobinComplexGraph.java 23 Oct 2003 23:16:36 -0000 1.12 *************** *** 79,83 **** gl.setGridRange( 0, 1, false ); //gl.setBackground( "/demo6.png" ); ! //gl.setOverlay( "/demo6.png" ); gl.datasource("load", "c:/test.rrd", "serverLoad", "AVERAGE"); gl.datasource("user", "c:/test.rrd", "serverCPUUser", "AVERAGE"); --- 79,83 ---- gl.setGridRange( 0, 1, false ); //gl.setBackground( "/demo6.png" ); ! //gl.setOverlay( "/overview.gif" ); gl.datasource("load", "c:/test.rrd", "serverLoad", "AVERAGE"); gl.datasource("user", "c:/test.rrd", "serverCPUUser", "AVERAGE"); |
From: <cob...@us...> - 2003-10-24 16:21:56
|
Update of /cvsroot/jrobin/src/jrobin/graph2 In directory sc8-pr-cvs1:/tmp/cvs-serv5766/src/jrobin/graph2 Modified Files: FetchSource.java ValueExtractor.java Grapher.java RrdGraphDef.java RrdGraph.java Log Message: New graph lib Switched to new FetchData method Index: FetchSource.java =================================================================== RCS file: /cvsroot/jrobin/src/jrobin/graph2/FetchSource.java,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** FetchSource.java 21 Oct 2003 19:41:57 -0000 1.1 --- FetchSource.java 23 Oct 2003 23:16:35 -0000 1.2 *************** *** 29,33 **** import jrobin.core.RrdDb; ! import jrobin.core.FetchPoint; import jrobin.core.FetchRequest; import jrobin.core.RrdException; --- 29,33 ---- import jrobin.core.RrdDb; ! import jrobin.core.FetchData; import jrobin.core.FetchRequest; import jrobin.core.RrdException; *************** *** 53,57 **** private Vector[] datasources = new Vector[MAX_CF]; ! FetchSource( String rrdFile ) { this.rrdFile = rrdFile; --- 53,57 ---- private Vector[] datasources = new Vector[MAX_CF]; ! protected FetchSource( String rrdFile ) { this.rrdFile = rrdFile; *************** *** 62,66 **** } ! FetchSource( String rrdFile, String consolFunc, String dsName, String name ) throws RrdException { this( rrdFile ); --- 62,66 ---- } ! protected FetchSource( String rrdFile, String consolFunc, String dsName, String name ) throws RrdException { this( rrdFile ); *************** *** 68,72 **** } ! void addSource( String consolFunc, String dsName, String name ) throws RrdException { if ( consolFunc.equalsIgnoreCase("AVERAGE") || consolFunc.equalsIgnoreCase("AVG") ) --- 68,72 ---- } ! protected void addSource( String consolFunc, String dsName, String name ) throws RrdException { if ( consolFunc.equalsIgnoreCase("AVERAGE") || consolFunc.equalsIgnoreCase("AVG") ) *************** *** 84,124 **** } ! String getRrdFile() { return rrdFile; } ! ValueExtractor fetch( RrdDb rrd, long startTime, long endTime ) throws IOException, RrdException { ! long rrdStep = rrd.getRrdDef().getStep(); ! FetchPoint[][] result = new FetchPoint[datasources.length][]; ! int[][] indices = new int[MAX_CF][]; for (int i = 0; i < datasources.length; i++) { if ( datasources[i].size() > 0 ) { // Fetch datasources FetchRequest request = rrd.createFetchRequest( cfNames[i], startTime, endTime + rrdStep); ! FetchPoint[] fetchPoints = request.fetch(); ! result[i] = fetchPoints; ! indices[i] = new int[datasources[i].size()]; } - else - indices[i] = new int[0]; } - - String[] names = new String[numSources]; - int tblPos = 0; ! for (int i = 0; i < datasources.length; i++) { ! for (int j = 0; j < datasources[i].size(); j++) { ! String[] spair = (String[])datasources[i].elementAt(j); ! indices[i][j] = rrd.getDsIndex(spair[0]); ! names[tblPos++] = spair[1]; ! } ! } ! ! return new ValueExtractor( names, indices, result ); } --- 84,127 ---- } ! protected String getRrdFile() { return rrdFile; } ! protected ValueExtractor fetch ( RrdDb rrd, long startTime, long endTime ) throws IOException, RrdException { ! long rrdStep = rrd.getRrdDef().getStep(); ! FetchData[] result = new FetchData[datasources.length]; ! ! String[] names = new String[numSources]; ! int tblPos = 0; for (int i = 0; i < datasources.length; i++) { if ( datasources[i].size() > 0 ) { + // Set the list of ds names + String[] dsNames = new String[ datasources[i].size() ]; + String[] vNames = new String[ datasources[i].size() ]; + + for (int j = 0; j < dsNames.length; j++ ) { + String[] spair = (String[])datasources[i].elementAt(j); + dsNames[j] = spair[0]; + vNames[j] = spair[1]; + } // Fetch datasources FetchRequest request = rrd.createFetchRequest( cfNames[i], startTime, endTime + rrdStep); ! request.setFilter( dsNames ); ! FetchData data = request.fetchData(); ! ! for (int j = 0; j < vNames.length; j++) ! names[ data.getDsIndex(dsNames[j]) + tblPos ] = vNames[j]; ! tblPos += dsNames.length; ! ! result[i] = data; } } ! return new ValueExtractor( names, result ); } Index: ValueExtractor.java =================================================================== RCS file: /cvsroot/jrobin/src/jrobin/graph2/ValueExtractor.java,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** ValueExtractor.java 21 Oct 2003 19:41:58 -0000 1.1 --- ValueExtractor.java 23 Oct 2003 23:16:35 -0000 1.2 *************** *** 25,29 **** package jrobin.graph2; ! import jrobin.core.FetchPoint; import jrobin.core.RrdException; --- 25,29 ---- package jrobin.graph2; ! import jrobin.core.FetchData; import jrobin.core.RrdException; *************** *** 31,76 **** * <p>Class used to extract specific time-based values, out of a number of fetched datasources.</p> * ! * @author Arne Vandamme (arn...@jr...) */ class ValueExtractor { private String[] varNames; // Name of the variable, NOT it's dsName in the file ! private int[][] varIndices; // Index of a variable in the FetchPoint value table ! private int[][] timePos; ! private FetchPoint[][] values; ! ValueExtractor( String[] names, int[][] indices, FetchPoint[][] values ) { this.varNames = names; - this.varIndices = indices; - this.values = values; ! timePos = new int[indices.length][]; ! for (int i = 0; i < indices.length; i++) ! timePos[i] = new int[ indices[i].length ]; } // Return the table position offset for the next datasource ! int extract( long timestamp, Source[] sources, int row, int offset ) throws RrdException { ! int tblPos = offset; ! ! for ( int i = 0; i < varIndices.length; i++ ) { ! for (int j = 0; j < varIndices[i].length; j++) { ! if ( timestamp < values[i][ timePos[i][j] ].getTime() ) ! throw new RrdException("Backward reading not allowed"); ! ! while( timePos[i][j] < values[i].length - 1 ) ! { ! if ( values[i][ timePos[i][j] ].getTime() <= timestamp ! && timestamp < values[i][ timePos[i][j] + 1 ].getTime() ) { ! sources[tblPos++].set( row, timestamp, values[i][ timePos[i][j] + 1 ].getValue( varIndices[i][j] ) ); ! break; ! } ! else ! timePos[i][j]++; } } } --- 31,89 ---- * <p>Class used to extract specific time-based values, out of a number of fetched datasources.</p> * ! * @author Arne Vandamme (cob...@jr...) */ class ValueExtractor { private String[] varNames; // Name of the variable, NOT it's dsName in the file ! ! private int[] tPos; ! private long[][] timestamps; ! private double[][][] dsValues; ! protected ValueExtractor( String[] names, FetchData[] values ) { this.varNames = names; ! // Set timestamps ! tPos = new int[values.length]; ! timestamps = new long[values.length][]; ! dsValues = new double[values.length][][]; ! ! for (int i = 0; i < timestamps.length; i++) { ! if ( values[i] != null ) { ! timestamps[i] = values[i].getTimestamps(); ! dsValues[i] = values[i].getValues(); ! } ! } } // Return the table position offset for the next datasource ! protected int extract( long timestamp, Source[] sources, int row, int offset ) throws RrdException { ! int tblPos = offset; ! ! for ( int i = 0; i < dsValues.length; i++ ) ! { ! if ( dsValues[i] == null ) ! continue; ! ! int tIndex = tPos[i]; ! ! if ( timestamp < timestamps[i][ tIndex ] ) ! throw new RrdException("Backward reading not allowed"); ! ! while ( tIndex < timestamps[i].length - 1 ) { ! if ( timestamps[i][ tIndex ] <= timestamp && timestamp < timestamps[i][ tIndex + 1] ) { ! for (int j = 0; j < dsValues[i].length; j++) ! sources[tblPos++].set( row, timestamp, dsValues[i][j][ tIndex + 1 ] ); ! break; ! } ! else { ! tIndex++; } } + + tPos[i] = tIndex; } *************** *** 78,82 **** } ! String[] getNames() { return varNames; } --- 91,95 ---- } ! protected String[] getNames() { return varNames; } Index: Grapher.java =================================================================== RCS file: /cvsroot/jrobin/src/jrobin/graph2/Grapher.java,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** Grapher.java 22 Oct 2003 21:06:53 -0000 1.2 --- Grapher.java 23 Oct 2003 23:16:35 -0000 1.3 *************** *** 49,89 **** * <p>Creates a BufferedImage of a graph, based on data from a GraphDef.</p> * ! * @author Arne Vandamme (arn...@jr...) */ class Grapher { ! private static final String SPACER = " "; ! private static final int GRAPH_RESOLUTION = 1000; ! private static final int DEFAULT_WIDTH = 400; ! private static final int DEFAULT_HEIGHT = 100; // Border space definitions ! private static final int UBORDER_SPACE = 10; ! private static final int BBORDER_SPACE = 16; ! private static final int LBORDER_SPACE = 10; ! private static final int RBORDER_SPACE = 10; ! ! public static final int CHART_UPADDING = 5; ! public static final int CHART_BPADDING = 25; ! public static final int CHART_RPADDING = 10; ! public static final int CHART_LPADDING = 50; // Default lpadding ! public static final int CHART_BPADDING_NM = 10; // No legend makers on the axis ! public static final int CHART_LPADDING_NM = 10; ! public static final int LINE_PADDING = 4; ! //public static final int DEFAULT_ALIGN = Comment.ALIGN_LEFT; ! private Font title_font = new Font("Lucida Sans Typewriter", Font.BOLD, 12); ! private Font normal_font = new Font("Lucida Sans Typewriter", Font.PLAIN, 10); ! private int numPoints = GRAPH_RESOLUTION; ! private int chart_lpadding, chart_bpadding; // Padding on the left and below the chart area ! private int imgWidth, imgHeight; // Dimensions of the entire image ! private int chartWidth, chartHeight; // Dimensions of the chart area within the image ! private int nfont_width, nfont_height, tfont_width, tfont_height; // Font specs ! private int commentBlock; // Size in pixels of the block below the chart itself ! private int graphOriginX, graphOriginY, x_offset, y_offset; --- 49,92 ---- * <p>Creates a BufferedImage of a graph, based on data from a GraphDef.</p> * ! * @author Arne Vandamme (cob...@jr...) */ class Grapher { ! // ================================================================ ! // -- Members ! // ================================================================ ! protected static final String SPACER = " "; // default comment spacer (two blank spaces) ! protected static final int GRAPH_RESOLUTION = 1000; // default graph resolution ! protected static final int DEFAULT_WIDTH = 400; // default width in pixels of the chart area ! protected static final int DEFAULT_HEIGHT = 100; // default height in pixels of the chart area // Border space definitions ! protected static final int UBORDER_SPACE = 10; // padding from graph upper border ! protected static final int BBORDER_SPACE = 16; // padding from graph lower border ! protected static final int LBORDER_SPACE = 10; // padding from graph left border ! protected static final int RBORDER_SPACE = 10; // padding from graph right border ! protected static final int CHART_UPADDING = 5; // padding space above the chart area ! protected static final int CHART_BPADDING = 25; // default padding space below the chart area ! protected static final int CHART_RPADDING = 10; // padding space on the right of the chart area ! protected static final int CHART_LPADDING = 50; // default padding space on the left of the chart area ! protected static final int CHART_BPADDING_NM = 10; // default padding below chart if no legend markers ! protected static final int CHART_LPADDING_NM = 10; // default padding left of chart if no legend markers ! protected static final int LINE_PADDING = 4; // default padding between two consecutive text lines ! // Default fonts ! protected static final Font TITLE_FONT = new Font("Lucida Sans Typewriter", Font.BOLD, 12); ! protected static final Font NORMAL_FONT = new Font("Lucida Sans Typewriter", Font.PLAIN, 10); ! private Font title_font = TITLE_FONT; // font used for the title ! private Font normal_font = NORMAL_FONT; // font used for all default text ! private int numPoints = GRAPH_RESOLUTION; // number of points used to calculate the graph ! private int chart_lpadding, chart_bpadding; // calculated padding on the left and below the chart area ! private int imgWidth, imgHeight; // dimensions of the entire image ! private int chartWidth, chartHeight; // dimensions of the chart area within the image ! private int nfont_width, nfont_height, tfont_width, tfont_height; // font dimennsion specs (approximated) ! private int commentBlock; // size in pixels of the block below the chart itself private int graphOriginX, graphOriginY, x_offset, y_offset; *************** *** 107,110 **** --- 110,123 ---- Calendar c = Calendar.getInstance(); + + // ================================================================ + // -- Constructors + // ================================================================ + /** + * Constructs a grapher object, used for creating a graph image based on a <code>RrdGraphDef</code> object. + * A reference to a <code>RrdGraph</code> object is kept for <code>RrdDb</code> pooling. + * @param graphDef Graph definition for the graph to be created. + * @param rrdGraph RrdGraph object that takes care of saving the images. + */ Grapher( RrdGraphDef graphDef, RrdGraph rrdGraph ) { *************** *** 112,123 **** this.rrdGraph = rrdGraph; ! // Set font specifics if ( graphDef.normalFont != null ) ! normal_font = graphDef.normalFont; if ( graphDef.titleFont != null ) ! title_font = graphDef.titleFont; nfont_height = normal_font.getSize(); // Determine font dimensions for regular comment font nfont_width = nfont_height / 2 + 1; // Bold font is higher tfont_height = ( title_font.isBold() ? title_font.getSize() + 2 : title_font.getSize() ); --- 125,137 ---- this.rrdGraph = rrdGraph; ! // Set font dimension specifics if ( graphDef.normalFont != null ) ! normal_font = graphDef.getDefaultFont(); if ( graphDef.titleFont != null ) ! title_font = graphDef.getTitleFont(); nfont_height = normal_font.getSize(); // Determine font dimensions for regular comment font nfont_width = nfont_height / 2 + 1; + // Bold font is higher tfont_height = ( title_font.isBold() ? title_font.getSize() + 2 : title_font.getSize() ); *************** *** 125,164 **** // Create the shared valueformatter ! valueFormat = new ValueFormatter( graphDef.baseValue ); } /** * Creates the actual graph based on the GraphDef definition. * @param cWidth Width of the chart area in pixels. * @param cHeight Height of the chart area in pixels. * @return The created graph as a BufferedImage. ! * @throws RrdException Thrown in case of a JRobin specific error, or a I/O error. */ ! BufferedImage createImage( int cWidth, int cHeight ) throws RrdException { // Calculate chart dimensions ! chartWidth = ( cWidth == 0 ? DEFAULT_WIDTH : cWidth ); ! chartHeight = ( cHeight == 0 ? DEFAULT_HEIGHT : cHeight ); if ( cWidth > GRAPH_RESOLUTION ) numPoints = cWidth; // Padding depends on grid visibility ! chart_lpadding = ( graphDef.majorGridX ? graphDef.chart_lpadding : CHART_LPADDING_NM ); ! chart_bpadding = ( graphDef.majorGridX ? CHART_BPADDING : CHART_BPADDING_NM ); // Size of all lines below chart ! commentBlock = 0; ! if ( graphDef.showLegend ) ! commentBlock = graphDef.getCommentLineCount() * (nfont_height + LINE_PADDING) - LINE_PADDING; ! x_offset = LBORDER_SPACE; ! if ( graphDef.valueAxisLabel != null ) x_offset += nfont_height + LINE_PADDING; ! imgWidth = chartWidth + x_offset + RBORDER_SPACE + chart_lpadding + CHART_RPADDING; ! y_offset = UBORDER_SPACE; ! ! // Title *always* gets a extra LF automatically ! if ( graphDef.title != null ) y_offset += ((tfont_height + LINE_PADDING) * graphDef.title.getLineCount() + tfont_height) + LINE_PADDING; ! imgHeight = chartHeight + commentBlock + y_offset + BBORDER_SPACE + CHART_UPADDING + CHART_BPADDING; // Create graphics object --- 139,185 ---- // Create the shared valueformatter ! valueFormat = new ValueFormatter( graphDef.getBaseValue() ); } + + // ================================================================ + // -- Protected (package) methods + // ================================================================ /** * Creates the actual graph based on the GraphDef definition. + * The graph is created as a <code>java.awt.image.BufferedImage</code>. * @param cWidth Width of the chart area in pixels. * @param cHeight Height of the chart area in pixels. * @return The created graph as a BufferedImage. ! * @throws RrdException Thrown in case of a JRobin specific error. ! * @throws IOException Thrown in case of a I/O related error. */ ! protected BufferedImage createImage( int cWidth, int cHeight ) throws RrdException, IOException { // Calculate chart dimensions ! chartWidth = ( cWidth == 0 ? DEFAULT_WIDTH : cWidth ); ! chartHeight = ( cHeight == 0 ? DEFAULT_HEIGHT : cHeight ); if ( cWidth > GRAPH_RESOLUTION ) numPoints = cWidth; // Padding depends on grid visibility ! chart_lpadding = ( graphDef.showMajorGridY() ? graphDef.getChartLeftPadding() : CHART_LPADDING_NM ); ! chart_bpadding = ( graphDef.showMajorGridX() ? CHART_BPADDING : CHART_BPADDING_NM ); // Size of all lines below chart ! commentBlock = 0; ! if ( graphDef.showLegend() ) ! commentBlock = graphDef.getCommentLineCount() * (nfont_height + LINE_PADDING) - LINE_PADDING; ! // x_offset and y_offset define the starting corner of the actual graph ! x_offset = LBORDER_SPACE; ! if ( graphDef.valueAxisLabel != null ) ! x_offset += nfont_height + LINE_PADDING; ! imgWidth = chartWidth + x_offset + RBORDER_SPACE + chart_lpadding + CHART_RPADDING; ! y_offset = UBORDER_SPACE; ! if ( graphDef.title != null ) // Title *always* gets a extra LF automatically ! y_offset += ((tfont_height + LINE_PADDING) * graphDef.getTitle().getLineCount() + tfont_height) + LINE_PADDING; ! imgHeight = chartHeight + commentBlock + y_offset + BBORDER_SPACE + CHART_UPADDING + CHART_BPADDING; // Create graphics object *************** *** 170,198 **** // Do the actual graphing ! try ! { ! calculateSeries(); ! plotImageBackground( graphics ); ! plotChart( graphics ); ! if ( graphDef.showLegend ) ! plotComments( graphics ); ! plotOverlay( graphics ); ! if ( graphDef.drawSignature ) ! plotSignature( graphics ); ! } ! catch (IOException e) ! { ! throw new RrdException( "Error retrieving data from RRD." ); ! } ! catch (RrdException e) ! { ! //throw new RrdException( e.getMessage() ); ! e.printStackTrace(); ! } // Dispose graphics context --- 191,206 ---- // Do the actual graphing ! calculateSeries(); // calculate all datasources ! plotImageBackground( graphics ); // draw the image background ! plotChart( graphics ); // draw the actual chart ! plotComments( graphics ); // draw all comment lines ! plotOverlay( graphics ); // draw a possible image overlay ! plotSignature( graphics ); // draw the JRobin signature ! // Dispose graphics context *************** *** 202,213 **** } ! private void plotSignature( Graphics2D g ) { ! Font sigFont = new Font("Courier", Font.PLAIN, 10); ! String sig = "www.jrobin.org"; ! g.setColor( Color.GRAY ); ! g.setFont( sigFont ); ! g.drawString( sig, imgWidth / 2 - (sig.length() * 5) / 2, imgHeight - 5 ); } --- 210,303 ---- } ! ! // ================================================================ ! // -- Private methods ! // ================================================================ ! /** ! * Fetches and calculates all datasources used in the graph. ! * @throws RrdException Thrown in case of a JRobin specific error. ! * @throws IOException Thrown in case of a I/O related error. ! */ ! private void calculateSeries() throws RrdException, IOException { ! Util.time(); ! ! ValueExtractor ve; ! FetchSource src; ! RrdDb rrd; ! String[] varList; ! long startTime = graphDef.getStartTime(); ! long endTime = graphDef.getEndTime(); ! ! int numDefs = graphDef.getNumDefs(); ! ! Cdef[] cdefList = graphDef.getCdefs(); ! int numCdefs = cdefList.length; ! ! // Set up the array with all datasources (both Def and Cdef) ! sources = new Source[ numDefs + numCdefs ]; ! sourceIndex = new HashMap( numDefs + numCdefs ); ! int tblPos = 0; ! int vePos = 0; ! ! ValueExtractor[] veList = new ValueExtractor[ graphDef.getFetchSources().size() ]; ! Iterator fetchSources = graphDef.getFetchSources().values().iterator(); ! ! while ( fetchSources.hasNext() ) ! { ! // Get the rrdDb ! src = (FetchSource) fetchSources.next(); ! rrd = rrdGraph.getRrd( src.getRrdFile() ); ! ! // Fetch all required datasources ! ve = src.fetch( rrd, startTime, endTime ); ! varList = ve.getNames(); ! ! for (int i= 0; i < varList.length; i++) { ! sources[tblPos] = new Def(varList[i], numPoints); ! sourceIndex.put( varList[i], new Integer(tblPos++) ); ! } ! ! veList[ vePos++ ] = ve; ! } ! ! // Add all Cdefs to the source table ! // Reparse all RPN datasources to use indices of the correct variables ! for ( int i = 0; i < cdefList.length; i++ ) ! { ! cdefList[i].prepare( sourceIndex, numPoints ); ! ! sources[tblPos] = cdefList[i]; ! sourceIndex.put( cdefList[i].getName(), new Integer(tblPos++) ); ! } ! ! // RPN calculator for the Cdefs ! RpnCalculator rpnCalc = new RpnCalculator( sources ); ! ! // Fill the array for all datasources ! timestamps = new long[numPoints]; ! ! for (int i = 0; i < numPoints; i++) ! { ! long t = (long) (startTime + i * ((endTime - startTime) / (double)(numPoints - 1))); ! int pos = 0; ! ! // Get all fetched datasources ! for (int j = 0; j < veList.length; j++) ! pos = veList[j].extract( t, sources, i, pos ); ! ! // Get all combined datasources ! for (int j = pos; j < sources.length; j++) ! sources[j].set(i, t, rpnCalc.evaluate( (Cdef) sources[j], i, t ) ); ! ! timestamps[i] = t; ! } ! ! // Clean up the fetched datasources forcibly ! veList = null; ! ! // DEBUG - calculate checkpoint ! Util.time(1); } *************** *** 249,252 **** --- 339,344 ---- private void plotComments( Graphics2D g ) throws RrdException { + if ( !graphDef.showLegend() ) return; + Util.time(); *************** *** 354,441 **** /** - * Fetches and calculates all datasources used in the graph. - */ - private void calculateSeries() throws RrdException, IOException - { - Util.time(); - - long startTime = graphDef.startTime; - long endTime = graphDef.endTime; - - int numDefs = graphDef.numDefs; - int numCdefs = graphDef.cdefList.size(); - - ValueExtractor ve; - FetchSource src; - RrdDb rrd; - String[] varList; - - // Set up the array for all datasources - sources = new Source[ numDefs + numCdefs ]; - sourceIndex = new HashMap( numDefs + numCdefs ); - int tblPos = 0; - - Vector veList = new Vector(); - Iterator fetchSources = graphDef.fetchSources.values().iterator(); - - while ( fetchSources.hasNext() ) - { - // Get the rrdDb - src = (FetchSource) fetchSources.next(); - rrd = rrdGraph.getRrd( src.getRrdFile() ); - - // Fetch all required datasources - ve = src.fetch( rrd, startTime, endTime ); - varList = ve.getNames(); - - for (int i= 0; i < varList.length; i++) { - sources[tblPos] = new Def(varList[i], numPoints); - sourceIndex.put( varList[i], new Integer(tblPos++) ); - } - - veList.add( ve ); - } - - // Add all Cdefs to the source table - // Reparse all RPN datasources to use indices of the correct variables - for ( int i = 0; i < graphDef.cdefList.size(); i++ ) - { - Cdef cdefSource = (Cdef) graphDef.cdefList.elementAt(i); - cdefSource.prepare( sourceIndex, numPoints ); - - sources[tblPos] = cdefSource; - sourceIndex.put( cdefSource.getName(), new Integer(tblPos++) ); - } - - RpnCalculator rpnCalc = new RpnCalculator( sources ); - - // Fill the array for all datasources, delete the fetched values - timestamps = new long[numPoints]; - - for (int i = 0; i < numPoints; i++) - { - long t = (long) (startTime + i * ((endTime - startTime) / (double)(numPoints - 1))); - int pos = 0; - - // Get all fetched datasources - for (int j = 0; j < veList.size(); j++) { - ve = (ValueExtractor) veList.elementAt(j); - pos = ve.extract( t, sources, i, pos ); - } - - // Get all combined datasources - for (int j = pos; j < sources.length; j++) - sources[j].set(i, t, rpnCalc.evaluate( (Cdef) sources[j], i, t ) ); - - timestamps[i] = t; - } - - veList.clear(); // Clean up the fetched datasources - - // DEBUG - calculate checkpoint - Util.time(1); - } - - /** * Draws the image background, title and value axis label. */ --- 446,449 ---- *************** *** 984,988 **** --- 992,1010 ---- } + /** + * Draws the standard JRobin signature on the image. + * @param g Handle of a Graphics2D context to draw on. + */ + private void plotSignature( Graphics2D g ) + { + if ( !graphDef.showSignature() ) + return; + + String sig = "www.jrobin.org"; + g.setColor( Color.GRAY ); + g.setFont( new Font("Courier", Font.PLAIN, 10) ); + g.drawString( sig, imgWidth / 2 - (sig.length() * 5) / 2, imgHeight - 5 ); + } } Index: RrdGraphDef.java =================================================================== RCS file: /cvsroot/jrobin/src/jrobin/graph2/RrdGraphDef.java,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** RrdGraphDef.java 22 Oct 2003 21:06:53 -0000 1.2 --- RrdGraphDef.java 23 Oct 2003 23:16:35 -0000 1.3 *************** *** 40,56 **** /** ! * <p>Class used to collect information for the new JRobin graph. JRobin graphs have many * options and this class has methods and properties to set them.</p> * ! * <p>At this moment, JRobin graphs are quite good looking, but RRDTool is still better. ! * However, JRobin graphs have almost the same potential as RRDTool's graph command. To learn ! * more about RRDTool's graphs see RRDTool's ! * <a href="../../../man/rrdgraph.html" target="man">rrdgraph man page</a>.</p> This man page * is important: JRobin uses the same concept of graph sources definition (DEF directives) * and supports RPN extensions in complex datasource definitions (RRDTool's CDEF directives).</p> * * <p><code>RrdGraphDef</code> class does not actually create any graph. It just collects necessary information. ! * Graph will be created when you pass <code>RrdGraphDef</code> object to the constructor ! * of {@link jrobin.graph.RrdGraph RrdGraph} object.</p> * * @author Arne Vandamme (arn...@jr...) --- 40,58 ---- /** ! * <p>Class used to collect information for a JRobin graph. JRobin graphs have many * options and this class has methods and properties to set them.</p> * ! * <p>The JRobin graph package was designed to create graphs that have the same look as the ! * RRDTool counter parts. Almost all the same graphing options are available, with some extra's ! * like more advanced text alignment and custom point-to-point lines and area's.</p> ! * ! * <p>To learn more about RDTool's graphs see RRDTool's ! * <a href="http://people.ee.ethz.ch/~oetiker/webtools/rrdtool/manual/rrdgraph.html" target="man">rrdgraph man page</a>. This man page * is important: JRobin uses the same concept of graph sources definition (DEF directives) * and supports RPN extensions in complex datasource definitions (RRDTool's CDEF directives).</p> * * <p><code>RrdGraphDef</code> class does not actually create any graph. It just collects necessary information. ! * Graph will be created when you pass <code>RrdGraphDef</code> object to a {@link jrobin.graph.RrdGraph RrdGraph}, either ! * by passing it to the constructor or using the <code>setGraphDef()</code> method.</p> * * @author Arne Vandamme (arn...@jr...) *************** *** 74,78 **** boolean majorGridX = true; // hide major X axis grid with labels (default: no) boolean majorGridY = true; // hide major Y axis grid with labels (default: no) - boolean rigidGrid = false; // disable auto scaling of grid range (default: no) boolean frontGrid = true; // show grid in front of the chart (default: yes) boolean antiAliasing = true; // use anti-aliasing for the chart (default: yes) --- 76,79 ---- *************** *** 97,132 **** File overlay = null; // no overlay image by default ! int chart_lpadding = Grapher.CHART_LPADDING; BasicStroke borderStroke = null; // defaults to standard beveled border ! TimeAxisUnit tAxis = null; ! boolean tAxisCentered = false; ! double valueGridStep = Double.NaN; ! double valueLabelStep = Double.NaN; ! double valueStep = 0; ! double baseValue = 1000; ! int scaleIndex = -1; // NO_SCALE ! GridRange gridRange = null; - int numDefs = 0; - int commentLines = 0; - int commentLineShift = 0; - HashMap fetchSources = new HashMap(); - Vector cdefList = new Vector(); - Vector plotDefs = new Vector(); - Vector comments = new Vector(); // ================================================================ // -- Constructors // ================================================================ /** ! * Constructs a new JRobin graph object. */ ! public RrdGraphDef() ! { ! // Default constructor } --- 98,137 ---- File overlay = null; // no overlay image by default ! int chart_lpadding = Grapher.CHART_LPADDING; // padding space on the left of the chart area ! ! double baseValue = ValueFormatter.DEFAULT_BASE; // unit base value to use (default: 1000) ! int scaleIndex = ValueFormatter.NO_SCALE; // fixed units exponent value to use BasicStroke borderStroke = null; // defaults to standard beveled border + TimeAxisUnit tAxis = null; // custom time axis grid, defaults to no custom + ValueAxisUnit vAxis = null; // custom value axis grid, defaults to no custom + GridRange gridRange = null; // custom value range definition, defaults to auto-scale ! // -- Non-settable members ! int numDefs = 0; // number of Def datasources added ! int commentLines = 0; // number of complete lines in the list of comment items ! int commentLineShift = 0; // modifier to add to get minimum one complete line of comments ! HashMap fetchSources = new HashMap(); // holds the list of FetchSources ! Vector cdefList = new Vector(); // holds the list of Cdef datasources ! Vector plotDefs = new Vector(); // holds the list of PlotDefs ! Vector comments = new Vector(); // holds the list of comment items + // REMOVE THESE + boolean tAxisCentered = false; + double valueGridStep = Double.NaN; + double valueLabelStep = Double.NaN; + double valueStep = 0; + + // ================================================================ // -- Constructors // ================================================================ /** ! * Constructs a new default JRobin graph object. */ ! public RrdGraphDef() { } *************** *** 135,139 **** * Using timestamps defined as number of seconds since the epoch. * @param startTime Starting timestamp in seconds. ! * @param endTime Ending timestamp in secons. * @throws RrdException Thrown if invalid parameters are supplied. */ --- 140,144 ---- * Using timestamps defined as number of seconds since the epoch. * @param startTime Starting timestamp in seconds. ! * @param endTime Ending timestamp in seconds. * @throws RrdException Thrown if invalid parameters are supplied. */ *************** *** 167,175 **** } // ================================================================ // -- Public methods // ================================================================ /** ! * Sets time span to be presented on the graph using timestamps. * @param startTime Starting timestamp in seconds. * @param endTime Ending timestamp in secons. --- 172,181 ---- } + // ================================================================ // -- Public methods // ================================================================ /** ! * Sets time span to be presented on the graph using timestamps in number of seconds. * @param startTime Starting timestamp in seconds. * @param endTime Ending timestamp in secons. *************** *** 218,226 **** /** * Sets vertical (value) axis label. ! * @param valueAxisLabel Axis label. */ ! public void setVerticalLabel( String valueAxisLabel) { ! this.valueAxisLabel = valueAxisLabel; } --- 224,232 ---- /** * Sets vertical (value) axis label. ! * @param label Vertical axis label. */ ! public void setVerticalLabel( String label) { ! this.valueAxisLabel = label; } *************** *** 235,240 **** /** ! * Sets chart area background color. If not set, back color defaults to white. ! * @param backColor Chart area background color. */ public void setCanvasColor( Color canvasColor ) --- 241,246 ---- /** ! * Sets chart area background color. If not set, canvas color defaults to white. ! * @param canvasColor Chart area background color. */ public void setCanvasColor( Color canvasColor ) *************** *** 257,261 **** /** ! * Sets the color of the title font used in the graph. * @param c The color to be used. */ --- 263,268 ---- /** ! * Sets the color of the title font used in the graph as a <code>java.awt.Color</code> object. ! * Default title font color is black. * @param c The color to be used. */ *************** *** 266,270 **** /** ! * Sets the color of the default font used in the graph. * @param c The color to be used. */ --- 273,278 ---- /** ! * Sets the color of the default font used in the graph as a <code>java.awt.Color</code> object. ! * Default font color is black. * @param c The color to be used. */ *************** *** 275,279 **** /** ! * Sets the font to be used for the graph title. * @param f The Font to be used. */ --- 283,288 ---- /** ! * Sets the font to be used for the graph title as a <code>java.awt.Font</code> object. ! * Default title font is "Lucida Sans Typewriter", with BOLD attributes and a size of 12 points. * @param f The Font to be used. */ *************** *** 284,288 **** /** ! * Sets the default font to be used in the graph. * @param f The Font to be used. */ --- 293,298 ---- /** ! * Sets the default font to be used in the graph as a <code>java.awt.Font</code> object. ! * Default font is "Lucida Sans Typewriter", with PLAIN attributes and a size of 10 points. * @param f The Font to be used. */ *************** *** 293,297 **** /** ! * Determines the color of the major grid. * @param c Color to use. */ --- 303,308 ---- /** ! * Sets the color of the chart's major grid. ! * Grid labels have the same color as the default font. * @param c Color to use. */ *************** *** 302,306 **** /** ! * Determines the color of the minor grid. * @param c Color to use. */ --- 313,317 ---- /** ! * Determines the color of chart's the minor grid. * @param c Color to use. */ *************** *** 320,324 **** /** ! * Determines the color of X axis. * @param c Color to use. */ --- 331,335 ---- /** ! * Determines the color of chart X axis. * @param c Color to use. */ *************** *** 329,333 **** /** ! * Determines the color of the small axis arrow on the X axis. * @param c Color to use. */ --- 340,344 ---- /** ! * Determines the color of the small axis arrow on the chart X axis. * @param c Color to use. */ *************** *** 365,369 **** /** ! * Determines if the major grid width labels for the Y axis needs to be drawn. * @param visible True if major grid needs to be drawn, false if not. */ --- 376,380 ---- /** ! * Determines if the major grid with labels for the Y axis needs to be drawn. * @param visible True if major grid needs to be drawn, false if not. */ *************** *** 375,379 **** /** * Determines if the X axis grid should be drawn. - * This will not change the left padding of the drawing area. * @param visible True if grid needs to be drawn, false if not. */ --- 386,389 ---- *************** *** 385,389 **** /** * Determines if the Y axis grid should be drawn. - * This will not change the bottom padding of the drawing area. * @param visible True if grid needs to be drawn, false if not. */ --- 395,398 ---- *************** *** 392,411 **** this.gridY = visible; } - - /** - * Determines if the grid should have rigid upper and lower limits. - * If so the upper and lower limit will not autoscale depending on the - * graph values. Default uses grid autoscaling. - * @param rigid True if the grid should have rigid limits. - */ - public void setRigidGrid( boolean rigid ) - { - this.rigidGrid = rigid; - } /** ! * Determine if the graph grid is in front of the graphs itself, or behind it. ! * Default is in front of the graph itself. ! * @param frontGrid True if the grid is in front of the graphs. */ public void setFrontGrid( boolean frontGrid ) --- 401,409 ---- this.gridY = visible; } /** ! * Determine if the graph grid is in front of the chart itself, or behind it. ! * Default is in front of the chart. ! * @param frontGrid True if the grid is in front of the chart. */ public void setFrontGrid( boolean frontGrid ) *************** *** 416,419 **** --- 414,419 ---- /** * Determine if the legend should be visible or not, default: visible. + * Invisible legend area means no comments will be plotted, and the graph will be smaller + * in height. * @param showLegend True if the legend is visible. */ *************** *** 423,426 **** --- 423,433 ---- } + /** + * Determine if the default JRobin signature should be visible, default: yes. + * The signature text is "www.jrobin.org" and the signature is centered at the bottom of the graph. + * Unless you have a good reason not to draw the signature, please be so kind as to leave the + * signature visible. Disabling the signature can give a minor performance boost. + * @param showSignature True if the signature is visible. + */ public void setShowSignature( boolean showSignature ) { *************** *** 439,443 **** /** ! * Set the number of pixels on the left of the canvas area ( value marker space ). * @param lp Number of pixels used, defaults to 50. */ --- 446,450 ---- /** ! * Set the number of pixels on the left of the chart area ( value marker space ). * @param lp Number of pixels used, defaults to 50. */ *************** *** 446,449 **** --- 453,578 ---- this.chart_lpadding = lp; } + + /** + * Sets a background image to use for the graph. + * The image can be any of the supported imageio formats, + * default <i>.gif, .jpg or .png</i>. + * + * Please note: if the provided file does not exit at graph creation time, the + * corresponding graph will be created without the background image, and without + * any exception being thrown. + * + * @param fileName Filename of the image to use + */ + public void setBackground( String fileName ) + { + File bgFile = new File( fileName ); + if ( bgFile.exists() ) + this.background = bgFile; + } + + /** + * Sets a overlay image to use for the graph. + * The image can be any of the supported imageio formats, + * default <i>.gif, .jpg or .png</i>. All pixels with the color white + * RGB (255, 255, 255) will be treated as transparent. + * + * Please note: if the provided file does not exit at graph creation time, the + * corresponding graph will be created without the overlay image, and without + * any exception being thrown. + * + * @param fileName Filename of the image to use + */ + public void setOverlay( String fileName ) + { + File ovFile = new File( fileName ); + if ( ovFile.exists() ) + this.overlay = ovFile; + } + + /** + * Sets the base for value scaling. + * If you are graphing memory this should be set to 1024 so that one Kb is 1024 bytes. + * As a default the base value is set to 1000, under the assumption you will be measuring + * network traffic, in wich case 1 kb/s equals 1000 b/s. + * @param base Value to set as base for scaling. + */ + public void setBaseValue( double base ) + { + this.baseValue = base; + } + + /** + * This sets the 10** exponent scaling of the Y-axis values. + * Normally values will be scaled to the appropriate units (k, M, etc.). + * However you may wish to display units always in k (Kilo, 10e3) even if the data is in the + * M (Mega, 10e6) range for instance. Value should be an integer which is a multiple of 3 + * between -18 and 18 inclusive. It is the exponent on the units you which to use. + * For example, use 3 to display the y-axis values in k (Kilo, 10e3, thousands), + * use -6 to display the y-axis values in u (Micro, 10e-6, millionths). Use a value of 0 to + * prevent any scaling of the y-axis values. + * @param e Exponent value to use + */ + public void setUnitsExponent( int e ) + { + this.scaleIndex = (6 - e / 3); // Index in the scale table + } + + /** + * Sets value range that will be presented in the graph. If not set, graph limits will be autoscaled. + * @param lower Lower limit. + * @param upper Upper limit. + * @param rigid Rigid grid, won't autoscale limits. + */ + + public void setGridRange(double lower, double upper, boolean rigid) + { + gridRange = new GridRange( lower, upper, rigid ); + } + + /** + * This sets the grid and labels on the Y axis. + * Minor grid lines appear at <code>gridStep</code>, major grid lines accompanied by a label + * will appear every <code>labelStep</code> value. + * @param gridStep Value step on which a minor grid line will appear. + * @param labelStep Value step on which a major grid line with value label will appear. + */ + public void setValueAxis( double gridStep, double labelStep ) + { + this.valueGridStep = gridStep; + this.valueLabelStep = labelStep; + } + + /** + * This sets the grid and labels on the X axis. + * There are both minor and major grid lines, the major lines are accompanied by a time label. + * + * To define a grid line you must define a specific time unit, and a number of time steps. + * A grid line will appear everey steps*unit. Possible units are defined in the + * {@link jrobin.graph.TimeAxisUnit TimeAxisUnit} class, and are <i>SECOND, MINUTE, HOUR, DAY, + * WEEK, MONTH</i> and <i>YEAR</i>. + * + * @param minGridTimeUnit Time unit for the minor grid lines. + * @param minGridUnitSteps Time unit steps for the minor grid lines. + * @param majGridTimeUnit Time unit for the major grid lines. + * @param majGridUnitSteps Time unit steps for the major grid lines. + * @param dateFormat Format string of the time labels, according to <code>java.text.SimpleDateFormat</code> specifications. + * @param centeredLabels True if the time label should be centered in the area between two major grid lines. + */ + public void setTimeAxis( int minGridTimeUnit, + int minGridUnitSteps, + int majGridTimeUnit, + int majGridUnitSteps, + String dateFormat, + boolean centeredLabels ) + { + this.tAxis = new TimeAxisUnit( minGridTimeUnit, + minGridUnitSteps, + majGridTimeUnit, + majGridUnitSteps, + new SimpleDateFormat( dateFormat ) + ); + this.tAxisCentered = centeredLabels; + } /** *************** *** 460,464 **** * @param file Path to RRD file. * @param dsName Data source name defined in the RRD file. ! * @param consolFun Consolidation function that will be used to extract data from the RRD * file ("AVERAGE", "MIN", "MAX" or "LAST"). */ --- 589,593 ---- * @param file Path to RRD file. * @param dsName Data source name defined in the RRD file. ! * @param consolFunc Consolidation function that will be used to extract data from the RRD * file ("AVERAGE", "MIN", "MAX" or "LAST"). */ *************** *** 492,496 **** * * <p>For more details on RPN see RRDTool's ! * <a href="../../../man/rrdgraph.html" target="man">rrdgraph man page</a>.</p> * @param name Graph source name. * @param rpn RPN expression containig comma delmited simple and complex graph --- 621,625 ---- * * <p>For more details on RPN see RRDTool's ! * <a href="http://people.ee.ethz.ch/~oetiker/webtools/rrdtool/manual/rrdgraph.html" target="man">rrdgraph man page</a>.</p> * @param name Graph source name. * @param rpn RPN expression containig comma delmited simple and complex graph *************** *** 505,511 **** * Adds line plot to the graph definition, using the specified color and legend. This method * takes exactly the same parameters as RRDTool's LINE1 directive (line width ! * is set to 1). There is only ! * one limitation: so far, legends in JRobin graphs are always centered (don't ! * try to specify alignment in the legend string). * * @param sourceName Graph source name. --- 634,638 ---- * Adds line plot to the graph definition, using the specified color and legend. This method * takes exactly the same parameters as RRDTool's LINE1 directive (line width ! * is set to 1). * * @param sourceName Graph source name. *************** *** 675,795 **** } ! /** ! * Sets a background image to use for the graph. ! * The image can be any of the supported imageio formats, ! * default <i>.gif, .jpg or .png</i>. ! * @param fileName Filename of the image to use ! */ ! public void setBackground( String fileName ) ! { ! File bgFile = new File( fileName ); ! if ( bgFile.exists() ) ! this.background = bgFile; } ! /** ! * Sets a overlay image to use for the graph. ! * The image can be any of the supported imageio formats, ! * default <i>.gif, .jpg or .png</i>. All pixels with the color white ! * RGB (255, 255, 255) will be treated as transparent. ! * @param fileName Filename of the image to use ! */ ! public void setOverlay( String fileName ) ! { ! File ovFile = new File( fileName ); ! if ( ovFile.exists() ) ! this.overlay = ovFile; } ! /** ! * ! * @param base ! */ ! public void setBaseValue( double base ) { ! this.baseValue = base; } ! /** ! * ! * @param e ! */ ! public void setUnitsExponent( int e ) { ! this.scaleIndex = (6 - e / 3); // Index in the scale table } ! /** ! * Sets value range that will be presented in the graph. If not set, graph will be ! * autoscaled. ! * @param lower Lower limit. ! * @param upper Upper limit. ! * @param rigid Rigid grid, won't autoscale limits. ! */ ! public void setGridRange(double lower, double upper, boolean rigid) ! { ! gridRange = new GridRange( lower, upper, rigid ); } ! /** ! * Should write explanation of custom grid specs here ! * @param gridStep ! * @param labelStep ! */ ! public void setValueAxis( double gridStep, double labelStep ) ! { ! this.valueGridStep = gridStep; ! this.valueLabelStep = labelStep; } ! /** ! * Should write explanation of custom grid specs here. ! * @param minGridTime ! * @param minGridUnits ! * @param majGridTime ! * @param majGridUnits ! * @param df ! * @param centered ! */ ! public void setTimeAxis( int minGridTime, ! int minGridUnits, ! int majGridTime, ! int majGridUnits, ! String df, ! boolean centered ) ! { ! this.tAxis = new TimeAxisUnit( minGridTime, ! minGridUnits, ! majGridTime, ! majGridUnits, ! new SimpleDateFormat( df ) ! ); ! this.tAxisCentered = centered; } ! /** ! * Sets vertical space between value ticks. If not specified, JRobin will try to guess it. ! * @param valueStep Value step between value ticks. ! */ ! public void setValueStep(double valueStep) { ! this.valueStep = valueStep; } ! ! // ================================================================ ! // -- Protected (package) methods ! // ================================================================ ! PlotDef[] getPlotDefs() { return (PlotDef[]) plotDefs.toArray( new PlotDef[] {} ); } ! Comment[] getComments() { return (Comment[]) comments.toArray( new Comment[] {} ); } ! int getCommentLineCount() { return ( comments.size() > 0 ? commentLines + commentLineShift : 0 ); } // ================================================================ --- 802,977 ---- } ! ! // ================================================================ ! // -- Protected (package) methods ! // ================================================================ ! protected long getStartTime() { ! return startTime; ! } ! ! protected long getEndTime() { ! return endTime; ! } ! ! protected Title getTitle() { ! return title; ! } ! ! protected String getVerticalLabel() { ! return valueAxisLabel; ! } ! ! protected Color getBackColor() { ! return backColor; ! } ! ! protected Color getCanvasColor() { ! return canvasColor; ! } ! ! protected Color getImageBorderColor() { ! return borderColor; ! } ! ! protected BasicStroke getImageBorderStroke() { ! return borderStroke; ! } ! ! protected Color getTitleFontColor() { ! return titleFontColor; } ! protected Color getDefaultFontColor() { ! return normalFontColor; } ! protected Font getTitleFont() { ! return titleFont; ! } ! ! protected Font getDefaultFont() { ! return normalFont; ! } ! ! protected Color getMajorGridColor() { ! return majorGridColor; ! } ! ! protected Color getMinorGridColor() { ! return minorGridColor; ! } ! ! protected Color getFrameColor() { ! return frameColor; ! } ! ! protected Color getAxisColor() { ! return axisColor; } ! protected Color getArrowColor() { ! return arrowColor; } ! protected boolean showMinorGridX() { ! return minorGridX; ! } ! ! protected boolean showMinorGridY() { ! return minorGridY; ! } ! ! protected boolean showMajorGridX() { ! return majorGridX; ! } ! ! protected boolean showMajorGridY() { ! return majorGridY; ! } ! protected boolean showGridX() { ! return gridX; } ! protected boolean showGridY() { ! return gridY; } ! protected boolean drawFrontGrid() { ! return frontGrid; } ! protected boolean showLegend() { ! return showLegend; } ! ! protected boolean showSignature() { ! return drawSignature; ! } ! ! protected boolean useAntiAliasing() { ! return antiAliasing; ! } ! ! protected int getChartLeftPadding() { ! return chart_lpadding; ! } ! ! protected File getBackground() { ! return background; ! } ! ! protected File getOverlay() { ! return overlay; ! } ! ! protected double getBaseValue() { ! return baseValue; ! } ! ! protected int getScaleIndex() { ! return scaleIndex; ! } ! ! protected GridRange getGridRange() { ! return gridRange; ! } ! ! //protected getValueAxis() ! ! //protected getTimeAxis() ! ! ! ! protected PlotDef[] getPlotDefs() { return (PlotDef[]) plotDefs.toArray( new PlotDef[] {} ); } ! protected Comment[] getComments() { return (Comment[]) comments.toArray( new Comment[] {} ); } ! protected int getCommentLineCount() { return ( comments.size() > 0 ? commentLines + commentLineShift : 0 ); } + + protected int getNumDefs() + { + return numDefs; + } + + protected Cdef[] getCdefs() + { + return (Cdef[]) cdefList.toArray( new Cdef[] {} ); + } + + protected HashMap getFetchSources() + { + return fetchSources; + } + // ================================================================ Index: RrdGraph.java =================================================================== RCS file: /cvsroot/jrobin/src/jrobin/graph2/RrdGraph.java,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** RrdGraph.java 21 Oct 2003 19:41:58 -0000 1.1 --- RrdGraph.java 23 Oct 2003 23:16:35 -0000 1.2 *************** *** 296,300 **** } } ! catch (RrdException e) { e.printStackTrace(); } --- 296,300 ---- } } ! catch (Exception e) { // Temporary e.printStackTrace(); } |
From: <cob...@us...> - 2003-10-24 05:07:15
|
Update of /cvsroot/jrobin/src/jrobin/core In directory sc8-pr-cvs1:/tmp/cvs-serv5766/src/jrobin/core Modified Files: FetchData.java Util.java Log Message: New graph lib Switched to new FetchData method Index: FetchData.java =================================================================== RCS file: /cvsroot/jrobin/src/jrobin/core/FetchData.java,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** FetchData.java 22 Oct 2003 13:47:09 -0000 1.3 --- FetchData.java 23 Oct 2003 23:16:36 -0000 1.4 *************** *** 127,130 **** --- 127,140 ---- /** + * Returns all archived values for all datasources. + * Returned values correspond to timestamps + * returned with {@link #getTimestamps() getTimestamps()} method. + * @return Two-dimensional aray of all datasource values. + */ + public double[][] getValues() { + return values; + } + + /** * Returns all archived values for a single datasource. * Returned values correspond to timestamps *************** *** 185,188 **** --- 195,212 ---- public String[] getDsNames() { return dsNames; + } + + /** + * Retrieve the table index number of a datasource by name. Names are case sensitive. + * @param dsName Name of the datasource for which to find the index. + * @return Index number of the datasources in the value table. + */ + public int getDsIndex( String dsName ) { + // Let's assume the table of dsNames is always small, so it is not necessary to use a hashmap for lookups + for (int i = 0; i < dsNames.length; i++) + if ( dsNames[i].equals(dsName) ) + return i; + + return -1; // Datasource not found ! } Index: Util.java =================================================================== RCS file: /cvsroot/jrobin/src/jrobin/core/Util.java,v retrieving revision 1.7 retrieving revision 1.8 diff -C2 -d -r1.7 -r1.8 *** Util.java 21 Oct 2003 19:42:00 -0000 1.7 --- Util.java 23 Oct 2003 23:16:36 -0000 1.8 *************** *** 183,189 **** { s2 = System.currentTimeMillis(); ! if ( str >= 0 ) timeList.addLast( str + "_" + (s2 - s1)); //System.err.println( "[" + str + "] --- " + (s2 - s1) + " ms"); s1 = s2; } --- 183,190 ---- { s2 = System.currentTimeMillis(); ! if ( str >= 0 ) { timeList.addLast( str + "_" + (s2 - s1)); //System.err.println( "[" + str + "] --- " + (s2 - s1) + " ms"); + } s1 = s2; } |
Update of /cvsroot/jrobin/src/jrobin/core In directory sc8-pr-cvs1:/tmp/cvs-serv8060/jrobin/core Modified Files: FetchRequest.java RpnCalculator.java RrdDb.java RrdFile.java Sample.java Added Files: RrdDbPool.java Log Message: RrdDbPool class added --- NEW FILE: RrdDbPool.java --- /* ============================================================ * JRobin : Pure java implementation of RRDTool's functionality * ============================================================ * * Project Info: http://www.sourceforge.net/projects/jrobin * Project Lead: Sasa Markovic (sa...@eu...); * * (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 jrobin.core; import java.io.File; import java.io.IOException; import java.util.*; /** * Class to represent the pool of open RRD files. * * To open already existing RRD file with JRobin, you have to create a * {@link jrobin.core.RrdDb RrdDb} object by specifying RRD file path * as constructor argument. This operation can be time consuming * especially with large RRD files with many datasources and * several long archives.<p> * * In a multithreaded environment you might probably need a reference to the * same RRD file from two different threads (RRD file updates are performed in * one thread but data fetching and graphing is performed in another one). To make * the RrdDb construction process more efficient it might be convenient to open all * RRD files in a centralized place. That's the purpose of RrdDbPool class.<p> * * How does it work? The typical usage scenario goes like this:<p> * * <pre> * // obtain instance to RrdDbPool object * RrdDbPool pool = RrdDbPool.getInstance(); * * // request a reference to RrdDb object * String path = "some_relative_or_absolute_path_to_any_RRD_file"; * RrdDb rrdDb = RrdDbPool.requestRrdDb(path); * * // reference obtained, do whatever you want with it... * ... * ... * * // once you don't need the reference, release it. * // DO NOT CALL rrdDb.close() - files no longer in use are eventually closed by the pool * pool.release(rrdDb); *</pre> * * It's that simple. When the reference is requested for * the first time, RrdDbPool will open the RRD file * for you and make some internal note that the RRD file is used only once. When the reference * to the same file (same RRD file path) is requested for the second time, the same RrdDb * reference will be returned, and its usage count will be increased by one. When the * reference is released its usage count will be decremented by one.<p> * * When the reference count drops to zero, RrdDbPool will not close the underlying * RRD file immediatelly. Instead of it, it will be marked as 'eligible for closing'. * If someone request the same RRD file again (before it gets closed), the same * reference will be returned again.<p> * * RrdDbPool has a 'garbage collector' which gets activated only when the number of open * RRD files is to big (> 50). Only RRD files with a reference count equal to zero * will be eligible for closing. Unreleased RrdDb references will be never invalidated. * RrdDbPool object keeps track of the time when each RRD file * becomes eligible for closing so that the oldest RRD file gets closed first.<p> * * Never use close() method on the reference returned from the pool. When the reference * is no longer needed, return it to the pool with a {@link #release(RrdDb) release()} * method.<p> * * However, you are not forced to use RrdDbPool methods to obtain RrdDb references * to RRD files, 'ordinary' RrdDb constructors are still available. But RrdDbPool class * offers serious performance improvement especially in complex applications with many * threads and many simultaneously open RRD files.<p> * * The pool is thread-safe. * */ public class RrdDbPool { private static RrdDbPool ourInstance; private static final boolean DEBUG = false; /** * Constant to represent the maximum number of internally open RRD files * which still does not force garbage collector to run. */ public static final int OPEN_FILES_DESIRED = 50; private HashMap rrdMap = new HashMap(); /** * Returns an instance to RrdDbPool object. Only one such object may exist in each JVM. * @return Instance to RrdDbPool object. */ public synchronized static RrdDbPool getInstance() { if (ourInstance == null) { ourInstance = new RrdDbPool(); } return ourInstance; } private RrdDbPool() { } /** * Returns a reference to an existing RRD file with the specified path. * If the file is already open in the pool, existing reference to it will be returned. * Otherwise, the file is open and a newly created reference to it is returned. * * @param path Relative or absolute path to a RRD file. * @return Reference to a RrdDb object (RRD file). * @throws IOException Thrown in case of I/O error. * @throws RrdException Thrown in case of JRobin specific error. */ public synchronized RrdDb requestRrdDb(String path) throws IOException, RrdException { String keypath = getCanonicalPath(path); if(rrdMap.containsKey(keypath)) { // already open RrdEntry rrdEntry = (RrdEntry) rrdMap.get(keypath); rrdEntry.reportUsage(); debug("EXISTING: " + rrdEntry.dump()); return rrdEntry.getRrdDb(); } else { // not found, open it RrdDb rrdDb = new RrdDb(path); put(keypath, rrdDb); return rrdDb; } } /** * Returns a reference to a new RRD file. The new file will have the specified * relative or absolute path, and its contents will be provided from the specified * XML file (RRDTool comaptible). * @param path Relative or absolute path to a new RRD file. * @param xmlPath Relative or absolute path to an existing XML dump file (RRDTool comaptible) * @return Reference to a RrdDb object (RRD file). * @throws IOException Thrown in case of I/O error. * @throws RrdException Thrown in case of JRobin specific error. */ public synchronized RrdDb requestRrdDb(String path, String xmlPath) throws IOException, RrdException { String keypath = getCanonicalPath(path); validateInactive(keypath); RrdDb rrdDb = new RrdDb(path, xmlPath); put(keypath, rrdDb); return rrdDb; } /** * Returns a reference to a new RRD file. The new file will be created based on the * definition contained in a RrdDef object. * @param rrdDef RRD definition object * @return Reference to a RrdDb object (RRD file). * @throws IOException Thrown in case of I/O error. * @throws RrdException Thrown in case of JRobin specific error. */ public synchronized RrdDb requestRrdDb(RrdDef rrdDef) throws IOException, RrdException { String path = rrdDef.getPath(); String keypath = getCanonicalPath(path); validateInactive(keypath); RrdDb rrdDb = new RrdDb(rrdDef); put(keypath, rrdDb); return rrdDb; } private void put(String keypath, RrdDb rrdDb) throws IOException { RrdEntry newEntry = new RrdEntry(rrdDb); debug("NEW: " + newEntry.dump()); rrdMap.put(keypath, newEntry); gc(); } private void validateInactive(String keypath) throws RrdException, IOException { if(rrdMap.containsKey(keypath)) { // already open, check if active (not released) RrdEntry rrdEntry = (RrdEntry) rrdMap.get(keypath); if(!rrdEntry.isReleased()) { // not released, not allowed here throw new RrdException("VALIDATOR: Cannot create new RrdDb file. " + "File " + keypath + " already active in pool"); } else { // open but released... safe to close it debug("WILL BE RECREATED: " + rrdEntry.dump()); rrdEntry.close(); rrdMap.values().remove(rrdEntry); } } } /** * Method used to report that the reference to a RRD file is no longer needed. File that * is no longer needed (all references to it are released) is marked 'eligible for * closing'. It will be eventually closed by the pool when the number of open RRD files * becomes too big. Most recently released files will be closed last. * @param rrdDb Reference to RRD file that is no longer needed. * @throws IOException Thrown in case of I/O error. * @throws RrdException Thrown in case of JRobin specific error. */ public synchronized void release(RrdDb rrdDb) throws IOException, RrdException { RrdFile rrdFile = rrdDb.getRrdFile(); if(rrdFile == null) { throw new RrdException("Cannot release: already closed"); } String path = rrdFile.getFilePath(); String keypath = getCanonicalPath(path); if(rrdMap.containsKey(keypath)) { RrdEntry rrdEntry = (RrdEntry) rrdMap.get(keypath); rrdEntry.release(); debug("RELEASED: " + rrdEntry.dump()); } else { throw new RrdException("RrdDb with path " + keypath + " not in pool"); } gc(); } private void gc() throws IOException { int mapSize = rrdMap.size(); if(mapSize <= OPEN_FILES_DESIRED) { // nothing to do debug("GC: no need to run"); return; } // prepare collection of released entries debug("GC: finding the oldest released entry"); Iterator valueIterator = rrdMap.values().iterator(); LinkedList releasedEntries = new LinkedList(); while(valueIterator.hasNext()) { RrdEntry rrdEntry = (RrdEntry) valueIterator.next(); if(rrdEntry.isReleased()) { releasedEntries.add(rrdEntry); } } if(releasedEntries.size() == 0) { debug("GC: no released entries found, nothing to do"); return; } debug("GC: found " + releasedEntries.size() + " released entries"); Comparator releaseDateComparator = new Comparator() { public int compare(Object o1, Object o2) { RrdEntry r1 = (RrdEntry) o1, r2 = (RrdEntry) o2; long diff = r1.getReleaseDate().getTime() - r2.getReleaseDate().getTime(); return diff < 0? -1: (diff == 0? 0: +1); } }; RrdEntry oldestEntry = (RrdEntry) Collections.min(releasedEntries, releaseDateComparator); debug("GC: oldest released entry found: " + oldestEntry.dump()); oldestEntry.close(); rrdMap.values().remove(oldestEntry); debug("GC: oldest entry closed and removed. "); debug("GC: number of entries reduced from " + mapSize + " to " + rrdMap.size()); } protected void finalize() throws IOException { reset(); } /** * Clears the internal state of the pool entirely. All open RRD files are closed. * Use with extreme caution. * @throws IOException Thrown in case of I/O related error. */ public synchronized void reset() throws IOException { Iterator it = rrdMap.values().iterator(); while(it.hasNext()) { RrdEntry rrdEntry = (RrdEntry) it.next(); rrdEntry.close(); } rrdMap.clear(); debug("Nothing left in the pool"); } static String getCanonicalPath(String path) throws IOException { return new File(path).getCanonicalPath(); } static void debug(String msg) { if(DEBUG) { System.out.println("POOL: " + msg); } } /** * Returns the internal state of the pool. Useful for debugging purposes. * @return Internal pool state (list of open RRD files, with the number of usages for * each one). * @throws IOException Thrown in case of I/O error. */ public synchronized String dump() throws IOException { StringBuffer buff = new StringBuffer(); Iterator it = rrdMap.values().iterator(); while(it.hasNext()) { RrdEntry rrdEntry = (RrdEntry) it.next(); buff.append(rrdEntry.dump()); buff.append("\n"); } return buff.toString(); } private class RrdEntry { private RrdDb rrdDb; private Date releaseDate; private int usageCount; public RrdEntry(RrdDb rrdDb) { this.rrdDb = rrdDb; reportUsage(); } RrdDb getRrdDb() { return rrdDb; } void reportUsage() { releaseDate = null; usageCount++; } void release() { if(usageCount > 0) { usageCount--; if(usageCount == 0) { releaseDate = new Date(); } } } boolean isReleased() { return usageCount == 0; } int getUsageCount() { return usageCount; } Date getReleaseDate() { return releaseDate; } void close() throws IOException { rrdDb.close(); } String dump() throws IOException { String keypath = getCanonicalPath(rrdDb.getRrdFile().getFilePath()); return keypath + " [" + usageCount + "]"; } } } Index: FetchRequest.java =================================================================== RCS file: /cvsroot/jrobin/src/jrobin/core/FetchRequest.java,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** FetchRequest.java 22 Oct 2003 08:55:10 -0000 1.3 --- FetchRequest.java 23 Oct 2003 14:55:34 -0000 1.4 *************** *** 165,169 **** */ public FetchPoint[] fetch() throws RrdException, IOException { ! return parentDb.fetch(this); } --- 165,171 ---- */ public FetchPoint[] fetch() throws RrdException, IOException { ! synchronized(parentDb) { ! return parentDb.fetch(this); ! } } *************** *** 177,181 **** */ public FetchData fetchData() throws RrdException, IOException { ! return parentDb.fetchData(this); } --- 179,185 ---- */ public FetchData fetchData() throws RrdException, IOException { ! synchronized(parentDb) { ! return parentDb.fetchData(this); ! } } Index: RpnCalculator.java =================================================================== RCS file: /cvsroot/jrobin/src/jrobin/core/RpnCalculator.java,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** RpnCalculator.java 22 Oct 2003 13:47:10 -0000 1.1 --- RpnCalculator.java 23 Oct 2003 14:55:34 -0000 1.2 *************** *** 1,2 **** --- 1,23 ---- + /* ============================================================ + * JRobin : Pure java implementation of RRDTool's functionality + * ============================================================ + * + * Project Info: http://www.sourceforge.net/projects/jrobin + * Project Lead: Sasa Markovic (sa...@eu...); + * + * (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 jrobin.core; Index: RrdDb.java =================================================================== RCS file: /cvsroot/jrobin/src/jrobin/core/RrdDb.java,v retrieving revision 1.11 retrieving revision 1.12 diff -C2 -d -r1.11 -r1.12 *** RrdDb.java 22 Oct 2003 13:47:09 -0000 1.11 --- RrdDb.java 23 Oct 2003 14:55:34 -0000 1.12 *************** *** 361,365 **** } ! synchronized void store(Sample sample) throws IOException, RrdException { long newTime = sample.getTime(); long lastTime = header.getLastUpdateTime(); --- 361,365 ---- } ! void store(Sample sample) throws IOException, RrdException { long newTime = sample.getTime(); long lastTime = header.getLastUpdateTime(); *************** *** 377,381 **** } ! synchronized FetchPoint[] fetch(FetchRequest request) throws IOException, RrdException { Archive archive = findMatchingArchive(request); FetchPoint[] points = archive.fetch(request); --- 377,381 ---- } ! FetchPoint[] fetch(FetchRequest request) throws IOException, RrdException { Archive archive = findMatchingArchive(request); FetchPoint[] points = archive.fetch(request); *************** *** 384,388 **** } ! synchronized FetchData fetchData(FetchRequest request) throws IOException, RrdException { Archive archive = findMatchingArchive(request); FetchData fetchData = archive.fetchData(request); --- 384,388 ---- } ! FetchData fetchData(FetchRequest request) throws IOException, RrdException { Archive archive = findMatchingArchive(request); FetchData fetchData = archive.fetchData(request); Index: RrdFile.java =================================================================== RCS file: /cvsroot/jrobin/src/jrobin/core/RrdFile.java,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** RrdFile.java 17 Sep 2003 11:50:16 -0000 1.2 --- RrdFile.java 23 Oct 2003 14:55:34 -0000 1.3 *************** *** 255,258 **** } } - - --- 255,256 ---- Index: Sample.java =================================================================== RCS file: /cvsroot/jrobin/src/jrobin/core/Sample.java,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** Sample.java 16 Oct 2003 09:26:30 -0000 1.3 --- Sample.java 23 Oct 2003 14:55:34 -0000 1.4 *************** *** 194,198 **** */ public void update() throws IOException, RrdException { ! parentDb.store(this); clearCurrentValues(); } --- 194,200 ---- */ public void update() throws IOException, RrdException { ! synchronized(parentDb) { ! parentDb.store(this); ! } clearCurrentValues(); } |
From: <cob...@us...> - 2003-10-22 22:08:05
|
Update of /cvsroot/jrobin/src/jrobin/graph2 In directory sc8-pr-cvs1:/tmp/cvs-serv999/src/jrobin/graph2 Modified Files: RpnCalculator.java Stack.java Grapher.java Area.java ChartGraphics.java RrdGraphDef.java PlotDef.java ValueFormatter.java Added Files: CustomLine.java CustomArea.java Log Message: New graph lib Add support for custom plotdefs Finalized some features --- NEW FILE: CustomLine.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 jrobin.graph2; import java.awt.Color; import java.awt.BasicStroke; import java.util.HashMap; import jrobin.core.RrdException; /** * <p>description</p> * * @author Arne Vandamme (arn...@jr...) */ class CustomLine extends PlotDef { private long xVal1; private long xVal2; private double yVal1; private double yVal2; private double dc; CustomLine( long startTime, double startValue, long endTime, double endValue, Color color ) { this.color = color; if ( color == null ) visible = false; this.xVal1 = startTime; this.xVal2 = endTime; this.yVal1 = startValue; this.yVal2 = endValue; try { long xc = xVal2 - xVal1; if ( xc != 0 ) this.dc = ( yVal2 - yVal1 ) / xc; else this.dc = 0; } catch (Exception e) { this.dc = 0; } } CustomLine( long startTime, double startValue, long endTime, double endValue, Color color, int lineWidth ) { this( startTime, startValue, endTime, endValue, color ); this.lineWidth = lineWidth; } void draw( ChartGraphics g, int[] xValues, int[] stackValues, int lastPlotType ) throws RrdException { g.setColor( color ); g.setStroke( new BasicStroke(lineWidth) ); int ax, ay, nx, ny; // Get X positions if ( xVal1 == Long.MIN_VALUE ) ax = g.getMinX(); else if ( xVal1 == Long.MAX_VALUE ) ax = g.getMaxX(); else ax = g.getX( xVal1 ); if ( xVal2 == Long.MIN_VALUE ) nx = g.getMinX(); else if ( xVal2 == Long.MAX_VALUE ) nx = g.getMaxX(); else nx = g.getX( xVal2 ); // Get Y positions if ( yVal1 == Double.MIN_VALUE ) ay = g.getMinY(); else if ( yVal1 == Double.MAX_VALUE ) ay = g.getMaxY(); else ay = g.getY( yVal1 ); if ( yVal2 == Double.MIN_VALUE ) ny = g.getMinY(); else if ( yVal2 == Double.MAX_VALUE ) ny = g.getMaxY(); else ny = g.getY( yVal2 ); // Draw the line if ( visible ) g.drawLine( ax, ay, nx, ny ); // Set the stackvalues int rx = nx - ax; if ( rx != 0 ) { double rc = ((ny - ay) * 1.0d) / rx; for (int i = 0; i < xValues.length; i++) { if ( xValues[i] < ax || xValues[i] > nx ) stackValues[i] = 0; else if ( ay == ny ) stackValues[i] = ay; else stackValues[i] = new Double(rc * (xValues[i] - ax) + ay).intValue(); } } g.setStroke( new BasicStroke() ); } double getValue( int tblPos, long[] timestamps ) { long time = timestamps[tblPos]; // Out of range if ( time > xVal2 || time < xVal1 ) return Double.NaN; // Hrule if ( yVal1 == yVal2 ) return yVal1; // Vrule if ( yVal1 == Double.MIN_VALUE && yVal2 == Double.MAX_VALUE ) return Double.NaN; // No line, very rare, will usually be 'out of range' first if ( xVal1 == xVal2 ) return Double.NaN; // Custom line return ( dc * ( time - xVal1 ) + yVal1 ); } void setSource( Source[] sources, HashMap sourceIndex ) throws RrdException { // Stub } } --- NEW FILE: CustomArea.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 jrobin.graph2; import java.awt.Color; import java.util.HashMap; import jrobin.core.RrdException; /** * <p>description</p> * * @author Arne Vandamme (arn...@jr...) */ class CustomArea extends PlotDef { private long xVal1; private long xVal2; private double yVal1; private double yVal2; CustomArea( long startTime, double startValue, long endTime, double endValue, Color color ) { this.color = color; if ( color == null ) visible = false; this.xVal1 = startTime; this.xVal2 = endTime; this.yVal1 = startValue; this.yVal2 = endValue; } void draw( ChartGraphics g, int[] xValues, int[] stackValues, int lastPlotType ) throws RrdException { g.setColor( color ); int ax, ay, nx, ny; // Get X positions if ( xVal1 == Long.MIN_VALUE ) ax = g.getMinX(); else if ( xVal1 == Long.MAX_VALUE ) ax = g.getMaxX(); else ax = g.getX( xVal1 ); if ( xVal2 == Long.MIN_VALUE ) nx = g.getMinX(); else if ( xVal2 == Long.MAX_VALUE ) nx = g.getMaxX(); else nx = g.getX( xVal2 ); // Get Y positions if ( yVal1 == Double.MIN_VALUE ) ay = g.getMinY(); else if ( yVal1 == Double.MAX_VALUE ) ay = g.getMaxY(); else ay = g.getY( yVal1 ); if ( yVal2 == Double.MIN_VALUE ) ny = g.getMinY(); else if ( yVal2 == Double.MAX_VALUE ) ny = g.getMaxY(); else ny = g.getY( yVal2 ); // Draw the area if ( visible ) { if ( ny > ay ) g.fillRect( ax, ay, nx, ny ); else g.fillRect( ax, ny, nx, ay ); } // Set the stackvalues // Always use the y value of the second specified point to stack on if ( yVal2 != Double.MAX_VALUE ) for (int i = 0; i < stackValues.length; i++) if ( xValues[i] < ax || xValues[i] > nx ) stackValues[i] = 0; else stackValues[i] = ny; } double getValue( int tblPos, long[] timestamps ) { long time = timestamps[tblPos]; // Out of range if ( time > xVal2 || time < xVal1 ) return Double.NaN; if ( yVal2 == Double.MAX_VALUE ) return Double.NaN; return yVal2; } void setSource( Source[] sources, HashMap sourceIndex ) throws RrdException { // Stub } } Index: RpnCalculator.java =================================================================== RCS file: /cvsroot/jrobin/src/jrobin/graph2/RpnCalculator.java,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** RpnCalculator.java 21 Oct 2003 19:41:58 -0000 1.1 --- RpnCalculator.java 22 Oct 2003 21:06:53 -0000 1.2 *************** *** 309,314 **** throw new RrdException("POP failed, stack empty"); ! Double lastValue = (Double) stack.get(last); ! stack.remove(last); return lastValue.doubleValue(); --- 309,313 ---- throw new RrdException("POP failed, stack empty"); ! Double lastValue = (Double) stack.remove(last); return lastValue.doubleValue(); Index: Stack.java =================================================================== RCS file: /cvsroot/jrobin/src/jrobin/graph2/Stack.java,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** Stack.java 21 Oct 2003 19:41:58 -0000 1.1 --- Stack.java 22 Oct 2003 21:06:53 -0000 1.2 *************** *** 49,55 **** { if ( lastPlotType == PlotDef.PLOT_LINE ) ! stack = new PlotDef( source, color, true ); else if ( lastPlotType == PlotDef.PLOT_AREA ) ! stack = new Area( source, color, true ); stack.draw( g, xValues, stackValues, lastPlotType ); --- 49,55 ---- { if ( lastPlotType == PlotDef.PLOT_LINE ) ! stack = new PlotDef( source, color, true, visible ); else if ( lastPlotType == PlotDef.PLOT_AREA ) ! stack = new Area( source, color, true, visible ); stack.draw( g, xValues, stackValues, lastPlotType ); Index: Grapher.java =================================================================== RCS file: /cvsroot/jrobin/src/jrobin/graph2/Grapher.java,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** Grapher.java 21 Oct 2003 19:41:58 -0000 1.1 --- Grapher.java 22 Oct 2003 21:06:53 -0000 1.2 *************** *** 60,64 **** // Border space definitions private static final int UBORDER_SPACE = 10; ! private static final int BBORDER_SPACE = 10; private static final int LBORDER_SPACE = 10; private static final int RBORDER_SPACE = 10; --- 60,64 ---- // Border space definitions private static final int UBORDER_SPACE = 10; ! private static final int BBORDER_SPACE = 16; private static final int LBORDER_SPACE = 10; private static final int RBORDER_SPACE = 10; *************** *** 175,179 **** plotImageBackground( graphics ); ! plotChart( graphics ); --- 175,179 ---- plotImageBackground( graphics ); ! plotChart( graphics ); *************** *** 182,185 **** --- 182,188 ---- plotOverlay( graphics ); + + if ( graphDef.drawSignature ) + plotSignature( graphics ); } catch (IOException e) *************** *** 199,202 **** --- 202,215 ---- } + private void plotSignature( Graphics2D g ) + { + Font sigFont = new Font("Courier", Font.PLAIN, 10); + String sig = "www.jrobin.org"; + g.setColor( Color.GRAY ); + g.setFont( sigFont ); + + g.drawString( sig, imgWidth / 2 - (sig.length() * 5) / 2, imgHeight - 5 ); + } + private void plotOverlay( Graphics2D g ) { *************** *** 419,423 **** veList.clear(); // Clean up the fetched datasources ! // DEBUG - calculate checkpoint Util.time(1); --- 432,436 ---- veList.clear(); // Clean up the fetched datasources ! // DEBUG - calculate checkpoint Util.time(1); *************** *** 509,512 **** --- 522,528 ---- Source src = plotDefs[i].getSource(); + if ( src == null ) + continue; + double min = src.getAggregate( Source.AGG_MINIMUM ); double max = src.getAggregate( Source.AGG_MAXIMUM ); *************** *** 515,523 **** { if ( plotDefs[i - 1].plotType == PlotDef.PLOT_STACK ) { // Use this source plus stack of previous ones ! double[] curValues = plotDefs[i].source.values; ! for (int j = 0; j < curValues.length; j++) { ! val = tmpSeries[j] + curValues[j]; if ( val < lowerValue ) lowerValue = val; --- 531,539 ---- { if ( plotDefs[i - 1].plotType == PlotDef.PLOT_STACK ) { // Use this source plus stack of previous ones ! //double[] curValues = plotDefs[i].source.values; ! for (int j = 0; j < tmpSeries.length; j++) { ! val = tmpSeries[j] + plotDefs[i].getValue(j, timestamps); if ( val < lowerValue ) lowerValue = val; *************** *** 528,537 **** } else { // Use this source plus the previous one ! double[] prevValues = plotDefs[i - 1].source.values; ! double[] curValues = plotDefs[i].source.values; ! for (int j = 0; j < prevValues.length; j++) { ! val = prevValues[j] + curValues[j]; if ( val < lowerValue ) lowerValue = val; --- 544,553 ---- } else { // Use this source plus the previous one ! //double[] prevValues = plotDefs[i - 1].source.values; ! //double[] curValues = plotDefs[i].source.values; ! for (int j = 0; j < tmpSeries.length; j++) { ! val = plotDefs[i - 1].getValue(j, timestamps) + plotDefs[i].getValue(j, timestamps); if ( val < lowerValue ) lowerValue = val; *************** *** 592,631 **** lastPlotType = plotDefs[i].plotType; } - - /* - for (int i = 0; i < plotDefs.length; i++) - { - Source source = plotDefs[i].getSource(); - - g.setColor( plotDefs[i].getColor() ); - - switch ( plotDefs[i].getType() ) - { - case PlotDef.PLOT_LINE: - graphics.setStroke( new BasicStroke(plotDefs[i].getLineWidth()) ); - plotDefs[i].draw( g, xValues, parentSeries, false ); - //drawLine( g, parentSeries, source, false ); - - graphics.setStroke( new BasicStroke() ); - break; - case PlotDef.PLOT_AREA: - drawArea( g, parentSeries, source, false ); - lastPlotType = PlotDef.PLOT_AREA; - break; - case PlotDef.PLOT_STACK: - if ( lastPlotType == PlotDef.PLOT_AREA ) - drawArea( g, parentSeries, source, true ); - else - drawLine( g, parentSeries, source, true ); - break; - case PlotDef.PLOT_VRULE: - int pos = g.getX( ((VruleSource) source).getTime() ); - graphics.setStroke( new BasicStroke(plotDefs[i].getLineWidth()) ); - g.drawLine( pos, 0 - chartHeight, pos, 0 + chartHeight ); - graphics.setStroke( new BasicStroke() ); - break; - } - } - */ // Reset clipping area and origin --- 608,611 ---- *************** *** 793,798 **** return; ! // Position the cursor just below the chart area ! int posy = tfont_height + UBORDER_SPACE; //y_offset + chartHeight + CHART_UPADDING + CHART_BPADDING + nfont_height; int posx = LBORDER_SPACE; --- 773,778 ---- return; ! // Position the cursor just above the chart area ! int posy = tfont_height - 1 + UBORDER_SPACE; //y_offset + chartHeight + CHART_UPADDING + CHART_BPADDING + nfont_height; int posx = LBORDER_SPACE; *************** *** 895,900 **** } ! double fixedGridStep = Double.NaN;//= graphDef.getValueGridStep(); ! double fixedLabelStep = Double.NaN;//= graphDef.getValueLabelStep(); if ( !Double.isNaN(fixedGridStep) && !Double.isNaN(fixedLabelStep) ) --- 875,880 ---- } ! double fixedGridStep = graphDef.valueGridStep; ! double fixedLabelStep = graphDef.valueLabelStep; if ( !Double.isNaN(fixedGridStep) && !Double.isNaN(fixedLabelStep) ) *************** *** 915,919 **** if ( !lowerFromRange ) lowerValue = v.getNiceLower( lowerValue ); ! return v.getValueMarkers( lowerValue, upperValue, 1000d, graphDef.scaleIndex); //return v.getValueMarkers( lowerValue, upperValue, graphDef.getBaseValue(), graphDef.getScaleIndex() ); } --- 895,899 ---- if ( !lowerFromRange ) lowerValue = v.getNiceLower( lowerValue ); ! return v.getValueMarkers( lowerValue, upperValue, graphDef.baseValue, graphDef.scaleIndex); //return v.getValueMarkers( lowerValue, upperValue, graphDef.getBaseValue(), graphDef.getScaleIndex() ); } *************** *** 942,947 **** double days = (endTime - startTime) / 86400.0; ! //t = graphDef.getTimeAxis(); ! //vLabelCentered = graphDef.getTimeAxisCentered(); if ( t == null ) --- 922,927 ---- double days = (endTime - startTime) / 86400.0; ! t = graphDef.tAxis; ! vLabelCentered = graphDef.tAxisCentered; if ( t == null ) Index: Area.java =================================================================== RCS file: /cvsroot/jrobin/src/jrobin/graph2/Area.java,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** Area.java 21 Oct 2003 19:41:58 -0000 1.1 --- Area.java 22 Oct 2003 21:06:53 -0000 1.2 *************** *** 40,46 **** } ! Area( Source source, Color c, boolean stacked ) { ! super( source, c, stacked ); } --- 40,46 ---- } ! Area( Source source, Color c, boolean stacked, boolean visible ) { ! super( source, c, stacked, visible ); } *************** *** 64,79 **** } ! if (nx > ax + 1) // More than one pixel hop, draw intermediate pixels too { ! // For each pixel between nx and ax, calculate the y, plot the line ! int co = (ny - ay) / (nx - ax); ! int j = (ax > 0 ? ax : 1 ); // Skip 0 ! ! for (j = ax; j <= nx; j++) ! g.drawLine( j, py, j, ( co * (j - ax) + ay) ); } ! else if ( nx != 0 && py != Integer.MIN_VALUE && ny != Integer.MIN_VALUE ) ! g.drawLine( nx, py, nx, ny ); ! stackValues[i] = ny; ax = nx; --- 64,82 ---- } ! if ( visible ) { ! if (nx > ax + 1) // More than one pixel hop, draw intermediate pixels too ! { ! // For each pixel between nx and ax, calculate the y, plot the line ! int co = (ny - ay) / (nx - ax); ! int j = (ax > 0 ? ax : 1 ); // Skip 0 ! ! for (j = ax; j <= nx; j++) ! g.drawLine( j, py, j, ( co * (j - ax) + ay) ); ! } ! else if ( nx != 0 && py != Integer.MIN_VALUE && ny != Integer.MIN_VALUE ) ! g.drawLine( nx, py, nx, ny ); } ! stackValues[i] = ny; ax = nx; Index: ChartGraphics.java =================================================================== RCS file: /cvsroot/jrobin/src/jrobin/graph2/ChartGraphics.java,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** ChartGraphics.java 21 Oct 2003 19:41:58 -0000 1.1 --- ChartGraphics.java 22 Oct 2003 21:06:53 -0000 1.2 *************** *** 111,113 **** --- 111,133 ---- g.setStroke( s ); } + + int getMinX() + { + return 0; + } + + int getMaxX() + { + return 0 + width; + } + + int getMinY() + { + return 0; + } + + int getMaxY() + { + return 0 + height; + } } Index: RrdGraphDef.java =================================================================== RCS file: /cvsroot/jrobin/src/jrobin/graph2/RrdGraphDef.java,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** RrdGraphDef.java 21 Oct 2003 19:41:58 -0000 1.1 --- RrdGraphDef.java 22 Oct 2003 21:06:53 -0000 1.2 *************** *** 34,37 **** --- 34,38 ---- import java.util.HashMap; import java.util.GregorianCalendar; + import java.text.SimpleDateFormat; import jrobin.core.Util; *************** *** 77,80 **** --- 78,82 ---- boolean antiAliasing = true; // use anti-aliasing for the chart (default: yes) boolean showLegend = true; // show legend and comments (default: yes) + boolean drawSignature = true; // show JRobin url signature (default: yes) Color backColor = new Color( 245, 245, 245 ); // variation of light gray *************** *** 99,102 **** --- 101,110 ---- BasicStroke borderStroke = null; // defaults to standard beveled border + TimeAxisUnit tAxis = null; + boolean tAxisCentered = false; + double valueGridStep = Double.NaN; + double valueLabelStep = Double.NaN; + double valueStep = 0; + double baseValue = 1000; int scaleIndex = -1; // NO_SCALE *************** *** 106,109 **** --- 114,118 ---- int commentLines = 0; int commentLineShift = 0; + HashMap fetchSources = new HashMap(); Vector cdefList = new Vector(); *************** *** 414,417 **** --- 423,431 ---- } + public void setShowSignature( boolean showSignature ) + { + this.drawSignature = showSignature; + } + /** * Set the anti-aliasing option for the drawing area of the graph. *************** *** 523,526 **** --- 537,546 ---- } + public void line( GregorianCalendar t1, double v1, GregorianCalendar t2, double v2, Color color, String legend, int lineWidth ) throws RrdException + { + plotDefs.add( new CustomLine( t1.getTimeInMillis() / 1000, v1, t2.getTimeInMillis() / 1000, v2, color, lineWidth ) ); + addLegend( legend, color ); + } + /** * Adds area plot to the graph definition, *************** *** 541,544 **** --- 561,570 ---- } + public void area( GregorianCalendar t1, double v1, GregorianCalendar t2, double v2, Color color, String legend ) throws RrdException + { + plotDefs.add( new CustomArea( t1.getTimeInMillis() / 1000, v1, t2.getTimeInMillis() / 1000, v2, color ) ); + addLegend( legend, color ); + } + /** * Adds stacked plot to the graph definition, *************** *** 560,563 **** --- 586,639 ---- /** + * Adds horizontal rule to the graph definition. + * @param value Rule posiotion. + * @param color Rule color. + * @param legend Legend to be added to the graph. + * @throws RrdException Thrown in case of JRobin specific error. + */ + public void hrule(double value, Color color, String legend) throws RrdException { + plotDefs.add( new CustomLine( Long.MIN_VALUE, value, Long.MAX_VALUE, value, color ) ); + addLegend( legend, color ); + } + + /** + * Adds horizontal rule to the graph definition. + * @param value Rule posiotion. + * @param color Rule color. + * @param legend Legend to be added to the graph. + * @param lineWidth Width of the hrule line in pixels. + * @throws RrdException Thrown in case of JRobin specific error. + */ + public void hrule(double value, Color color, String legend, int lineWidth) throws RrdException { + plotDefs.add( new CustomLine( Long.MIN_VALUE, value, Long.MAX_VALUE, value, color, lineWidth ) ); + addLegend( legend, color ); + } + + /** + * Adds a vertical rule to the graph definition. + * @param timestamp Rule position (specific moment in time) + * @param color Rule color. + * @param legend Legend to be added to the graph. + */ + public void vrule( GregorianCalendar timestamp, Color color, String legend ) throws RrdException { + long timeSecs = timestamp.getTimeInMillis() / 1000; + plotDefs.add( new CustomLine( timeSecs, Double.MIN_VALUE, timeSecs, Double.MAX_VALUE, color ) ); + addLegend( legend, color ); + } + + /** + * Adds a vertical rule to the graph definition. + * @param timestamp Rule position (specific moment in time) + * @param color Rule color. + * @param legend Legend to be added to the graph. + * @param lineWidth Width of the vrule in pixels. + */ + public void vrule( GregorianCalendar timestamp, Color color, String legend, int lineWidth ) throws RrdException { + long timeSecs = timestamp.getTimeInMillis() / 1000; + plotDefs.add( new CustomLine( timeSecs, Double.MIN_VALUE, timeSecs, Double.MAX_VALUE, color, lineWidth ) ); + addLegend( legend, color ); + } + + /** * Adds comment to the graph definition. Comments will be left, center or right aligned * if the comment ends with <code>@l</code>, <code>@c</code> or <code>@r</code>, *************** *** 655,658 **** --- 731,778 ---- } + /** + * Should write explanation of custom grid specs here + * @param gridStep + * @param labelStep + */ + public void setValueAxis( double gridStep, double labelStep ) + { + this.valueGridStep = gridStep; + this.valueLabelStep = labelStep; + } + + /** + * Should write explanation of custom grid specs here. + * @param minGridTime + * @param minGridUnits + * @param majGridTime + * @param majGridUnits + * @param df + * @param centered + */ + public void setTimeAxis( int minGridTime, + int minGridUnits, + int majGridTime, + int majGridUnits, + String df, + boolean centered ) + { + this.tAxis = new TimeAxisUnit( minGridTime, + minGridUnits, + majGridTime, + majGridUnits, + new SimpleDateFormat( df ) + ); + this.tAxisCentered = centered; + } + + /** + * Sets vertical space between value ticks. If not specified, JRobin will try to guess it. + * @param valueStep Value step between value ticks. + */ + public void setValueStep(double valueStep) { + this.valueStep = valueStep; + } + // ================================================================ // -- Protected (package) methods *************** *** 671,677 **** { return ( comments.size() > 0 ? commentLines + commentLineShift : 0 ); - //return ( comments.size() > 0 ? (commentLines > 0 ? commentLines : 1) : 0 ); } private void addComment( Comment cmt ) { --- 791,799 ---- { return ( comments.size() > 0 ? commentLines + commentLineShift : 0 ); } + // ================================================================ + // -- Private methods + // ================================================================ private void addComment( Comment cmt ) { *************** *** 683,687 **** private void addLegend( String legend, Color color ) throws RrdException { ! if ( legend != null ) addComment( new Legend(legend, color) ); } --- 805,809 ---- private void addLegend( String legend, Color color ) throws RrdException { ! if ( legend != null && color != null ) addComment( new Legend(legend, color) ); } Index: PlotDef.java =================================================================== RCS file: /cvsroot/jrobin/src/jrobin/graph2/PlotDef.java,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** PlotDef.java 21 Oct 2003 19:41:58 -0000 1.1 --- PlotDef.java 22 Oct 2003 21:06:53 -0000 1.2 *************** *** 53,61 **** protected Color color = Color.BLACK; // Default color is black PlotDef( String sourceName, Color color ) { this.sourceName = sourceName; ! this.color = color; } --- 53,67 ---- protected Color color = Color.BLACK; // Default color is black + // Implicit + PlotDef() { + } PlotDef( String sourceName, Color color ) { this.sourceName = sourceName; ! this.color = color; ! // If no color is given, we should not plot this source ! if ( color == null ) ! visible = false; } *************** *** 66,74 **** } ! PlotDef( Source source, Color color, boolean stacked ) { this.source = source; this.color = color; this.stacked = stacked; } --- 72,81 ---- } ! PlotDef( Source source, Color color, boolean stacked, boolean visible ) { this.source = source; this.color = color; this.stacked = stacked; + this.visible = visible; } *************** *** 84,87 **** --- 91,95 ---- } + // Default draw is a standard line void draw( ChartGraphics g, int[] xValues, int[] stackValues, int lastPlotType ) throws RrdException { *************** *** 97,106 **** ny = g.getY( source.values[i] ); ! if ( stacked ) ny += stackValues[i]; ! if ( visible && nx != 0 && ay != Integer.MIN_VALUE && ny != Integer.MIN_VALUE ) g.drawLine( ax, ay, nx, ny ); ! stackValues[i] = ny; ax = nx; --- 105,114 ---- ny = g.getY( source.values[i] ); ! if ( stacked && ny != Integer.MIN_VALUE ) ny += stackValues[i]; ! if ( visible && ny != Double.NaN && nx != 0 && ay != Integer.MIN_VALUE && ny != Integer.MIN_VALUE ) g.drawLine( ax, ay, nx, ny ); ! stackValues[i] = ny; ax = nx; *************** *** 109,112 **** --- 117,125 ---- g.setStroke( new BasicStroke() ); + } + + double getValue( int tblPos, long[] timestamps ) + { + return source.values[tblPos]; } Index: ValueFormatter.java =================================================================== RCS file: /cvsroot/jrobin/src/jrobin/graph2/ValueFormatter.java,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** ValueFormatter.java 21 Oct 2003 19:41:58 -0000 1.1 --- ValueFormatter.java 22 Oct 2003 21:06:53 -0000 1.2 *************** *** 59,63 **** ValueFormatter() { - } --- 59,62 ---- |
From: <cob...@us...> - 2003-10-22 21:17:46
|
Update of /cvsroot/jrobin/src/jrobin/demo In directory sc8-pr-cvs1:/tmp/cvs-serv999/src/jrobin/demo Modified Files: ProfileGraphsOld.java ProfileGraphsNew.java JRobinGallery.java JRobinComplexGraph.java Log Message: New graph lib Add support for custom plotdefs Finalized some features Index: ProfileGraphsOld.java =================================================================== RCS file: /cvsroot/jrobin/src/jrobin/demo/ProfileGraphsOld.java,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** ProfileGraphsOld.java 21 Oct 2003 19:42:00 -0000 1.1 --- ProfileGraphsOld.java 22 Oct 2003 21:06:53 -0000 1.2 *************** *** 287,290 **** --- 287,292 ---- def.gprint("load", "AVERAGE", "Average: @5.2@s"); def.gprint("load", "LAST", "Current: @6.2@s\n"); + def.hrule( 3.0, Color.YELLOW, "legende", 5); + def.vrule( new GregorianCalendar(2003, 7, 24, 9, 00), Color.BLUE, "9am", 2 ); def.comment("\n"); def.comment("-------------------------------------------------------------------------------@c"); Index: ProfileGraphsNew.java =================================================================== RCS file: /cvsroot/jrobin/src/jrobin/demo/ProfileGraphsNew.java,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** ProfileGraphsNew.java 21 Oct 2003 19:42:00 -0000 1.1 --- ProfileGraphsNew.java 22 Oct 2003 21:06:53 -0000 1.2 *************** *** 52,56 **** // Demo sake ! private GregorianCalendar startDate = new GregorianCalendar(2003, 7, 24, 00, 00); private GregorianCalendar endDate = new GregorianCalendar(2003, 7, 25, 00, 00); --- 52,56 ---- // Demo sake ! private GregorianCalendar startDate = new GregorianCalendar(2003, 7, 24, 00, 30); private GregorianCalendar endDate = new GregorianCalendar(2003, 7, 25, 00, 00); *************** *** 288,291 **** --- 288,293 ---- def.gprint("load", "AVERAGE", "Average: @5.2@s"); def.gprint("load", "LAST", "Current: @6.2@s\n"); + def.hrule( 3.0, Color.YELLOW, "legende", 5); + def.vrule( new GregorianCalendar(2003, 7, 24, 9, 00), Color.BLUE, "9am", 2 ); def.comment("\n"); def.comment("-------------------------------------------------------------------------------@c"); Index: JRobinGallery.java =================================================================== RCS file: /cvsroot/jrobin/src/jrobin/demo/JRobinGallery.java,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** JRobinGallery.java 21 Oct 2003 19:42:00 -0000 1.2 --- JRobinGallery.java 22 Oct 2003 21:06:53 -0000 1.3 *************** *** 19,24 **** public static void graph7() throws RrdException, IOException { RrdGraphDef def = new RrdGraphDef(); ! GregorianCalendar start = new GregorianCalendar(2003, 4, 1); ! GregorianCalendar end = new GregorianCalendar(2003, 5, 1); def.setTimePeriod(start, end); long t0 = start.getTime().getTime() / 1000L; --- 19,24 ---- public static void graph7() throws RrdException, IOException { RrdGraphDef def = new RrdGraphDef(); ! GregorianCalendar start = new GregorianCalendar(2003, 3, 25); ! GregorianCalendar end = new GregorianCalendar(2003, 5, 5); def.setTimePeriod(start, end); long t0 = start.getTime().getTime() / 1000L; *************** *** 36,39 **** --- 36,40 ---- def.datasource("c" + i, "TIME," + t + ",GT,v2,UNKN,IF"); } + def.area( new GregorianCalendar( 2003, 4, 1 ), Double.MIN_VALUE, new GregorianCalendar( 2003, 5, 1 ), Double.MAX_VALUE, Color.ORANGE, "april 2003\n" ); for(int i = 0; i < n; i++) { if(i==0) { *************** *** 85,89 **** def.area("blank2", Color.WHITE, null); def.line("v1", Color.BLUE, null, 1); ! def.line("v2", Color.BLUE, null, 1); def.setTitle("Voltage measurement"); def.setVerticalLabel("[Volts]"); --- 86,90 ---- def.area("blank2", Color.WHITE, null); def.line("v1", Color.BLUE, null, 1); ! def.line("v2", null, null, 1); def.setTitle("Voltage measurement"); def.setVerticalLabel("[Volts]"); Index: JRobinComplexGraph.java =================================================================== RCS file: /cvsroot/jrobin/src/jrobin/demo/JRobinComplexGraph.java,v retrieving revision 1.10 retrieving revision 1.11 diff -C2 -d -r1.10 -r1.11 *** JRobinComplexGraph.java 21 Oct 2003 19:42:00 -0000 1.10 --- JRobinComplexGraph.java 22 Oct 2003 21:06:53 -0000 1.11 *************** *** 45,49 **** public static void main(String[] args) { ! GregorianCalendar start = new GregorianCalendar(2003, 7, 24, 20, 00); GregorianCalendar end = new GregorianCalendar(2003, 7, 25, 00, 00); --- 45,49 ---- public static void main(String[] args) { ! GregorianCalendar start = new GregorianCalendar(2003, 7, 24, 00, 00); GregorianCalendar end = new GregorianCalendar(2003, 7, 25, 00, 00); *************** *** 78,82 **** //gl.setAntiAliasing(false); gl.setGridRange( 0, 1, false ); ! gl.datasource("load", "c:/test.rrd", "serverLoad", "AVERAGE"); gl.datasource("user", "c:/test.rrd", "serverCPUUser", "AVERAGE"); --- 78,83 ---- //gl.setAntiAliasing(false); gl.setGridRange( 0, 1, false ); ! //gl.setBackground( "/demo6.png" ); ! //gl.setOverlay( "/demo6.png" ); gl.datasource("load", "c:/test.rrd", "serverLoad", "AVERAGE"); gl.datasource("user", "c:/test.rrd", "serverCPUUser", "AVERAGE"); *************** *** 93,97 **** gl.comment("CPU utilization (%)\n"); gl.comment(" "); ! //gl.hrule( 7.0, Color.YELLOW, null, 10f); gl.area("load", new Color(0x66,0x99,0xcc), " 0 - 25%"); gl.area("p25t50", new Color(0x00,0x66,0x99), "25 - 50%"); --- 94,98 ---- gl.comment("CPU utilization (%)\n"); gl.comment(" "); ! //gl.stack("load", Color.RED, null); gl.area("load", new Color(0x66,0x99,0xcc), " 0 - 25%"); gl.area("p25t50", new Color(0x00,0x66,0x99), "25 - 50%"); *************** *** 122,130 **** gl.gprint("load", "AVERAGE", "Average: @5.2@s"); gl.gprint("load", "LAST", "Current: @6.2@s\n"); ! gl.comment("\n"); ! gl.comment("-------------------------------------------------------------------------------@c"); ! //gl.vrule( new GregorianCalendar(2003, 7, 24, 9, 00), Color.BLUE, "9am", 2f ); //gl.vrule( new GregorianCalendar(2003, 7, 24, 17, 00), Color.BLUE, "5pm", 3f ); ! gl.comment("Generated: " + new Date() + "@R"); // Create the actual graph --- 123,136 ---- gl.gprint("load", "AVERAGE", "Average: @5.2@s"); gl.gprint("load", "LAST", "Current: @6.2@s\n"); ! //gl.hrule( 3.0, null, "legende", 1); ! //gl.vrule( new GregorianCalendar(2003, 7, 24, 9, 00), Color.BLUE, "9am", 2 ); ! gl.area( new GregorianCalendar(2003, 7, 24, 9, 00), Double.MIN_VALUE, new GregorianCalendar(2003, 7, 24, 17, 00), Double.MAX_VALUE, Color.ORANGE, "deviation@r" ); ! gl.area( new GregorianCalendar(2003, 7, 24, 8, 00), Double.MIN_VALUE, new GregorianCalendar(2003, 7, 24, 10, 00), Double.MAX_VALUE, Color.PINK, null ); ! gl.area( new GregorianCalendar(2003, 7, 24, 16, 00), Double.MIN_VALUE, new GregorianCalendar(2003, 7, 24, 18, 00), 12, Color.PINK, null ); ! gl.stack("load", Color.BLUE, "hmm"); ! gl.comment("\n-------------------------------------------------------------------------------@c"); ! //gl.vrule( new GregorianCalendar(2003, 7, 24, 17, 00), Color.BLUE, "5pm", 3f ); ! gl.comment("Generated: " + new Date() + "@L"); // Create the actual graph *************** *** 158,162 **** // Print out timing information for the new package API long s2 = Calendar.getInstance().getTimeInMillis(); ! System.out.println( "New package: " + (s2 - s1) + " ms" ); // -------------------------------------------------------- --- 164,168 ---- // Print out timing information for the new package API long s2 = Calendar.getInstance().getTimeInMillis(); ! System.err.println( "New package: " + (s2 - s1) + " ms" ); // -------------------------------------------------------- *************** *** 273,277 **** // Print out timings for the old graph API s2 = Calendar.getInstance().getTimeInMillis(); ! System.out.println( "Old package: " + (s2 - s1) + " ms" ); System.exit(0); --- 279,283 ---- // Print out timings for the old graph API s2 = Calendar.getInstance().getTimeInMillis(); ! System.err.println( "Old package: " + (s2 - s1) + " ms" ); System.exit(0); |
From: <sa...@us...> - 2003-10-22 15:23:44
|
Update of /cvsroot/jrobin/src/jrobin/core In directory sc8-pr-cvs1:/tmp/cvs-serv12502/jrobin/core Modified Files: FetchData.java RrdDb.java Added Files: RpnCalculator.java Log Message: Added aggregation functions (with RPN pre-processing) to FetchData class to easily obtain MIN, MAX, LAST or AVERAGE values of the fetched data... --- NEW FILE: RpnCalculator.java --- package jrobin.core; import java.util.StringTokenizer; class RpnCalculator { static final String VAR_PLACEHOLDER = "value"; private static final byte TOK_VAR = 0; private static final byte TOK_NUM = 1; private static final byte TOK_PLUS = 2; private static final byte TOK_MINUS = 3; private static final byte TOK_MULT = 4; private static final byte TOK_DIV = 5; private static final byte TOK_MOD = 6; private static final byte TOK_SIN = 7; private static final byte TOK_COS = 8; private static final byte TOK_LOG = 9; private static final byte TOK_EXP = 10; private static final byte TOK_FLOOR = 11; private static final byte TOK_CEIL = 12; private static final byte TOK_ROUND = 13; private static final byte TOK_POW = 14; private static final byte TOK_ABS = 15; private static final byte TOK_SQRT = 16; private static final byte TOK_RANDOM = 17; private static final byte TOK_LT = 18; private static final byte TOK_LE = 19; private static final byte TOK_GT = 20; private static final byte TOK_GE = 21; private static final byte TOK_EQ = 22; private static final byte TOK_IF = 23; private static final byte TOK_MIN = 24; private static final byte TOK_MAX = 25; private static final byte TOK_LIMIT = 26; private static final byte TOK_DUP = 27; private static final byte TOK_EXC = 28; private static final byte TOK_POP = 29; private static final byte TOK_UN = 30; private static final byte TOK_UNKN = 31; // private static final byte TOK_NOW = 32; // private static final byte TOK_TIME = 33; private static final byte TOK_PI = 34; private static final byte TOK_E = 35; private static final byte TOK_AND = 36; private static final byte TOK_OR = 37; private static final byte TOK_XOR = 38; private String[] tokens; private byte[] tokenCodes; private double[] parsedDoubles; private RpnStack stack = new RpnStack(); private String rpnExpression; private double value; // private long timestamp; RpnCalculator(String rpnExpression) throws RrdException { this.rpnExpression = rpnExpression; createTokens(); } void setValue(double value) { this.value = value; } /* not supported yet public void setTimestamp(long timestamp) { this.timestamp = timestamp; } */ private void createTokens() throws RrdException { StringTokenizer st = new StringTokenizer(rpnExpression, ","); int count = st.countTokens(); tokens = new String[count]; tokenCodes = new byte[count]; parsedDoubles = new double[count]; for(int i = 0; st.hasMoreTokens(); i++) { String token = st.nextToken(); tokens[i] = token; byte tokenCode = findTokenCode(token); tokenCodes[i] = tokenCode; if(tokenCode == TOK_NUM) { parsedDoubles[i] = Double.parseDouble(token); } } } private byte findTokenCode(String token) throws RrdException { if(isVariable(token)) { return TOK_VAR; } else if(isNumber(token)) { return TOK_NUM; } else if(token.equals("+")) { return TOK_PLUS; } else if(token.equals("-")) { return TOK_MINUS; } else if(token.equals("*")) { return TOK_MULT; } else if(token.equals("/")) { return TOK_DIV; } else if(token.equals("%")) { return TOK_MOD; } else if(token.equals("SIN")) { return TOK_SIN; } else if(token.equals("COS")) { return TOK_COS; } else if(token.equals("LOG")) { return TOK_LOG; } else if(token.equals("EXP")) { return TOK_EXP; } else if(token.equals("FLOOR")) { return TOK_FLOOR; } else if(token.equals("CEIL")) { return TOK_CEIL; } else if(token.equals("ROUND")) { return TOK_ROUND; } else if(token.equals("POW")) { return TOK_POW; } else if(token.equals("ABS")) { return TOK_ABS; } else if(token.equals("SQRT")) { return TOK_SQRT; } else if(token.equals("RANDOM")) { return TOK_RANDOM; } else if(token.equals("LT")) { return TOK_LT; } else if(token.equals("LE")) { return TOK_LE; } else if(token.equals("GT")) { return TOK_GT; } else if(token.equals("GE")) { return TOK_GE; } else if(token.equals("EQ")) { return TOK_EQ; } else if(token.equals("IF")) { return TOK_IF; } else if(token.equals("MIN")) { return TOK_MIN; } else if(token.equals("MAX")) { return TOK_MAX; } else if(token.equals("LIMIT")) { return TOK_LIMIT; } else if(token.equals("DUP")) { return TOK_DUP; } else if(token.equals("EXC")) { return TOK_EXC; } else if(token.equals("POP")) { return TOK_POP; } else if(token.equals("UN")) { return TOK_UN; } else if(token.equals("UNKN")) { return TOK_UNKN; } /* not supported yet else if(token.equals("NOW")) { return TOK_NOW; } else if(token.equals("TIME")) { return TOK_TIME; } */ else if(token.equals("PI")) { return TOK_PI; } else if(token.equals("E")) { return TOK_E; } else if(token.equals("AND")) { return TOK_AND; } else if(token.equals("OR")) { return TOK_OR; } else if(token.equals("XOR")) { return TOK_XOR; } else { throw new RrdException("Unknown RPN token encountered: " + token); } } private static boolean isNumber(String token) { try { Double.parseDouble(token); return true; } catch(NumberFormatException nfe) { return false; } } private static boolean isVariable(String token) { return token.equals(VAR_PLACEHOLDER); } double calculate() throws RrdException { resetCalculator(); for(int i = 0; i < tokenCodes.length; i++) { byte tokenCode = tokenCodes[i]; double x1, x2, x3; switch(tokenCode) { case TOK_NUM: push(parsedDoubles[i]); break; case TOK_VAR: push(value); break; case TOK_PLUS: push(pop() + pop()); break; case TOK_MINUS: x2 = pop(); x1 = pop(); push(x1 - x2); break; case TOK_MULT: push(pop() * pop()); break; case TOK_DIV: x2 = pop(); x1 = pop(); push(x1 / x2); break; case TOK_MOD: x2 = pop(); x1 = pop(); push(x1 % x2); break; case TOK_SIN: push(Math.sin(pop())); break; case TOK_COS: push(Math.cos(pop())); break; case TOK_LOG: push(Math.log(pop())); break; case TOK_EXP: push(Math.exp(pop())); break; case TOK_FLOOR: push(Math.floor(pop())); break; case TOK_CEIL: push(Math.ceil(pop())); break; case TOK_ROUND: push(Math.round(pop())); break; case TOK_POW: x2 = pop(); x1 = pop(); push(Math.pow(x1, x2)); break; case TOK_ABS: push(Math.abs(pop())); break; case TOK_SQRT: push(Math.sqrt(pop())); break; case TOK_RANDOM: push(Math.random()); break; case TOK_LT: x2 = pop(); x1 = pop(); push(x1 < x2? 1: 0); break; case TOK_LE: x2 = pop(); x1 = pop(); push(x1 <= x2? 1: 0); break; case TOK_GT: x2 = pop(); x1 = pop(); push(x1 > x2? 1: 0); break; case TOK_GE: x2 = pop(); x1 = pop(); push(x1 >= x2? 1: 0); break; case TOK_EQ: x2 = pop(); x1 = pop(); push(x1 == x2? 1: 0); break; case TOK_IF: x3 = pop(); x2 = pop(); x1 = pop(); push(x1 != 0? x2: x3); break; case TOK_MIN: push(Math.min(pop(), pop())); break; case TOK_MAX: push(Math.max(pop(), pop())); break; case TOK_LIMIT: x3 = pop(); x2 = pop(); x1 = pop(); push(x1 < x2 || x1 > x3? Double.NaN: x1); break; case TOK_DUP: x1 = pop(); push(x1); push(x1); break; case TOK_EXC: x2 = pop(); x1 = pop(); push(x2); push(x1); break; case TOK_POP: pop(); break; case TOK_UN: push(Double.isNaN(pop())? 1: 0); break; case TOK_UNKN: push(Double.NaN); break; /* not supported yet case TOK_NOW: push(Util.getTime()); break; case TOK_TIME: push(timestamp); break; */ case TOK_PI: push(Math.PI); break; case TOK_E: push(Math.E); break; case TOK_AND: x2 = pop(); x1 = pop(); push((x1 != 0 && x2 != 0)? 1: 0); break; case TOK_OR: x2 = pop(); x1 = pop(); push((x1 != 0 || x2 != 0)? 1: 0); break; case TOK_XOR: x2 = pop(); x1 = pop(); push(((x1 != 0 && x2 == 0) || (x1 == 0 && x2 != 0))? 1: 0); break; default: throw new RrdException("Unexpected RPN token encountered [" + tokenCode + "]"); } } double retVal = pop(); if(!isStackEmpty()) { throw new RrdException("Stack not empty at the end of calculation. " + "Probably bad RPN expression"); } return retVal; } void push(double x) throws RrdException { stack.push(x); } double pop() throws RrdException { return stack.pop(); } void resetCalculator() { stack.reset(); } boolean isStackEmpty() { return stack.isEmpty(); } class RpnStack { static final int MAX_STACK_SIZE = 1000; private double[] stack = new double[MAX_STACK_SIZE]; private int pos = 0; void push(double x) throws RrdException { if(pos >= MAX_STACK_SIZE) { throw new RrdException( "PUSH failed, RPN stack full [" + MAX_STACK_SIZE + "]"); } stack[pos++] = x; } double pop() throws RrdException { if(pos <= 0) { throw new RrdException("POP failed, RPN stack is empty "); } return stack[--pos]; } void reset() { pos = 0; } boolean isEmpty() { return pos == 0; } } public static void main(String[] args) throws RrdException { RpnCalculator c = new RpnCalculator("2,3,/,value,+"); c.setValue(5); System.out.println(c.calculate()); } } Index: FetchData.java =================================================================== RCS file: /cvsroot/jrobin/src/jrobin/core/FetchData.java,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** FetchData.java 22 Oct 2003 08:55:10 -0000 1.2 --- FetchData.java 22 Oct 2003 13:47:09 -0000 1.3 *************** *** 196,198 **** --- 196,317 ---- } + /** + * Returns aggregated value from the fetched data for a single datasource. + * @param dsName Datasource name + * @param consolFun Consolidation function to be applied to fetched datasource values. + * Valid consolidation functions are MIN, MAX, LAST and AVERAGE + * @return MIN, MAX, LAST or AVERAGE value calculated from the fetched data + * for the given datasource name + * @throws RrdException Thrown if the given datasource name cannot be found in fetched data. + */ + public double getAggregate(String dsName, String consolFun) throws RrdException { + return getAggregate(dsName, consolFun, null); + } + + /** + * Returns aggregated value from the fetched data for a single datasource. + * Before applying aggrregation functions, specified RPN expression is applied to fetched + * data. For example, if you have a gauge datasource named 'foots' but you wont to + * find the maximum fetched value in meters use something like:</p> + * <code>getAggregate("foots", "MAX", "value,0.3048,*");</code> + * Note that 'value' in the RPN expression is a reserved word and stands for the + * original value (value fetched from RRD file)</p> + * @param dsName Datasource name + * @param consolFun Consolidation function to be applied to fetched datasource values. + * Valid consolidation functions are MIN, MAX, LAST and AVERAGE + * @return MIN, MAX, LAST or AVERAGE value calculated from the fetched data + * for the given datasource name + * @throws RrdException Thrown if the given datasource name cannot be found in fetched data. + */ + public double getAggregate(String dsName, String consolFun, String rpnExpression) + throws RrdException { + if(consolFun.equals("MAX")) { + return getMax(dsName, rpnExpression); + } + else if(consolFun.equals("MIN")) { + return getMin(dsName, rpnExpression); + } + else if(consolFun.equals("LAST")) { + return getLast(dsName, rpnExpression); + } + else if(consolFun.equals("AVERAGE")) { + return getAverage(dsName, rpnExpression); + } + else { + throw new RrdException("Unsupported consolidation function [" + consolFun + "]"); + } + } + + private double getMax(String dsName, String rpnExpression) throws RrdException { + RpnCalculator rpnCalculator = null; + if(rpnExpression != null) { + rpnCalculator = new RpnCalculator(rpnExpression); + } + double vals[] = getValues(dsName), max = Double.NaN; + for(int i = 0; i < vals.length - 1; i++) { + double value = vals[i + 1]; + if(rpnCalculator != null) { + rpnCalculator.setValue(value); + value = rpnCalculator.calculate(); + } + max = Util.max(max, value); + } + return max; + } + + private double getMin(String dsName, String rpnExpression) throws RrdException { + RpnCalculator rpnCalculator = null; + if(rpnExpression != null) { + rpnCalculator = new RpnCalculator(rpnExpression); + } + double vals[] = getValues(dsName), min = Double.NaN; + for(int i = 0; i < vals.length - 1; i++) { + double value = vals[i + 1]; + if(rpnCalculator != null) { + rpnCalculator.setValue(value); + value = rpnCalculator.calculate(); + } + min = Util.min(min, value); + } + return min; + } + + private double getLast(String dsName, String rpnExpression) throws RrdException { + RpnCalculator rpnCalculator = null; + if(rpnExpression != null) { + rpnCalculator = new RpnCalculator(rpnExpression); + } + double vals[] = getValues(dsName); + double value = vals[vals.length - 1]; + if(rpnCalculator != null) { + rpnCalculator.setValue(value); + value = rpnCalculator.calculate(); + } + return value; + } + + private double getAverage(String dsName, String rpnExpression) throws RrdException { + RpnCalculator rpnCalculator = null; + if(rpnExpression != null) { + rpnCalculator = new RpnCalculator(rpnExpression); + } + double vals[] = getValues(dsName); + double totalVal = 0; + long totalSecs = 0; + for(int i = 0; i < vals.length - 1; i++) { + long t1 = Math.max(request.getFetchStart(), timestamps[i]); + long t2 = Math.min(request.getFetchEnd(), timestamps[i + 1]); + double value = vals[i + 1]; + if(rpnCalculator != null) { + rpnCalculator.setValue(value); + value = rpnCalculator.calculate(); + } + if(!Double.isNaN(value)) { + totalSecs += (t2 - t1); + totalVal += (t2 - t1) * value; + } + } + return totalSecs > 0? totalVal / totalSecs: Double.NaN; + } + } Index: RrdDb.java =================================================================== RCS file: /cvsroot/jrobin/src/jrobin/core/RrdDb.java,v retrieving revision 1.10 retrieving revision 1.11 diff -C2 -d -r1.10 -r1.11 *** RrdDb.java 22 Oct 2003 08:55:10 -0000 1.10 --- RrdDb.java 22 Oct 2003 13:47:09 -0000 1.11 *************** *** 643,645 **** --- 643,659 ---- close(); } + + public static void main(String[] args) throws RrdException, IOException { + RrdDb rrd = new RrdDb("demo.rrd"); + long t1 = Util.getTimestamp(2003, 4, 1); + long t2 = Util.getTimestamp(2003, 4, 2); + FetchData data = rrd.createFetchRequest("AVERAGE", t1, t2).fetchData(); + data.dump(); + System.out.println("MAX : " + data.getAggregate("sun", "MAX")); + System.out.println("MAX2: " + data.getAggregate("sun", "MAX", "value,2,*")); + System.out.println("MIN : " + data.getAggregate("sun", "MIN")); + System.out.println("MIN2: " + data.getAggregate("sun", "MIN", "value,2,*")); + System.out.println("AVG : " + data.getAggregate("sun", "AVERAGE")); + System.out.println("AVG2: " + data.getAggregate("sun", "AVERAGE", "value,2,*")); + } } |
From: <sa...@us...> - 2003-10-22 12:37:28
|
Update of /cvsroot/jrobin/src/jrobin/core In directory sc8-pr-cvs1:/tmp/cvs-serv32464/jrobin/core Modified Files: Archive.java FetchData.java FetchRequest.java RrdDb.java Log Message: fetch improvements Index: Archive.java =================================================================== RCS file: /cvsroot/jrobin/src/jrobin/core/Archive.java,v retrieving revision 1.6 retrieving revision 1.7 diff -C2 -d -r1.6 -r1.7 *** Archive.java 21 Oct 2003 12:53:05 -0000 1.6 --- Archive.java 22 Oct 2003 08:55:10 -0000 1.7 *************** *** 287,290 **** --- 287,294 ---- FetchPoint[] fetch(FetchRequest request) throws IOException, RrdException { + if(request.getFilter() != null) { + throw new RrdException("fetch() method does not support filtered datasources." + + " Use fetchData() to get filtered fetch data."); + } long arcStep = getArcStep(); long fetchStart = Util.normalize(request.getFetchStart(), arcStep); *************** *** 321,325 **** long startTime = getStartTime(); long endTime = getEndTime(); ! int dsCount = robins.length; int ptsCount = (int) ((fetchEnd - fetchStart) / arcStep + 1); long[] timestamps = new long[ptsCount]; --- 325,333 ---- long startTime = getStartTime(); long endTime = getEndTime(); ! String[] dsToFetch = request.getFilter(); ! if(dsToFetch == null) { ! dsToFetch = parentDb.getDsNames(); ! } ! int dsCount = dsToFetch.length; int ptsCount = (int) ((fetchEnd - fetchStart) / arcStep + 1); long[] timestamps = new long[ptsCount]; *************** *** 331,342 **** // inbound time int robinIndex = (int)((time - startTime) / arcStep); ! for(int dsIndex = 0; dsIndex < dsCount; dsIndex++) { ! values[dsIndex][ptIndex] = robins[dsIndex].getValue(robinIndex); } } else { // time out of bounds ! for(int dsIndex = 0; dsIndex < dsCount; dsIndex++) { ! values[dsIndex][ptIndex] = Double.NaN; } } --- 339,351 ---- // inbound time int robinIndex = (int)((time - startTime) / arcStep); ! for(int i = 0; i < dsCount; i++) { ! int dsIndex = parentDb.getDsIndex(dsToFetch[i]); ! values[i][ptIndex] = robins[dsIndex].getValue(robinIndex); } } else { // time out of bounds ! for(int i = 0; i < dsCount; i++) { ! values[i][ptIndex] = Double.NaN; } } Index: FetchData.java =================================================================== RCS file: /cvsroot/jrobin/src/jrobin/core/FetchData.java,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** FetchData.java 21 Oct 2003 13:50:29 -0000 1.1 --- FetchData.java 22 Oct 2003 08:55:10 -0000 1.2 *************** *** 56,60 **** FetchData(Archive matchingArchive, FetchRequest request) throws IOException { this.matchingArchive = matchingArchive; ! this.dsNames = matchingArchive.getParentDb().getDsNames(); this.request = request; } --- 56,63 ---- FetchData(Archive matchingArchive, FetchRequest request) throws IOException { this.matchingArchive = matchingArchive; ! this.dsNames = request.getFilter(); ! if(this.dsNames == null) { ! this.dsNames = matchingArchive.getParentDb().getDsNames(); ! } this.request = request; } *************** *** 175,179 **** /** ! * Returns array of datasource names found in the underlying RRD file. * @return Array of datasource names. */ --- 178,184 ---- /** ! * Returns array of datasource names found in the underlying RRD file. If the request ! * was filtered (data was fetched only for selected datasources), only datasources selected ! * for fetching are returned. * @return Array of datasource names. */ Index: FetchRequest.java =================================================================== RCS file: /cvsroot/jrobin/src/jrobin/core/FetchRequest.java,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** FetchRequest.java 21 Oct 2003 12:53:05 -0000 1.2 --- FetchRequest.java 22 Oct 2003 08:55:10 -0000 1.3 *************** *** 42,45 **** --- 42,46 ---- private long fetchEnd; private long resolution; + private String[] filter; FetchRequest(RrdDb parentDb, String consolFun, long fetchStart, long fetchEnd, *************** *** 54,57 **** --- 55,93 ---- /** + * Sets request filter in order to fetch data only for + * the specified array of datasources (datasource names). + * If not set (or set to null), fetched data will + * containt values of all datasources defined in the underlying RRD file. + * To fetch data only from selected + * datasources, specify an array of datasource names as method argument. + * @param filter Array of datsources (datsource names) to fetch data from. + */ + public void setFilter(String[] filter) { + this.filter = filter; + } + + /** + * Sets request filter in order to fetch data only for + * a single datasource (datasource name). + * If not set (or set to null), fetched data will + * containt values of all datasources defined in the underlying RRD file. + * To fetch data for a single datasource only, + * specify an array of datasource names as method argument. + * @param filter Array of datsources (datsource names) to fetch data from. + */ + public void setFilter(String filter) { + this.filter = (filter == null)? null: (new String[] { filter }); + } + + /** + * Returns request filter. See {@link #setFilter(String[]) setFilter()} for + * complete explanation. + * @return Request filter (array of datasource names), null if not set. + */ + public String[] getFilter() { + return filter; + } + + /** * Returns consolitation function to be used during the fetch process. * @return Consolidation function. *************** *** 142,145 **** --- 178,189 ---- public FetchData fetchData() throws RrdException, IOException { return parentDb.fetchData(this); + } + + /** + * Returns the underlying RrdDb object. + * @return RrdDb object used to create this FetchRequest object. + */ + public RrdDb getParentDb() { + return parentDb; } Index: RrdDb.java =================================================================== RCS file: /cvsroot/jrobin/src/jrobin/core/RrdDb.java,v retrieving revision 1.9 retrieving revision 1.10 diff -C2 -d -r1.9 -r1.10 *** RrdDb.java 21 Oct 2003 12:53:05 -0000 1.9 --- RrdDb.java 22 Oct 2003 08:55:10 -0000 1.10 *************** *** 24,28 **** import java.io.*; - import java.util.GregorianCalendar; /** --- 24,27 ---- |
From: <sa...@us...> - 2003-10-21 21:43:20
|
Update of /cvsroot/jrobin/src/jrobin/core In directory sc8-pr-cvs1:/tmp/cvs-serv5285/jrobin/core Modified Files: Util.java Log Message: minor changes Index: Util.java =================================================================== RCS file: /cvsroot/jrobin/src/jrobin/core/Util.java,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** Util.java 16 Oct 2003 09:26:30 -0000 1.5 --- Util.java 21 Oct 2003 14:42:31 -0000 1.6 *************** *** 27,30 **** --- 27,31 ---- import java.util.Date; import java.util.Locale; + import java.util.GregorianCalendar; /** *************** *** 112,115 **** --- 113,159 ---- } + /** + * Returns timestamp (unix epoch) for the given Date object + * @param date Date object + * @return Corresponding timestamp (without milliseconds) + */ + public static long getTimestamp(Date date) { + return (date.getTime() + 500L) / 1000L; + } + + /** + * Returns timestamp (unix epoch) for the given GregorianCalendar object + * @param gc GregorianCalendar object + * @return Corresponding timestamp (without milliseconds) + */ + public static long getTimestamp(GregorianCalendar gc) { + return getTimestamp(gc.getTime()); + } + + /** + * Returns timestamp (unix epoch) for the given year, month, day, hour and minute. + * @param year Year + * @param month Month (zero-based) + * @param day Day in month + * @param hour Hour + * @param min Minute + * @return Corresponding timestamp + */ + public static long getTimestamp(int year, int month, int day, int hour, int min) { + GregorianCalendar gc = new GregorianCalendar(year, month, day, hour, min); + return Util.getTimestamp(gc); + } + + /** + * Returns timestamp (unix epoch) for the given year, month and day. + * @param year Year + * @param month Month (zero-based) + * @param day Day in month + * @return Corresponding timestamp + */ + public static long getTimestamp(int year, int month, int day) { + return Util.getTimestamp(year, month, day, 0, 0); + } + static double parseDouble(String valueStr) { double value; *************** *** 122,125 **** return value; } - } --- 166,169 ---- return value; } } + |
Update of /cvsroot/jrobin/src/jrobin/graph2 In directory sc8-pr-cvs1:/tmp/cvs-serv2871/src/jrobin/graph2 Added Files: FetchSource.java RpnCalculator.java ValueAxisUnit.java Title.java Area.java ChartGraphics.java RrdGraphDef.java Gprint.java RrdGraph.java Comment.java Cdef.java Source.java GridRange.java TimeMarker.java ValueScaler.java Stack.java TimeAxisUnit.java Legend.java ValueMarker.java ValueExtractor.java LegendMarker.java Grapher.java Def.java PlotDef.java ValueFormatter.java Log Message: Experimental graph2 package major update, but very unfinished --- NEW FILE: FetchSource.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 jrobin.graph2; import java.util.Vector; import java.io.IOException; import jrobin.core.RrdDb; import jrobin.core.FetchPoint; import jrobin.core.FetchRequest; import jrobin.core.RrdException; /** * <p>Class used to group datasources per RRD db, for faster fetching.</p> * * @author Arne Vandamme (arn...@jr...) */ class FetchSource { static final int AVG = 0; static final int MAX = 1; static final int MIN = 2; static final int LAST = 3; static final int MAX_CF = 4; static final String[] cfNames = new String[] { "AVERAGE", "MAX", "MIN", "LAST" }; private String rrdFile; // Holds the name of the RRD file private int numSources = 0; private Vector[] datasources = new Vector[MAX_CF]; FetchSource( String rrdFile ) { this.rrdFile = rrdFile; // Initialization for (int i = 0; i < datasources.length; i++) datasources[i] = new Vector(); } FetchSource( String rrdFile, String consolFunc, String dsName, String name ) throws RrdException { this( rrdFile ); addSource( consolFunc, dsName, name ); } void addSource( String consolFunc, String dsName, String name ) throws RrdException { if ( consolFunc.equalsIgnoreCase("AVERAGE") || consolFunc.equalsIgnoreCase("AVG") ) datasources[AVG].add( new String[] { dsName, name } ); else if ( consolFunc.equalsIgnoreCase("MAX") || consolFunc.equalsIgnoreCase("MAXIMUM") ) datasources[MAX].add( new String[] { dsName, name } ); else if ( consolFunc.equalsIgnoreCase("MIN") || consolFunc.equalsIgnoreCase("MINIMUM") ) datasources[MIN].add( new String[] { dsName, name } ); else if ( consolFunc.equalsIgnoreCase("LAST") ) datasources[LAST].add( new String[] { dsName, name } ); else throw new RrdException( "Invalid consolidation function specified." ); numSources++; } String getRrdFile() { return rrdFile; } ValueExtractor fetch( RrdDb rrd, long startTime, long endTime ) throws IOException, RrdException { long rrdStep = rrd.getRrdDef().getStep(); FetchPoint[][] result = new FetchPoint[datasources.length][]; int[][] indices = new int[MAX_CF][]; for (int i = 0; i < datasources.length; i++) { if ( datasources[i].size() > 0 ) { // Fetch datasources FetchRequest request = rrd.createFetchRequest( cfNames[i], startTime, endTime + rrdStep); FetchPoint[] fetchPoints = request.fetch(); result[i] = fetchPoints; indices[i] = new int[datasources[i].size()]; } else indices[i] = new int[0]; } String[] names = new String[numSources]; int tblPos = 0; for (int i = 0; i < datasources.length; i++) { for (int j = 0; j < datasources[i].size(); j++) { String[] spair = (String[])datasources[i].elementAt(j); indices[i][j] = rrd.getDsIndex(spair[0]); names[tblPos++] = spair[1]; } } return new ValueExtractor( names, indices, result ); } } --- NEW FILE: RpnCalculator.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 jrobin.graph2; import java.util.ArrayList; import jrobin.core.Util; import jrobin.core.RrdException; /** * <p>Used to calculate result of an RPN expression.</p> * * @author Arne Vandamme (arn...@jr...) * @author Sasa Markovic (sa...@jr...) */ public class RpnCalculator { // Token definitions public static final byte TKN_CONSTANT = 0; public static final byte TKN_DATASOURCE = 1; public static final byte TKN_PLUS = 2; public static final byte TKN_MINUS = 3; public static final byte TKN_MULTIPLY = 4; public static final byte TKN_DIVIDE = 5; public static final byte TKN_MOD = 6; public static final byte TKN_SIN = 7; public static final byte TKN_COS = 8; public static final byte TKN_LOG = 9; public static final byte TKN_EXP = 10; public static final byte TKN_FLOOR = 11; public static final byte TKN_CEIL = 12; public static final byte TKN_ROUND = 13; public static final byte TKN_POW = 14; public static final byte TKN_ABS = 15; public static final byte TKN_SQRT = 16; public static final byte TKN_RANDOM = 17; public static final byte TKN_LT = 18; public static final byte TKN_LE = 19; public static final byte TKN_GT = 20; public static final byte TKN_GE = 21; public static final byte TKN_EQ = 22; public static final byte TKN_IF = 23; public static final byte TKN_MIN = 24; public static final byte TKN_MAX = 25; public static final byte TKN_LIMIT = 26; public static final byte TKN_DUP = 27; public static final byte TKN_EXC = 28; public static final byte TKN_POP = 29; public static final byte TKN_UN = 30; public static final byte TKN_UNKN = 31; public static final byte TKN_NOW = 32; public static final byte TKN_TIME = 33; public static final byte TKN_PI = 34; public static final byte TKN_E = 35; public static final byte TKN_AND = 36; public static final byte TKN_OR = 37; public static final byte TKN_XOR = 38; private Source[] sources; ArrayList stack = new ArrayList(); RpnCalculator( Source[] sources ) { this.sources = sources; } double evaluate( Cdef cdef, int row, long timestamp ) throws RrdException { stack.clear(); byte[] tokens = cdef.tokens; int[] dsIndices = cdef.dsIndices; double[] constants = cdef.constants; double x1, x2, x3; for ( int i = 0; i < tokens.length; i++ ) { switch ( tokens[i] ) { case TKN_CONSTANT: push( constants[i] ); break; case TKN_DATASOURCE: push( sources[ dsIndices[i] ].get(row) ); break; case TKN_PLUS: push(pop() + pop()); break; case TKN_MINUS: x2 = pop(); x1 = pop(); push(x1 - x2); break; case TKN_MULTIPLY: push(pop() * pop()); break; case TKN_DIVIDE: x2 = pop(); x1 = pop(); push(x1 / x2); break; case TKN_MOD: x2 = pop(); x1 = pop(); push(x1 % x2); break; case TKN_SIN: push(Math.sin(pop())); break; case TKN_COS: push(Math.cos(pop())); break; case TKN_LOG: push(Math.log(pop())); break; case TKN_EXP: push(Math.exp(pop())); break; case TKN_FLOOR: push(Math.floor(pop())); break; case TKN_CEIL: push(Math.ceil(pop())); break; case TKN_ROUND: push(Math.round(pop())); break; case TKN_POW: x2 = pop(); x1 = pop(); push(Math.pow(x1, x2)); break; case TKN_ABS: push(Math.abs(pop())); break; case TKN_SQRT: push(Math.sqrt(pop())); break; case TKN_RANDOM: push(Math.random()); break; case TKN_LT: x2 = pop(); x1 = pop(); push(x1 < x2? 1: 0); break; case TKN_LE: x2 = pop(); x1 = pop(); push(x1 <= x2? 1: 0); break; case TKN_GT: x2 = pop(); x1 = pop(); push(x1 > x2? 1: 0); break; case TKN_GE: x2 = pop(); x1 = pop(); push(x1 >= x2? 1: 0); break; case TKN_EQ: x2 = pop(); x1 = pop(); push(x1 == x2? 1: 0); break; case TKN_IF: x3 = pop(); x2 = pop(); x1 = pop(); push(x1 != 0 ? x2: x3); break; case TKN_MIN: push(Math.min(pop(), pop())); break; case TKN_MAX: push(Math.max(pop(), pop())); break; case TKN_LIMIT: double high = pop(), low = pop(), value = pop(); push(value < low || value > high? Double.NaN: value); break; case TKN_DUP: double x = pop(); push(x); push(x); break; case TKN_EXC: x2 = pop(); x1 = pop(); push(x2); push(x1); break; case TKN_POP: pop(); break; case TKN_UN: push(Double.isNaN(pop())? 1: 0); break; case TKN_UNKN: push(Double.NaN); break; case TKN_NOW: push(Util.getTime()); break; case TKN_TIME: push(timestamp); break; case TKN_PI: push(Math.PI); break; case TKN_E: push(Math.E); break; case TKN_AND: x2 = pop(); x1 = pop(); push((x1 != 0 && x2 != 0)? 1: 0); break; case TKN_OR: x2 = pop(); x1 = pop(); push((x1 != 0 || x2 != 0)? 1: 0); break; case TKN_XOR: x2 = pop(); x1 = pop(); push(((x1 != 0 && x2 == 0) || (x1 == 0 && x2 != 0))? 1: 0); break; } } if (stack.size() != 1) throw new RrdException("RPN error, invalid stack length"); return pop(); } private void push( double value ) { stack.add( new Double(value) ); } private double pop() throws RrdException { int last = stack.size() - 1; if ( last < 0 ) throw new RrdException("POP failed, stack empty"); Double lastValue = (Double) stack.get(last); stack.remove(last); return lastValue.doubleValue(); } } --- NEW FILE: ValueAxisUnit.java --- /* ============================================================ * JRobin : Pure java implementation of RRDTool's functionality * ============================================================ * * Project Info: http://www.sourceforge.net/projects/jrobin * Project Lead: Sasa Markovic (sa...@eu...); * * (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. */ /* * Created on 29-aug-2003 * * To change the template for this generated file go to * Window - Preferences - Java - Code Generation - Code and Comments */ package jrobin.graph2; import java.util.*; /** * @author cbld * * To change the template for this generated type comment go to * Window - Preferences - Java - Code Generation - Code and Comments */ public class ValueAxisUnit { private double labelStep = 2; private double markStep = 1; private int roundStep = 2; private int gridUnit = 1; // minor grid private double gridParts = 2d; private int mGridUnit = 10; // major grid private double mGridParts = 1d; private double gridStep = 2; private double mGridStep = 10; ValueAxisUnit( double labelStep, double markStep, int roundStep ) { this.labelStep = labelStep; this.markStep = markStep; this.roundStep = roundStep; } ValueAxisUnit( int gridUnit, double gridParts, int mGridUnit, double mGridParts ) { this.gridUnit = gridUnit; this.gridParts = gridParts; this.mGridUnit = mGridUnit; this.mGridParts = mGridParts; gridStep = gridUnit * gridParts; mGridStep = mGridUnit * mGridParts; } private double round( double value ) { return round( value, 14 ); // Big precision } private double round( double value, int numDecs ) { return new java.math.BigDecimal(value).setScale(numDecs , java.math.BigDecimal.ROUND_HALF_EVEN).doubleValue(); } public ValueMarker[] getValueMarkers( double lower, double upper, double base, int scaleIndex ) { double minPoint = 0.0d; double majPoint = 0.0d; // Find the first visible gridpoint if ( lower > 0 ) { while ( minPoint < lower ) minPoint += gridStep; while ( majPoint < lower ) majPoint += mGridStep; } else { while ( minPoint > lower ) minPoint -= gridStep; while ( majPoint > lower ) majPoint -= mGridStep; // Go one up to make it visible if (minPoint != lower ) minPoint += gridStep; if (majPoint != lower ) majPoint += mGridStep; } // Now get all time markers. // Again we choose to use a series of loops as to avoid unnecessary drawing. ArrayList markerList = new ArrayList(); while ( minPoint <= upper && majPoint <= upper ) { if ( minPoint < majPoint ) { markerList.add( new ValueMarker(minPoint, "", false) ); minPoint = round( minPoint + gridStep ); } else { String str; ValueScaler vs = new ValueScaler( majPoint, scaleIndex, base); int ival = new Double(vs.getScaledValue()).intValue(); if ( ival == vs.getScaledValue() ) str = (ival + vs.getPrefix()).trim(); else str = (round(vs.getScaledValue(), 2) + vs.getPrefix()).trim(); if ( minPoint == majPoint ) // Special case, but will happen most of the time { markerList.add( new ValueMarker(majPoint, str, true) ); minPoint = round( minPoint + gridStep ); majPoint = round( majPoint + mGridStep ); } else { markerList.add( new ValueMarker(majPoint, str, true) ); majPoint = round( majPoint + mGridStep ); } } } while ( minPoint <= upper ) { markerList.add( new ValueMarker(minPoint, "", false) ); minPoint = round( minPoint + gridStep ); } while ( majPoint <= upper ) { String str; ValueScaler vs = new ValueScaler( majPoint, scaleIndex, base); int ival = new Double(vs.getScaledValue()).intValue(); if ( ival == vs.getScaledValue() ) str = (ival + vs.getPrefix()).trim(); else str = (vs.getScaledValue() + vs.getPrefix()).trim(); markerList.add( new ValueMarker(majPoint, str, true) ); majPoint = round( majPoint + mGridStep ); } return (ValueMarker[]) markerList.toArray( new ValueMarker[0] ); } public double getNiceLower( double ovalue ) { // Add some checks double gridParts = this.gridParts; double mGridParts = this.mGridParts; double gridFactor = 1.0; double mGridFactor = 1.0; if ( gridUnit * gridParts < 1.0 ) { gridParts *= 100; gridFactor = 100; } if ( mGridUnit * mGridParts < 1.0 ) { mGridParts *= 100; mGridFactor = 100; } double value = ovalue * gridFactor; int valueInt = new Double(value).intValue(); int roundStep = new Double(gridUnit * gridParts).intValue(); if ( roundStep == 0 ) roundStep = 1; int num = valueInt / roundStep; int mod = valueInt % roundStep; double gridValue = (roundStep * num) * 1.0d; if ( gridValue > value ) gridValue -= roundStep; if ( num == 0 && value >= 0 ) gridValue = 0.0; else if ( Math.abs(gridValue - value) < (gridParts * gridUnit) / 16 ) gridValue -= roundStep; value = ovalue * mGridFactor; roundStep = new Double(mGridUnit * mGridParts).intValue(); if ( roundStep == 0 ) roundStep = 1; num = valueInt / roundStep; mod = valueInt % roundStep; double mGridValue = (roundStep * num) * 1.0d; if ( mGridValue > value ) mGridValue -= roundStep; if ( value != 0.0d ) { if ( Math.abs(mGridValue - gridValue) < (mGridParts * mGridUnit) / 2) return mGridValue / mGridFactor; else return gridValue / gridFactor; } return ovalue; } public double getNiceHigher( double ovalue ) { // Add some checks double gridParts = this.gridParts; double mGridParts = this.mGridParts; double gridFactor = 1.0; double mGridFactor = 1.0; if ( gridUnit * gridParts < 1.0 ) { gridParts *= 100; gridFactor = 100; } if ( mGridUnit * mGridParts < 1.0 ) { mGridParts *= 100; mGridFactor = 100; } double value = ovalue * gridFactor; int valueInt = new Double(value).intValue(); int roundStep = new Double(gridUnit * gridParts).intValue(); if ( roundStep == 0 ) roundStep = 1; int num = valueInt / roundStep; int mod = valueInt % roundStep; double gridValue = (roundStep * (num + 1)) * 1.0d; if ( gridValue - value < (gridParts * gridUnit) / 8 ) gridValue += roundStep; value = ovalue * mGridFactor; roundStep = new Double(mGridUnit * mGridParts).intValue(); if ( roundStep == 0 ) roundStep = 1; num = valueInt / roundStep; mod = valueInt % roundStep; double mGridValue = (roundStep * (num + 1)) * 1.0d; if ( value != 0.0d ) { if ( Math.abs(mGridValue - gridValue) < (mGridParts * mGridUnit) / 2) return mGridValue / mGridFactor; else return gridValue / gridFactor; } return ovalue; } } --- NEW FILE: Title.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 jrobin.graph2; import jrobin.core.RrdException; /** * <p>description</p> * * @author Arne Vandamme (arn...@jr...) * @author Sasa Markovic (sa...@jr...) */ class Title extends Comment { Title( String text ) throws RrdException { this.text = text; lfToken = Comment.TKN_ACF; super.parseComment(); } } --- NEW FILE: Area.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 jrobin.graph2; import java.awt.Color; /** * <p>description</p> * * @author Arne Vandamme (arn...@jr...) */ class Area extends PlotDef { Area( String sourceName, Color c ) { super( sourceName, c ); this.plotType = PlotDef.PLOT_AREA; } Area( Source source, Color c, boolean stacked ) { super( source, c, stacked ); } void draw( ChartGraphics g, int[] xValues, int[] stackValues, int lastPlotType ) { g.setColor( color ); int ax = 0, ay = 0, py; int nx = 0, ny = 0, last = -1; for (int i = 0; i < xValues.length; i++) { py = 0; nx = xValues[i]; ny = g.getY( source.values[i] ); if ( stacked ) { py = stackValues[i]; ny += stackValues[i]; } if (nx > ax + 1) // More than one pixel hop, draw intermediate pixels too { // For each pixel between nx and ax, calculate the y, plot the line int co = (ny - ay) / (nx - ax); int j = (ax > 0 ? ax : 1 ); // Skip 0 for (j = ax; j <= nx; j++) g.drawLine( j, py, j, ( co * (j - ax) + ay) ); } else if ( nx != 0 && py != Integer.MIN_VALUE && ny != Integer.MIN_VALUE ) g.drawLine( nx, py, nx, ny ); stackValues[i] = ny; ax = nx; ay = ny; } } } --- NEW FILE: ChartGraphics.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 jrobin.graph2; import java.awt.Color; import java.awt.Stroke; import java.awt.Graphics2D; /** * <p>description</p> * * @author Arne Vandamme (arn...@jr...) */ public class ChartGraphics { Graphics2D g; private int width, height; private long xStart, xEnd; private double yStart, yEnd; double widthDelta = 1.0d, heightDelta = 3.0d; ChartGraphics( Graphics2D graphics ) { g = graphics; } void drawLine(int x1, int y1, int x2, int y2) { g.drawLine( x1, -y1, x2, -y2 ); } // Contrary to Graphics2D fillRect, this method uses boundary points void fillRect(int x1, int y1, int x2, int y2) { g.fillRect( x1, -y2, x2 - x1, y2 - y1 ); } void setColor( Color c ) { g.setColor( c ); } void setMeasurements( int width, int height ) { this.width = width; this.height = height; } void setXRange( long start, long end ) { xStart = start; xEnd = end; if ( xEnd != xStart ) widthDelta = width * 1.0d / (( xEnd - xStart) * 1.0d); else widthDelta = 1.0d; } void setYRange( double lower, double upper ) { yStart = lower; yEnd = upper; if ( yEnd != yStart ) heightDelta = height * 1.0d / (( yEnd - yStart) * 1.0d); else heightDelta = 1.0d; } int getX( long timestamp ) { return new Double((timestamp - xStart) * widthDelta).intValue(); } int getY( double value ) { if ( Double.isNaN(value) ) return Integer.MIN_VALUE; int tmp = new Double( (value - ( yStart < 0 ? 0 : Math.abs(yStart) ) ) * heightDelta).intValue(); return ( tmp > value * heightDelta ? tmp - 1 : tmp ); } void setStroke( Stroke s ) { g.setStroke( s ); } } --- NEW FILE: RrdGraphDef.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 jrobin.graph2; import java.io.File; import java.io.Serializable; import java.awt.Font; import java.awt.Color; import java.awt.BasicStroke; import java.util.Date; import java.util.Vector; import java.util.HashMap; import java.util.GregorianCalendar; import jrobin.core.Util; import jrobin.core.RrdException; /** * <p>Class used to collect information for the new JRobin graph. JRobin graphs have many * options and this class has methods and properties to set them.</p> * * <p>At this moment, JRobin graphs are quite good looking, but RRDTool is still better. * However, JRobin graphs have almost the same potential as RRDTool's graph command. To learn * more about RRDTool's graphs see RRDTool's * <a href="../../../man/rrdgraph.html" target="man">rrdgraph man page</a>.</p> This man page * is important: JRobin uses the same concept of graph sources definition (DEF directives) * and supports RPN extensions in complex datasource definitions (RRDTool's CDEF directives).</p> * * <p><code>RrdGraphDef</code> class does not actually create any graph. It just collects necessary information. * Graph will be created when you pass <code>RrdGraphDef</code> object to the constructor * of {@link jrobin.graph.RrdGraph RrdGraph} object.</p> * * @author Arne Vandamme (arn...@jr...) * @author Sasa Markovic (sa...@jr...) */ public class RrdGraphDef implements Serializable { // ================================================================ // -- Members // ================================================================ long endTime = Util.getTime(); // default time spam of the last 24 hours long startTime = Util.getTime() - 86400L; Title title = null; // no title String valueAxisLabel = null; // no vertical label boolean gridX = true; // hide entire X axis grid (default: no) boolean gridY = true; // hide entire Y axis grid (default: no) boolean minorGridX = true; // hide minor X axis grid (default: no) boolean minorGridY = true; // hide minor Y axis grid (default: no) boolean majorGridX = true; // hide major X axis grid with labels (default: no) boolean majorGridY = true; // hide major Y axis grid with labels (default: no) boolean rigidGrid = false; // disable auto scaling of grid range (default: no) boolean frontGrid = true; // show grid in front of the chart (default: yes) boolean antiAliasing = true; // use anti-aliasing for the chart (default: yes) boolean showLegend = true; // show legend and comments (default: yes) Color backColor = new Color( 245, 245, 245 ); // variation of light gray Color canvasColor = Color.WHITE; // white Color borderColor = Color.LIGHT_GRAY; // light gray, only applicable with a borderStroke Color normalFontColor = Color.BLACK; // black Color titleFontColor = Color.BLACK; // black Color majorGridColor = new Color(130,30,30); // variation of dark red Color minorGridColor = new Color(140,140,140); // variation of gray Color axisColor = new Color(130,30,30); // variation of dark red Color arrowColor = Color.RED; // red Color frameColor = Color.LIGHT_GRAY; // light gray Font titleFont = null; // use default 'grapher' font Font normalFont = null; // use default 'grapher' font File background = null; // no background image by default File overlay = null; // no overlay image by default int chart_lpadding = Grapher.CHART_LPADDING; BasicStroke borderStroke = null; // defaults to standard beveled border double baseValue = 1000; int scaleIndex = -1; // NO_SCALE GridRange gridRange = null; int numDefs = 0; int commentLines = 0; int commentLineShift = 0; HashMap fetchSources = new HashMap(); Vector cdefList = new Vector(); Vector plotDefs = new Vector(); Vector comments = new Vector(); // ================================================================ // -- Constructors // ================================================================ /** * Constructs a new JRobin graph object. */ public RrdGraphDef() { // Default constructor } /** * Constructs a new JRobin graph object, with a specified time span to be presented on the graph. * Using timestamps defined as number of seconds since the epoch. * @param startTime Starting timestamp in seconds. * @param endTime Ending timestamp in secons. * @throws RrdException Thrown if invalid parameters are supplied. */ public RrdGraphDef( long startTime, long endTime ) throws RrdException { setTimePeriod( startTime, endTime ); } /** * Constructs a new JRobin graph object, with a specified time span to be presented on the graph. * Time spam defined using <code>java.util.Date</code> objects. * @param start Starting time. * @param end Ending time. * @throws RrdException Thrown in case of invalid parameters. */ public RrdGraphDef( Date start, Date end) throws RrdException { setTimePeriod( start, end ); } /** * Constructs a new JRobin graph object, with a specified time span to be presented on the graph. * Time spam defined using <code>java.util.GregorianCalendar</code> objects. * @param start Starting time. * @param end Ending time. * @throws RrdException Thrown in case of invalid parameters. */ public RrdGraphDef( GregorianCalendar start, GregorianCalendar end ) throws RrdException { setTimePeriod( start, end ); } // ================================================================ // -- Public methods // ================================================================ /** * Sets time span to be presented on the graph using timestamps. * @param startTime Starting timestamp in seconds. * @param endTime Ending timestamp in secons. * @throws RrdException Thrown if invalid parameters are supplied. */ public void setTimePeriod( long startTime, long endTime ) throws RrdException { if ( startTime < 0 || endTime <= startTime ) throw new RrdException( "Invalid graph start/end time: " + startTime + "/" + endTime ); this.startTime = startTime; this.endTime = endTime; } /** * Sets time span to be presented on the graph using <code>java.util.Date</code> objects. * @param start Starting time. * @param end Ending time. * @throws RrdException Thrown in case of invalid parameters. */ public void setTimePeriod( Date start, Date end ) throws RrdException { setTimePeriod( start.getTime() / 1000L, end.getTime() / 1000L ); } /** * Sets time span to be presented on the graph using <code>java.util.GregorianCalendar</code> objects. * @param start Starting time. * @param end Ending time * @throws RrdException Thrown if invalid parameters are supplied. */ public void setTimePeriod( GregorianCalendar start, GregorianCalendar end ) throws RrdException { setTimePeriod( start.getTime(), end.getTime() ); } /** * Sets graph title. * @param title Graph title. */ public void setTitle( String title ) throws RrdException { this.title = new Title( title ); } /** * Sets vertical (value) axis label. * @param valueAxisLabel Axis label. */ public void setVerticalLabel( String valueAxisLabel) { this.valueAxisLabel = valueAxisLabel; } /** * Sets image background color. If not set, back color defaults to a very light gray. * @param backColor Graph background color. */ public void setBackColor( Color backColor ) { this.backColor = backColor; } /** * Sets chart area background color. If not set, back color defaults to white. * @param backColor Chart area background color. */ public void setCanvasColor( Color canvasColor ) { this.canvasColor = canvasColor; } /** * Specifies the settings of the image border. * Default is sort of beveled border around the image. * @param c Bordercolor of the image. * @param w Pixel width of the image border. */ public void setImageBorder( Color c, int w ) { this.borderStroke = new BasicStroke( w ); if ( c != null ) this.borderColor = c; } /** * Sets the color of the title font used in the graph. * @param c The color to be used. */ public void setTitleFontColor( Color c ) { this.titleFontColor = c; } /** * Sets the color of the default font used in the graph. * @param c The color to be used. */ public void setDefaultFontColor( Color c ) { this.normalFontColor = c; } /** * Sets the font to be used for the graph title. * @param f The Font to be used. */ public void setTitleFont( Font f ) { this.titleFont = f; } /** * Sets the default font to be used in the graph. * @param f The Font to be used. */ public void setDefaultFont( Font f ) { this.normalFont = f; } /** * Determines the color of the major grid. * @param c Color to use. */ public void setMajorGridColor( Color c ) { this.majorGridColor = c; } /** * Determines the color of the minor grid. * @param c Color to use. */ public void setMinorGridColor( Color c ) { this.minorGridColor = c; } /** * Determines the color of chart area frame. * @param c Color to use. */ public void setFrameColor( Color c ) { this.frameColor = c; } /** * Determines the color of X axis. * @param c Color to use. */ public void setAxisColor( Color c ) { this.axisColor = c; } /** * Determines the color of the small axis arrow on the X axis. * @param c Color to use. */ public void setArrowColor( Color c ) { this.arrowColor = c; } /** * Determines if the minor grid for the X axis needs to be drawn. * @param visible True if minor grid needs to be drawn, false if not. */ public void setMinorGridX( boolean visible ) { this.minorGridX = visible; } /** * Determines if the minor grid for the Y axis needs to be drawn. * @param visible True if minor grid needs to be drawn, false if not. */ public void setMinorGridY( boolean visible ) { this.minorGridY = visible; } /** * Determines if the major grid with labels for the X axis needs to be drawn. * @param visible True if major grid needs to be drawn, false if not. */ public void setMajorGridX( boolean visible ) { this.majorGridX = visible; } /** * Determines if the major grid width labels for the Y axis needs to be drawn. * @param visible True if major grid needs to be drawn, false if not. */ public void setMajorGridY( boolean visible ) { this.majorGridY = visible; } /** * Determines if the X axis grid should be drawn. * This will not change the left padding of the drawing area. * @param visible True if grid needs to be drawn, false if not. */ public void setGridX( boolean visible ) { this.gridX = visible; } /** * Determines if the Y axis grid should be drawn. * This will not change the bottom padding of the drawing area. * @param visible True if grid needs to be drawn, false if not. */ public void setGridY( boolean visible ) { this.gridY = visible; } /** * Determines if the grid should have rigid upper and lower limits. * If so the upper and lower limit will not autoscale depending on the * graph values. Default uses grid autoscaling. * @param rigid True if the grid should have rigid limits. */ public void setRigidGrid( boolean rigid ) { this.rigidGrid = rigid; } /** * Determine if the graph grid is in front of the graphs itself, or behind it. * Default is in front of the graph itself. * @param frontGrid True if the grid is in front of the graphs. */ public void setFrontGrid( boolean frontGrid ) { this.frontGrid = frontGrid; } /** * Determine if the legend should be visible or not, default: visible. * @param showLegend True if the legend is visible. */ public void setShowLegend( boolean showLegend ) { this.showLegend = showLegend; } /** * Set the anti-aliasing option for the drawing area of the graph. * Default uses anti-aliasing. * @param aa True if anti-aliasing is on, false if off */ public void setAntiAliasing( boolean aa ) { this.antiAliasing = aa; } /** * Set the number of pixels on the left of the canvas area ( value marker space ). * @param lp Number of pixels used, defaults to 50. */ public void setChartLeftPadding( int lp ) { this.chart_lpadding = lp; } /** * <p>Adds simple graph source to graph definition. Graph source <code>name</code> * can be used:</p> * <ul> * <li>To specify sources for line, area and stack plots. * <li>To define complex graph sources * (see {@link #datasource(java.lang.String, java.lang.String) complex graph * source definition}). * <li>To specify graph data source for the * {@link #gprint(java.lang.String, java.lang.String, java.lang.String) gprint()} method. * @param name Graph source name. * @param file Path to RRD file. * @param dsName Data source name defined in the RRD file. * @param consolFun Consolidation function that will be used to extract data from the RRD * file ("AVERAGE", "MIN", "MAX" or "LAST"). */ public void datasource( String name, String file, String dsName, String consolFunc ) throws RrdException { if ( fetchSources.containsKey(file) ) { FetchSource rf = (FetchSource) fetchSources.get(file); rf.addSource( consolFunc, dsName, name ); } else fetchSources.put( file, new FetchSource(file, consolFunc, dsName, name) ); numDefs++; } /** * <p>Adds complex graph source with the given name to the graph definition. * Complex graph sources are evaluated using the supplied <code>rpn</code> expression. * * <p>Complex graph source <code>name</code> can be used:</p> * <ul> * <li>To specify sources for line, area and stack plots. * <li>To define other complex graph sources. * <li>To specify graph data source for the * {@link #gprint(java.lang.String, java.lang.String, java.lang.String) gprint()} method. * * <p>JRobin supports the following RPN functions, operators and constants: +, -, *, /, * %, SIN, COS, LOG, EXP, FLOOR, CEIL, ROUND, POW, ABS, SQRT, RANDOM, LT, LE, GT, GE, EQ, * IF, MIN, MAX, LIMIT, DUP, EXC, POP, UN, UNKN, NOW, TIME, PI and E. JRobin does not * force you to specify at least one simple graph source name as RRDTool.</p> * * <p>For more details on RPN see RRDTool's * <a href="../../../man/rrdgraph.html" target="man">rrdgraph man page</a>.</p> * @param name Graph source name. * @param rpn RPN expression containig comma delmited simple and complex graph * source names, RPN constants, functions and operators. */ public void datasource( String name, String rpn ) { cdefList.add( new Cdef(name, rpn) ); } /** * Adds line plot to the graph definition, using the specified color and legend. This method * takes exactly the same parameters as RRDTool's LINE1 directive (line width * is set to 1). There is only * one limitation: so far, legends in JRobin graphs are always centered (don't * try to specify alignment in the legend string). * * @param sourceName Graph source name. * @param color Line collor to be used. * @param legend Legend to be printed on the graph. * @throws RrdException Thrown if invalid graph source name is supplied. */ public void line( String sourceName, Color color, String legend ) throws RrdException { plotDefs.add( new PlotDef(sourceName, color) ); addLegend( legend, color ); } /** * Adds line plot to the graph definition, using the specified color, legend and line width. * This method takes exactly the same parameters as RRDTool's LINE directive. There is only * one limitation: so far, legends in JRobin graphs are always centered (don't * try to specify alignment in the legend string). * * @param sourceName Graph source name. * @param color Line collor to be used. * @param legend Legend to be printed on the graph. * @throws RrdException Thrown if invalid graph source name is supplied. */ public void line( String sourceName, Color color, String legend, int lineWidth ) throws RrdException { plotDefs.add( new PlotDef(sourceName, color, lineWidth) ); addLegend( legend, color ); } /** * Adds area plot to the graph definition, * using the specified color and legend. This method * takes exactly the same parameters as RRDTool's AREA directive. There is only * one limitation: so far, legends in JRobin graphs are always centered (don't * try to specify alignment in the legend string). * * @param sourceName Graph source name. * @param color Filling collor to be used for area plot. * @param legend Legend to be printed on the graph. * @throws RrdException Thrown if invalid graph source name is supplied. */ public void area( String sourceName, Color color, String legend ) throws RrdException { plotDefs.add( new Area(sourceName, color) ); addLegend( legend, color ); } /** * Adds stacked plot to the graph definition, * using the specified color and legend. This method * takes exactly the same parameters as RRDTool's STACK directive. There is only * one limitation: so far, legends in JRobin graphs are always centered (don't * try to specify alignment in the legend string). * * @param sourceName Graph source name. * @param color Collor to be used. * @param legend Legend to be printed on the graph. * @throws RrdException Thrown if invalid graph source name is supplied. */ public void stack( String sourceName, Color color, String legend ) throws RrdException { plotDefs.add( new Stack(sourceName, color) ); addLegend( legend, color ); } /** * Adds comment to the graph definition. Comments will be left, center or right aligned * if the comment ends with <code>@l</code>, <code>@c</code> or <code>@r</code>, * respectively. * @param text Comment * @throws RrdException Thrown in case of JRobin specific error. */ public void comment(String text) throws RrdException { addComment( new Comment(text) ); } /** * <p>Calculate the chosen consolidation function <code>consolFun</code> over * the graph <code>sourceName</code> and prints the result * on the graph using the specified <code>format</code> string.</p> * * <p>In the format string there should be a * <code>@n</code> marker (replace <code>n</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> * * <p>The text printed on the graph will be left, center or right aligned * if the format string ends with <code>@l</code>, <code>@c</code> or <code>@r</code>, * respectively.</p> * * @param sourceName Graph source name * @param consolFun Consolidation function to be used for calculation ("AVERAGE", * "MIN", "MAX" or "LAST") * @param format Format string. For example: "speed is @2 @sbits/sec@c", * "temperature = @0 degrees" * @throws RrdException Thrown in case of JRobin specific error */ public void gprint(String sourceName, String consolFun, String format) throws RrdException { addComment( new Gprint(sourceName, consolFun, format) ); } /** * Sets a background image to use for the graph. * The image can be any of the supported imageio formats, * default <i>.gif, .jpg or .png</i>. * @param fileName Filename of the image to use */ public void setBackground( String fileName ) { File bgFile = new File( fileName ); if ( bgFile.exists() ) this.background = bgFile; } /** * Sets a overlay image to use for the graph. * The image can be any of the supported imageio formats, * default <i>.gif, .jpg or .png</i>. All pixels with the color white * RGB (255, 255, 255) will be treated as transparent. * @param fileName Filename of the image to use */ public void setOverlay( String fileName ) { File ovFile = new File( fileName ); if ( ovFile.exists() ) this.overlay = ovFile; } /** * * @param base */ public void setBaseValue( double base ) { this.baseValue = base; } /** * * @param e */ public void setUnitsExponent( int e ) { this.scaleIndex = (6 - e / 3); // Index in the scale table } /** * Sets value range that will be presented in the graph. If not set, graph will be * autoscaled. * @param lower Lower limit. * @param upper Upper limit. * @param rigid Rigid grid, won't autoscale limits. */ public void setGridRange(double lower, double upper, boolean rigid) { gridRange = new GridRange( lower, upper, rigid ); } // ================================================================ // -- Protected (package) methods // ================================================================ PlotDef[] getPlotDefs() { return (PlotDef[]) plotDefs.toArray( new PlotDef[] {} ); } Comment[] getComments() { return (Comment[]) comments.toArray( new Comment[] {} ); } int getCommentLineCount() { return ( comments.size() > 0 ? commentLines + commentLineShift : 0 ); //return ( comments.size() > 0 ? (commentLines > 0 ? commentLines : 1) : 0 ); } private void addComment( Comment cmt ) { commentLines += cmt.getLineCount(); commentLineShift = (cmt.isCompleteLine() ? 0 : 1); comments.add( cmt ); } private void addLegend( String legend, Color color ) throws RrdException { if ( legend != null ) addComment( new Legend(legend, color) ); } } --- NEW FILE: Gprint.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 jrobin.graph2; import java.util.HashMap; import java.util.regex.Matcher; import java.util.regex.Pattern; import jrobin.core.RrdException; /** * <p>description</p> * * @author Arne Vandamme (arn...@jr...) */ class Gprint extends Comment { 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 String sourceName; private int aggregate; private int numDec = 3; // Show 3 decimal values by default private int strLen = -1; private boolean normalScale = false; private boolean uniformScale = false; Gprint( String sourceName, String consolFunc, String text ) throws RrdException { this.text = text; checkValuePlacement(); // First see if this GPRINT is valid super.parseComment(); this.commentType = Comment.CMT_GPRINT; this.sourceName = sourceName; if ( consolFunc.equalsIgnoreCase("AVERAGE") || consolFunc.equalsIgnoreCase("AVG") ) aggregate = Source.AGG_AVERAGE; else if ( consolFunc.equalsIgnoreCase("MAX") || consolFunc.equalsIgnoreCase("MAXIMUM") ) aggregate = Source.AGG_MAXIMUM; else if ( consolFunc.equalsIgnoreCase("MIN") || consolFunc.equalsIgnoreCase("MINIMUM") ) aggregate = Source.AGG_MINIMUM; else if ( consolFunc.equalsIgnoreCase("LAST") ) aggregate = Source.AGG_LAST; else if ( consolFunc.equalsIgnoreCase("FIRST") ) aggregate = Source.AGG_FIRST; else throw new RrdException( "Invalid consolidation function specified." ); } void setValue( Source[] sources, HashMap sourceIndex, ValueFormatter vFormat ) throws RrdException { try { double value = sources[ ((Integer) sourceIndex.get(sourceName)).intValue() ].getAggregate( aggregate ); vFormat.setFormat( value, numDec, strLen ); vFormat.setScaling( normalScale, uniformScale ); String valueStr = vFormat.getFormattedValue(); String prefix = vFormat.getPrefix(); // Replace all values for (int i = 0; i < oList.size(); i += 2 ) { String str = (String) oList.elementAt(i); str = str.replaceAll(VALUE_MARKER, valueStr); if ( normalScale ) str = str.replaceAll(SCALE_MARKER, prefix); if ( uniformScale ) str = str.replaceAll(UNIFORM_SCALE_MARKER, prefix); oList.set( i, str ); } } catch (Exception e) { throw new RrdException( "Could not find datasource: " + sourceName ); } } /** * Check value placement by finding placeholder. * Check for uniform or regular scaling. * Check for the number of decimals and the complete value string length. * @throws RrdException */ protected void checkValuePlacement() 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: RrdGraph.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 jrobin.graph2; import javax.swing.JPanel; import java.util.ArrayList; import java.io.File; import java.io.IOException; import java.io.Serializable; import javax.imageio.ImageIO; import java.awt.image.RenderedImage; import java.awt.image.BufferedImage; import jrobin.core.RrdDb; import jrobin.core.Util; import jrobin.core.RrdException; /** * <p>Class to represent JRobin graphs. This class needs an appropriate RrdGraphDef to generate graphs.</p> * * @author Arne Vandamme (arn...@jr...) * @author Sasa Markovic (sa...@jr...) */ public class RrdGraph implements Serializable { // ================================================================ // -- Members // ================================================================ private static int DEFAULT_POOLSIZE = 15; private Grapher grapher; private BufferedImage img; private ArrayList rrdDbPool; private int maxPoolSize = DEFAULT_POOLSIZE; // ================================================================ // -- Constructors // ================================================================ /** * Constructs a new JRobin graph object. */ public RrdGraph() { this( DEFAULT_POOLSIZE ); } /** * Constructs a new JRobin graph object. * @param poolSize Maximum number of concurrent open rrd files in the RrdGraph object. */ public RrdGraph( int poolSize ) { maxPoolSize = poolSize; rrdDbPool = new ArrayList( poolSize ); } /** * Constructs a new JRobin graph object from the supplied definition. * @param graphDef Graph definition. * @throws IOException Thrown in case of I/O error. * @throws RrdException Thrown in case of JRobin specific error. */ public RrdGraph( RrdGraphDef graphDef ) throws IOException, RrdException { this( graphDef, DEFAULT_POOLSIZE ); } /** * Constructs a new JRobin graph from the supplied definition. * @param graphDef Graph definition. * @param poolSize Maximum number of concurrent open rrd files in the RrdGraph object. * @throws IOException Thrown in case of I/O error. * @throws RrdException Thrown in case of JRobin specific error. */ public RrdGraph( RrdGraphDef graphDef, int poolSize ) throws IOException, RrdException { maxPoolSize = poolSize; rrdDbPool = new ArrayList( poolSize ); grapher = new Grapher( graphDef, this ); } // ================================================================ // -- Public mehods // ================================================================ /** * Sets the graph definition to use for the graph construction. * @param graphDef Graph definition. */ public void setGraphDef( RrdGraphDef graphDef ) { img = null; grapher = new Grapher( graphDef, this ); } /** * Creates and saves a graph image with default dimensions as a PNG file. * By default the chart area is 400 by 100 pixels, the size of the entire image is dependant * on number of title/legend/comment lines and some other settings. * @param path Path to the PNG file to be created. * @throws IOException Thrown in case of I/O error. */ public void saveAsPNG( String path ) throws RrdException, IOException { saveAsPNG( path, 0, 0 ); } /** * Creates and saves a graph image with custom chart dimensions as a PNG file. * The resulting size of the entire image is also influenced by many other settings like number of comment lines. * @param path Path to the PNG file to be created. * @param width Width of the chart area in pixels. * @param height Height of the chart area in pixels. * @throws IOException Thrown in case of I/O error. */ public void saveAsPNG( String path, int width, int height ) throws RrdException, IOException { Util.time(); RenderedImage r =(RenderedImage) getBufferedImage(width, height); Util.time(); ImageIO.write( r, "png", new File(path) ); Util.time(5); } /** * Creates and saves a graph image with default dimensions as a JPEG file. * By default the chart area is 400 by 100 pixels, the size of the entire image is dependant * on number of title/legend/comment lines and some other settings. * @param path Path to the JPEG file to be created. * @param quality JPEG quality, between 0 (= low) and 1.0f (= high). * @throws IOException Thrown in case of I/O error. */ public void saveAsJPEG( String path, float quality ) throws IOException { saveAsJPEG( path, 0, 0, quality ); } /** * Creates and saves a graph image with custom chart dimensions as a JPEG file. * The resulting size of the entire image is also influenced by many other settings like number of comment lines. * @param path Path to the JPEG file to be created. * @param width Width of the chart area in pixels. * @param height Height of the chart area in pixels. * @param quality JPEG quality, between 0 (= low) and 1.0f (= high). * @throws IOException Thrown in case of I/O error. */ public void saveAsJPEG( String path, int width, int height, float quality ) throws IOException { System.err.println( "Method not implemented..." ); } /** * Returns graph width default chart dimensions (400 by 100) as an array of PNG bytes. * @param width Width of the chart area in pixels. * @param height Height of the chart area in pixels. * @return Array of PNG bytes. * @throws IOException Thrown in case of I/O error. ... [truncated message content] |
Update of /cvsroot/jrobin/src/jrobin/demo In directory sc8-pr-cvs1:/tmp/cvs-serv2871/src/jrobin/demo Modified Files: JRobinComplexGraph.java JRobinGallery.java Added Files: TimeProfile.java ProfileGraphsOld.java JRobinTimeProfiler.java ProfileGraphsNew.java Log Message: Experimental graph2 package major update, but very unfinished --- NEW FILE: TimeProfile.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 jrobin.demo; /** * <p>description</p> * * @author Arne Vandamme (arn...@jr...) * @author Sasa Markovic (sa...@jr...) */ public class TimeProfile { String name = ""; long[] defCreation = new long[2]; long[][] creation = new long[2][6]; long[] totalCreation = new long[2]; } --- NEW FILE: ProfileGraphsOld.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 jrobin.demo; import java.io.IOException; import java.io.PrintWriter; import java.awt.Color; import java.util.LinkedList; import java.util.GregorianCalendar; import java.util.Date; import jrobin.core.RrdException; import jrobin.core.Util; import jrobin.graph.*; /** * <p>description</p> * * @author Arne Vandamme (arn...@jr...) * @author Sasa Markovic (sa...@jr...) */ class ProfileGraphsOld { private final int DNUM = 0; // profiler num, 0 or 1 (1 = new, 0 = old) private int demoNum; private PrintWriter out; private RrdGraph graph; private JRobinTimeProfiler profiler; // Demo sake private GregorianCalendar startDate = new GregorianCalendar(2003, 7, 24, 00, 00); private GregorianCalendar endDate = new GregorianCalendar(2003, 7, 25, 00, 00); private void addTimingInfo( int profileIndex, LinkedList v ) { int i = profileIndex - 1; while ( ! v.isEmpty() ) { String timetag = (String) v.removeFirst(); String[] s = timetag.split("_"); int num = Integer.parseInt(s[0]); long time = Long.parseLong(s[1]); profiler.profiles[i].creation[DNUM][num] = time; } } ProfileGraphsOld( PrintWriter out, JRobinTimeProfiler profiler ) { this.profiler = profiler; this.out = out; long fullStart, fullStop; fullStart = System.currentTimeMillis(); try { createDemo1(); createDemo2(); createDemo3(); createDemoEx(4); createDemoEx(5); createDemoEx(6); } catch ( Exception e ) { out.println( "\nException occurred: " + e.getMessage() + "\n" ); } fullStop = System.currentTimeMillis(); profiler.oldGraphs = (fullStop - fullStart); //out.println( " Total execution time for graph batch: " + setw( 10, (fullStop - fullStart)) ); } private void createDemo1() throws IOException, RrdException { demoNum = 1; profiler.profiles[demoNum - 1].name = "Simple traffic graph."; long start, stop; // Create Def start = System.currentTimeMillis(); RrdGraphDef def = new RrdGraphDef(); def.setTimePeriod( startDate, endDate ); def.setTitle("ahha"); def.datasource("in2", "/test.rrd", "ifInOctets", "AVERAGE"); def.datasource("out2", "/test.rrd", "ifOutOctets", "AVERAGE"); def.datasource("in", "in2,8,*"); def.datasource("out", "out2,8,*"); def.area("in", Color.RED, "Incoming traffic"); def.gprint("in", "AVERAGE", "(average: @5.2 @sbit/s)\n"); def.line("out", Color.BLUE, "Outgoing traffic"); def.gprint("out", "AVERAGE", "(average: @6.2 @sbit/s)"); stop = System.currentTimeMillis(); profiler.profiles[demoNum - 1].defCreation[DNUM] = (stop - start); // Create graph graph = new RrdGraph( def ); graph.saveAsPNG( "/time_demo" + demoNum + "-" + DNUM + ".png", 0, 0 ); // Default size stop = System.currentTimeMillis(); profiler.profiles[demoNum - 1].totalCreation[DNUM] = (stop - start); addTimingInfo( demoNum, Util.timeList ); } private void createDemo2() throws IOException, RrdException { demoNum = 2; profiler.profiles[demoNum - 1].name = "Rainbow graph."; long start, stop; // Create Def start = System.currentTimeMillis(); // ============================================================== RrdGraphDef def = new RrdGraphDef(); GregorianCalendar sd = new GregorianCalendar(2003, 4, 1); GregorianCalendar ed = new GregorianCalendar(2003, 5, 1); def.setTimePeriod(sd, ed); long t0 = sd.getTime().getTime() / 1000L; long t1 = ed.getTime().getTime() / 1000L; def.datasource("sine", "TIME," + t0 + ",-," + (t1 - t0) + ",/,7,PI,*,*,SIN"); def.datasource("v2", "/gallery.rrd", "shade", "AVERAGE"); def.datasource("cosine", "TIME," + t0 + ",-," + (t1 - t0) + ",/,3,PI,*,*,COS"); def.datasource("line", "TIME," + t0 + ",-," + (t1 - t0) + ",/,1000,*"); def.datasource("v1", "sine,line,*,ABS"); int n = 40; for(int i = 0; i < n; i++) { long t = t0 + (t1 - t0) * i / n; def.datasource("c" + i, "TIME," + t + ",GT,v2,UNKN,IF"); } for(int i = 0; i < n; i++) { if(i==0) { def.area("c"+i, new Color(255-255*Math.abs(i-n/2)/(n/2),0,0), "Output by night"); } else if(i==n/2) { def.area("c"+i, new Color(255-255*Math.abs(i-n/2)/(n/2),0,0), "Output by day"); } else { def.area("c"+i, new Color(255-255*Math.abs(i-n/2)/(n/2),0,0), null); } } def.line("v2", Color.YELLOW, null); def.line("v1", Color.BLUE, "Input voltage@L", 3); def.line("v1", Color.YELLOW, null, 1); def.setTitle("Voltage measurement"); //def.setVerticalLabel("[Volts]"); def.setValueAxisLabel("[Volts]"); def.comment("fancy looking graphs@r"); //def.setValueStep(100); // ============================================================== stop = System.currentTimeMillis(); profiler.profiles[demoNum - 1].defCreation[DNUM] = (stop - start); // Create graph graph = new RrdGraph( def ); graph.saveAsPNG( "/time_demo" + demoNum + "-" + DNUM + ".png", 400, 250 ); // Default size stop = System.currentTimeMillis(); profiler.profiles[demoNum - 1].totalCreation[DNUM] = (stop - start); addTimingInfo( demoNum, Util.timeList ); } private void createDemo3() throws IOException, RrdException { demoNum = 3; profiler.profiles[demoNum - 1].name = "Customized complex graph."; long start, stop; // Create Def start = System.currentTimeMillis(); // ============================================================== RrdGraphDef def = new RrdGraphDef(); def.setTimePeriod( startDate, endDate ); //gl.setTitleFont( new Font("Lucida Sans Typewriter", Font.PLAIN, 10) ); def.setTitle( "+------------------------------------------------------------------+@c" + "| Server load...@Land@C...CPU usage |@r" + "+------------------------------------------------------------------+@c" ); //gl.setVerticalLabel("server load"); def.setValueAxisLabel("server load"); def.setBackColor( Color.DARK_GRAY ); def.setCanvasColor( Color.LIGHT_GRAY ); def.setImageBorder( Color.BLACK, 1 ); //gl.setDefaultFontColor( Color.WHITE ); //gl.setTitleFontColor( Color.GREEN ); def.setMajorGridColor(Color.YELLOW); def.setMinorGridColor( new Color( 130, 30, 30) ); def.setFrameColor( Color.BLACK ); def.setAxisColor( Color.RED ); def.setArrowColor( Color.GREEN ); //gl.setGridX( false ); //gl.setGridY( false ); //gl.setFrontGrid(false); def.setShowLegend(true); //gl.setUnitsExponent(3); //gl.setAntiAliasing(false); //gl.setGridRange( 0, 1, false ); def.setValueRange( 0, 1 ); def.setRigidGrid( false ); def.setFontColor( Color.WHITE ); def.datasource("load", "c:/test.rrd", "serverLoad", "AVERAGE"); def.datasource("user", "c:/test.rrd", "serverCPUUser", "AVERAGE"); def.datasource("nice", "c:/test.rrd", "serverCPUNice", "AVERAGE"); def.datasource("system", "c:/test.rrd", "serverCPUSystem", "AVERAGE"); def.datasource("idle", "c:/test.rrd", "serverCPUIdle", "AVERAGE"); def.datasource("total", "user,nice,+,system,+,idle,+"); def.datasource("busy", "user,nice,+,system,+,total,/,100,*"); def.datasource("p25t50", "busy,25,GT,busy,50,LE,load,0,IF,0,IF"); def.datasource("p50t75", "busy,50,GT,busy,75,LE,load,0,IF,0,IF"); def.datasource("p75t90", "busy,75,GT,busy,90,LE,load,0,IF,0,IF"); def.datasource("p90t100", "busy,90,GT,load,0,IF"); def.comment("CPU utilization (%)\n"); def.comment(" "); //gl.hrule( 7.0, Color.YELLOW, null, 10f); def.area("load", new Color(0x66,0x99,0xcc), " 0 - 25%"); def.area("p25t50", new Color(0x00,0x66,0x99), "25 - 50%"); def.comment(" "); def.gprint("busy", "MIN", "Minimum:@5.1@s%"); def.gprint("busy", "MAX", "Maximum: @5.1@S%"); def.comment("\n"); def.comment(" "); def.area("p50t75", new Color(0x66,0x66,0x00), "50 - 75%"); def.area("p75t90", new Color(0xff,0x66,0x00), "75 - 90%"); def.area("p90t100", new Color(0xcc,0x33,0x00), "90 - 100%"); //gDef.rule(10.0, Color.ORANGE, null); def.gprint("busy", "AVERAGE", " Average:@5.1@s%"); def.gprint("busy", "LAST", "Current: @5.1@s%"); def.comment("\n"); def.comment("\n"); def.comment("Server load\n"); def.comment(" "); def.line("load", new Color(0x00,0x00,0x00), "Load average (5 min)" ); //gDef.area("load", Color.RED, " hmm \n"); //gl.stack("p75t90", Color.GREEN, " hmm"); def.comment(" "); def.gprint("load", "MIN", " Minimum: @5.2@s"); def.gprint("load", "MAX", "Maximum: @6.2@s"); def.comment("\n"); def.comment(" "); def.comment(" "); def.gprint("load", "AVERAGE", "Average: @5.2@s"); def.gprint("load", "LAST", "Current: @6.2@s\n"); def.comment("\n"); def.comment("-------------------------------------------------------------------------------@c"); //gl.vrule( new GregorianCalendar(2003, 7, 24, 9, 00), Color.BLUE, "9am", 2f ); //gl.vrule( new GregorianCalendar(2003, 7, 24, 17, 00), Color.BLUE, "5pm", 3f ); def.comment("Generated: " + new Date() + "@R"); // ============================================================== stop = System.currentTimeMillis(); profiler.profiles[demoNum - 1].defCreation[DNUM] = (stop - start); // Create graph graph = new RrdGraph( def ); graph.saveAsPNG( "/time_demo" + demoNum + "-" + DNUM + ".png", 0, 0 ); // Default size stop = System.currentTimeMillis(); profiler.profiles[demoNum - 1].totalCreation[DNUM] = (stop - start); addTimingInfo( demoNum, Util.timeList ); } private void createDemoEx( int demoNum ) throws IOException, RrdException { profiler.profiles[demoNum - 1].name = "Complex graph (3 RRD files)."; long start, stop; // Create Def start = System.currentTimeMillis(); // ============================================================== RrdGraphDef def = new RrdGraphDef(); def.setTimePeriod( startDate, endDate ); def.setTitle( "+------------------------------------------------------------------+@c" + "| Server load...@Land@C...CPU usage |@r" + "+------------------------------------------------------------------+@c" ); def.setValueAxisLabel("server load"); def.setAntiAliasing(false); def.datasource("load", "c:/test.rrd", "serverLoad", "AVERAGE"); def.datasource("user", "c:/test.rrd", "serverCPUUser", "AVERAGE"); def.datasource("nice", "c:/test1.rrd", "serverCPUNice", "AVERAGE"); def.datasource("system", "c:/test1.rrd", "serverCPUSystem", "AVERAGE"); def.datasource("idle", "c:/test2.rrd", "serverCPUIdle", "AVERAGE"); def.datasource("total", "user,nice,+,system,+,idle,+"); def.datasource("busy", "user,nice,+,system,+,total,/,100,*"); def.datasource("p25t50", "busy,25,GT,busy,50,LE,load,0,IF,0,IF"); def.datasource("p50t75", "busy,50,GT,busy,75,LE,load,0,IF,0,IF"); def.datasource("p75t90", "busy,75,GT,busy,90,LE,load,0,IF,0,IF"); def.datasource("p90t100", "busy,90,GT,load,0,IF"); def.comment("CPU utilization (%)\n"); def.comment(" "); //gl.hrule( 7.0, Color.YELLOW, null, 10f); def.area("load", new Color(0x66,0x99,0xcc), " 0 - 25%"); def.area("p25t50", new Color(0x00,0x66,0x99), "25 - 50%"); def.comment(" "); def.gprint("busy", "MIN", "Minimum:@5.1@s%"); def.gprint("busy", "MAX", "Maximum: @5.1@S%"); def.comment("\n"); def.comment(" "); def.area("p50t75", new Color(0x66,0x66,0x00), "50 - 75%"); def.area("p75t90", new Color(0xff,0x66,0x00), "75 - 90%"); def.area("p90t100", new Color(0xcc,0x33,0x00), "90 - 100%"); //gDef.rule(10.0, Color.ORANGE, null); def.gprint("busy", "AVERAGE", " Average:@5.1@s%"); def.gprint("busy", "LAST", "Current: @5.1@s%"); def.comment("\n"); def.comment("\n"); def.comment("Server load\n"); def.comment(" "); def.line("load", new Color(0x00,0x00,0x00), "Load average (5 min)" ); //gDef.area("load", Color.RED, " hmm \n"); //gl.stack("p75t90", Color.GREEN, " hmm"); def.comment(" "); def.gprint("load", "MIN", " Minimum: @5.2@s"); def.gprint("load", "MAX", "Maximum: @6.2@s"); def.comment("\n"); def.comment(" "); def.comment(" "); def.gprint("load", "AVERAGE", "Average: @5.2@s"); def.gprint("load", "LAST", "Current: @6.2@s\n"); def.comment("\n"); def.comment("-------------------------------------------------------------------------------@c"); //gl.vrule( new GregorianCalendar(2003, 7, 24, 9, 00), Color.BLUE, "9am", 2f ); //gl.vrule( new GregorianCalendar(2003, 7, 24, 17, 00), Color.BLUE, "5pm", 3f ); def.comment("Generated: " + new Date() + "@R"); // ============================================================== stop = System.currentTimeMillis(); profiler.profiles[demoNum - 1].defCreation[DNUM] = (stop - start); // Create graph graph = new RrdGraph( def ); graph.saveAsPNG( "/time_demo" + demoNum + "-" + DNUM + ".png", 0, 0 ); // Default size stop = System.currentTimeMillis(); profiler.profiles[demoNum - 1].totalCreation[DNUM] = (stop - start); addTimingInfo( demoNum, Util.timeList ); } } --- NEW FILE: JRobinTimeProfiler.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 jrobin.demo; import java.io.*; /** * <p>This class is used for time/performance profiling of the 'old' and 'new' JRobin graphing packages.</p> * * @author Arne Vandamme (arn...@jr...) * @author Sasa Markovic (sa...@jr...) */ public class JRobinTimeProfiler { private static int NUM_DEMOS = 6; TimeProfile[] profiles; long oldGraphs, newGraphs; String[] steps = new String[] { "Prepare", "CalculateSeries", "PlotImageBackground", "PlotChart", "PlotComments", "ImageSave", "", "" }; JRobinTimeProfiler( PrintWriter out ) { profiles = new TimeProfile[NUM_DEMOS]; for (int i = 0; i < profiles.length; i++) profiles[i] = new TimeProfile(); new ProfileGraphsOld( out, this ); new ProfileGraphsNew( out, this ); long proc; for (int i = 0; i < profiles.length; i++) { TimeProfile p = profiles[i]; out.println("\n DEMO " + (i + 1) + ": " + p.name + "\n-----------------------------------------------------"); // Graph def creation times proc = ( p.defCreation[0] > 0 ? ((p.defCreation[0] - p.defCreation[1]) * 100 / p.defCreation[0]) : 0); out.println( setwr(25, " 0 - RrdGraphDef creation") + setw(10, p.defCreation[0]) + setw(15, p.defCreation[1]) + setw(10, proc + "%") + "\n" ); // Step creation times for (int j = 0; j < p.creation[0].length; j++) { proc = ( p.creation[0][j] > 0 ? ((p.creation[0][j] - p.creation[1][j]) * 100 / p.creation[0][j]) : 0); out.println( setw(2, "" + (j + 1)) + " - " + setwr(20, steps[j]) + setw(10, p.creation[0][j]) + setw(15, p.creation[1][j]) + setw(10, proc + "%") ); } // Total creation time proc = ( p.totalCreation[0] > 0 ? ((p.totalCreation[0] - p.totalCreation[1]) * 100 / p.totalCreation[0]) : 0); out.println( "\n" + setwr(25, " Total time:") + setw(10, p.totalCreation[0]) + setw(15, p.totalCreation[1]) + setw(10, proc + "%") + "\n" ); } proc = ( oldGraphs > 0 ? ((oldGraphs - newGraphs) * 100 / oldGraphs) : 0); out.println( setwr(25, " Total batch time:") + setw(10, oldGraphs) + setw(15, newGraphs) + setw(10, proc + "%") + "\n" ); out.println("\n\n"); } private String setwr( int num, String str ) { int diff = num - str.length(); StringBuffer prefix = new StringBuffer(""); for (int i = 0; i < diff; i++) prefix.append(' '); return str + prefix.toString(); } private String setw( int num, String str ) { int diff = num - str.length(); StringBuffer prefix = new StringBuffer(""); for (int i = 0; i < diff; i++) prefix.append(' '); return prefix.append(str).toString(); } private String setw( int num, long val ) { return setw(num, "" + val); } public static void main( String[] args ) { PrintWriter out = new PrintWriter( System.out ); new JRobinTimeProfiler( out ); out.close(); } } --- NEW FILE: ProfileGraphsNew.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 jrobin.demo; import java.io.IOException; import java.io.PrintWriter; import java.awt.Color; import java.util.Date; import java.util.LinkedList; import java.util.GregorianCalendar; import jrobin.core.RrdException; import jrobin.core.Util; import jrobin.graph2.*; /** * <p>description</p> * * @author Arne Vandamme (arn...@jr...) * @author Sasa Markovic (sa...@jr...) */ public class ProfileGraphsNew { private final int DNUM = 1; // profiler num, 0 or 1 (1 = new, 0 = old) private int demoNum; private PrintWriter out; private RrdGraph graph; private JRobinTimeProfiler profiler; // Demo sake private GregorianCalendar startDate = new GregorianCalendar(2003, 7, 24, 00, 00); private GregorianCalendar endDate = new GregorianCalendar(2003, 7, 25, 00, 00); private void addTimingInfo( int profileIndex, LinkedList v ) { int i = profileIndex - 1; while ( ! v.isEmpty() ) { String timetag = (String) v.removeFirst(); String[] s = timetag.split("_"); int num = Integer.parseInt(s[0]); long time = Long.parseLong(s[1]); profiler.profiles[i].creation[DNUM][num] = time; } } ProfileGraphsNew( PrintWriter out, JRobinTimeProfiler profiler ) { this.profiler = profiler; this.out = out; long fullStart, fullStop; fullStart = System.currentTimeMillis(); try { graph = new RrdGraph(); // Default rrddb pool size createDemo1(); createDemo2(); createDemo3(); createDemoEx(4); createDemoEx(5); createDemoEx(6); graph.closeFiles(); } catch ( Exception e ) { out.println( "\nException occurred: " + e.getMessage() + "\n" ); } fullStop = System.currentTimeMillis(); profiler.newGraphs = (fullStop - fullStart); //out.println( " Total execution time for graph batch: " + setw( 10, (fullStop - fullStart)) ); } private void createDemo1() throws IOException, RrdException { demoNum = 1; long start, stop; // Create Def start = System.currentTimeMillis(); RrdGraphDef def = new RrdGraphDef(); def.setTimePeriod( startDate, endDate ); def.setTitle("ahha"); def.datasource("in2", "/test.rrd", "ifInOctets", "AVERAGE"); def.datasource("out2", "/test.rrd", "ifOutOctets", "AVERAGE"); def.datasource("in", "in2,8,*"); def.datasource("out", "out2,8,*"); def.area("in", Color.RED, "Incoming traffic"); def.gprint("in", "AVERAGE", "(average: @5.2 @sbit/s)\n"); def.line("out", Color.BLUE, "Outgoing traffic"); def.gprint("out", "AVERAGE", "(average: @6.2 @sbit/s)"); stop = System.currentTimeMillis(); profiler.profiles[demoNum - 1].defCreation[DNUM] = (stop - start); // Create graph graph.setGraphDef(def); graph.saveAsPNG( "/time_demo1-" + DNUM + ".png" ); // Default size stop = System.currentTimeMillis(); profiler.profiles[demoNum - 1].totalCreation[DNUM] = (stop - start); addTimingInfo( 1, Util.timeList ); } private void createDemo2() throws IOException, RrdException { demoNum = 2; long start, stop; // Create Def start = System.currentTimeMillis(); // ============================================================== RrdGraphDef def = new RrdGraphDef(); GregorianCalendar sd = new GregorianCalendar(2003, 4, 1); GregorianCalendar ed = new GregorianCalendar(2003, 5, 1); def.setTimePeriod(sd, ed); long t0 = sd.getTime().getTime() / 1000L; long t1 = ed.getTime().getTime() / 1000L; def.datasource("sine", "TIME," + t0 + ",-," + (t1 - t0) + ",/,7,PI,*,*,SIN"); def.datasource("v2", "/gallery.rrd", "shade", "AVERAGE"); def.datasource("cosine", "TIME," + t0 + ",-," + (t1 - t0) + ",/,3,PI,*,*,COS"); def.datasource("line", "TIME," + t0 + ",-," + (t1 - t0) + ",/,1000,*"); def.datasource("v1", "sine,line,*,ABS"); int n = 40; for(int i = 0; i < n; i++) { long t = t0 + (t1 - t0) * i / n; def.datasource("c" + i, "TIME," + t + ",GT,v2,UNKN,IF"); } for(int i = 0; i < n; i++) { if(i==0) { def.area("c"+i, new Color(255-255*Math.abs(i-n/2)/(n/2),0,0), "Output by night"); } else if(i==n/2) { def.area("c"+i, new Color(255-255*Math.abs(i-n/2)/(n/2),0,0), "Output by day"); } else { def.area("c"+i, new Color(255-255*Math.abs(i-n/2)/(n/2),0,0), null); } } def.line("v2", Color.YELLOW, null); def.line("v1", Color.BLUE, "Input voltage@L", 3); def.line("v1", Color.YELLOW, null, 1); def.setTitle("Voltage measurement"); def.setVerticalLabel("[Volts]"); //def.setValueAxisLabel("[Volts]"); def.comment("fancy looking graphs@r"); //def.setValueStep(100); // ============================================================== stop = System.currentTimeMillis(); profiler.profiles[demoNum - 1].defCreation[DNUM] = (stop - start); // Create graph graph.setGraphDef(def); graph.saveAsPNG( "/time_demo" + demoNum + "-" + DNUM + ".png", 400, 250 ); // Default size stop = System.currentTimeMillis(); profiler.profiles[demoNum - 1].totalCreation[DNUM] = (stop - start); addTimingInfo( demoNum, Util.timeList ); } private void createDemo3() throws IOException, RrdException { demoNum = 3; profiler.profiles[demoNum - 1].name = "Customized complex graph."; long start, stop; // Create Def start = System.currentTimeMillis(); // ============================================================== RrdGraphDef def = new RrdGraphDef(); def.setTimePeriod( startDate, endDate ); //gl.setTitleFont( new Font("Lucida Sans Typewriter", Font.PLAIN, 10) ); def.setTitle( "+------------------------------------------------------------------+@c" + "| Server load...@Land@C...CPU usage |@r" + "+------------------------------------------------------------------+@c" ); def.setVerticalLabel("server load"); //def.setValueAxisLabel("server load"); def.setBackColor( Color.DARK_GRAY ); def.setCanvasColor( Color.LIGHT_GRAY ); def.setImageBorder( Color.BLACK, 1 ); //gl.setDefaultFontColor( Color.WHITE ); //gl.setTitleFontColor( Color.GREEN ); def.setMajorGridColor(Color.YELLOW); def.setMinorGridColor( new Color( 130, 30, 30) ); def.setFrameColor( Color.BLACK ); def.setAxisColor( Color.RED ); def.setArrowColor( Color.GREEN ); //gl.setGridX( false ); //gl.setGridY( false ); //gl.setFrontGrid(false); def.setShowLegend(true); //gl.setUnitsExponent(3); //gl.setAntiAliasing(false); def.setGridRange( 0, 1, false ); //def.setValueRange( 0, 1 ); //def.setRigidGrid( false ); def.setDefaultFontColor( Color.WHITE ); def.setTitleFontColor( Color.WHITE ); def.datasource("load", "c:/test.rrd", "serverLoad", "AVERAGE"); def.datasource("user", "c:/test.rrd", "serverCPUUser", "AVERAGE"); def.datasource("nice", "c:/test.rrd", "serverCPUNice", "AVERAGE"); def.datasource("system", "c:/test.rrd", "serverCPUSystem", "AVERAGE"); def.datasource("idle", "c:/test.rrd", "serverCPUIdle", "AVERAGE"); def.datasource("total", "user,nice,+,system,+,idle,+"); def.datasource("busy", "user,nice,+,system,+,total,/,100,*"); def.datasource("p25t50", "busy,25,GT,busy,50,LE,load,0,IF,0,IF"); def.datasource("p50t75", "busy,50,GT,busy,75,LE,load,0,IF,0,IF"); def.datasource("p75t90", "busy,75,GT,busy,90,LE,load,0,IF,0,IF"); def.datasource("p90t100", "busy,90,GT,load,0,IF"); def.comment("CPU utilization (%)\n"); def.comment(" "); //gl.hrule( 7.0, Color.YELLOW, null, 10f); def.area("load", new Color(0x66,0x99,0xcc), " 0 - 25%"); def.area("p25t50", new Color(0x00,0x66,0x99), "25 - 50%"); def.comment(" "); def.gprint("busy", "MIN", "Minimum:@5.1@s%"); def.gprint("busy", "MAX", "Maximum: @5.1@S%"); def.comment("\n"); def.comment(" "); def.area("p50t75", new Color(0x66,0x66,0x00), "50 - 75%"); def.area("p75t90", new Color(0xff,0x66,0x00), "75 - 90%"); def.area("p90t100", new Color(0xcc,0x33,0x00), "90 - 100%"); //gDef.rule(10.0, Color.ORANGE, null); def.gprint("busy", "AVERAGE", " Average:@5.1@s%"); def.gprint("busy", "LAST", "Current: @5.1@s%"); def.comment("\n"); def.comment("\n"); def.comment("Server load\n"); def.comment(" "); def.line("load", new Color(0x00,0x00,0x00), "Load average (5 min)" ); //gDef.area("load", Color.RED, " hmm \n"); //gl.stack("p75t90", Color.GREEN, " hmm"); def.comment(" "); def.gprint("load", "MIN", " Minimum: @5.2@s"); def.gprint("load", "MAX", "Maximum: @6.2@s"); def.comment("\n"); def.comment(" "); def.comment(" "); def.gprint("load", "AVERAGE", "Average: @5.2@s"); def.gprint("load", "LAST", "Current: @6.2@s\n"); def.comment("\n"); def.comment("-------------------------------------------------------------------------------@c"); //gl.vrule( new GregorianCalendar(2003, 7, 24, 9, 00), Color.BLUE, "9am", 2f ); //gl.vrule( new GregorianCalendar(2003, 7, 24, 17, 00), Color.BLUE, "5pm", 3f ); def.comment("Generated: " + new Date() + "@R"); // ============================================================== stop = System.currentTimeMillis(); profiler.profiles[demoNum - 1].defCreation[DNUM] = (stop - start); // Create graph graph.setGraphDef(def); graph.saveAsPNG( "/time_demo" + demoNum + "-" + DNUM + ".png" ); // Default size stop = System.currentTimeMillis(); profiler.profiles[demoNum - 1].totalCreation[DNUM] = (stop - start); addTimingInfo( demoNum, Util.timeList ); } private void createDemoEx( int demoNum ) throws IOException, RrdException { long start, stop; // Create Def start = System.currentTimeMillis(); // ============================================================== RrdGraphDef def = new RrdGraphDef(); def.setTimePeriod( startDate, endDate ); def.setTitle( "+------------------------------------------------------------------+@c" + "| Server load...@Land@C...CPU usage |@r" + "+------------------------------------------------------------------+@c" ); def.setVerticalLabel("server load"); def.setAntiAliasing(false); def.datasource("load", "c:/test.rrd", "serverLoad", "AVERAGE"); def.datasource("user", "c:/test.rrd", "serverCPUUser", "AVERAGE"); def.datasource("nice", "c:/test1.rrd", "serverCPUNice", "AVERAGE"); def.datasource("system", "c:/test1.rrd", "serverCPUSystem", "AVERAGE"); def.datasource("idle", "c:/test2.rrd", "serverCPUIdle", "AVERAGE"); def.datasource("total", "user,nice,+,system,+,idle,+"); def.datasource("busy", "user,nice,+,system,+,total,/,100,*"); def.datasource("p25t50", "busy,25,GT,busy,50,LE,load,0,IF,0,IF"); def.datasource("p50t75", "busy,50,GT,busy,75,LE,load,0,IF,0,IF"); def.datasource("p75t90", "busy,75,GT,busy,90,LE,load,0,IF,0,IF"); def.datasource("p90t100", "busy,90,GT,load,0,IF"); def.comment("CPU utilization (%)\n"); def.comment(" "); //gl.hrule( 7.0, Color.YELLOW, null, 10f); def.area("load", new Color(0x66,0x99,0xcc), " 0 - 25%"); def.area("p25t50", new Color(0x00,0x66,0x99), "25 - 50%"); def.comment(" "); def.gprint("busy", "MIN", "Minimum:@5.1@s%"); def.gprint("busy", "MAX", "Maximum: @5.1@S%"); def.comment("\n"); def.comment(" "); def.area("p50t75", new Color(0x66,0x66,0x00), "50 - 75%"); def.area("p75t90", new Color(0xff,0x66,0x00), "75 - 90%"); def.area("p90t100", new Color(0xcc,0x33,0x00), "90 - 100%"); //gDef.rule(10.0, Color.ORANGE, null); def.gprint("busy", "AVERAGE", " Average:@5.1@s%"); def.gprint("busy", "LAST", "Current: @5.1@s%"); def.comment("\n"); def.comment("\n"); def.comment("Server load\n"); def.comment(" "); def.line("load", new Color(0x00,0x00,0x00), "Load average (5 min)" ); //gDef.area("load", Color.RED, " hmm \n"); //gl.stack("p75t90", Color.GREEN, " hmm"); def.comment(" "); def.gprint("load", "MIN", " Minimum: @5.2@s"); def.gprint("load", "MAX", "Maximum: @6.2@s"); def.comment("\n"); def.comment(" "); def.comment(" "); def.gprint("load", "AVERAGE", "Average: @5.2@s"); def.gprint("load", "LAST", "Current: @6.2@s\n"); def.comment("\n"); def.comment("-------------------------------------------------------------------------------@c"); //gl.vrule( new GregorianCalendar(2003, 7, 24, 9, 00), Color.BLUE, "9am", 2f ); //gl.vrule( new GregorianCalendar(2003, 7, 24, 17, 00), Color.BLUE, "5pm", 3f ); def.comment("Generated: " + new Date() + "@R"); // ============================================================== stop = System.currentTimeMillis(); profiler.profiles[demoNum - 1].defCreation[DNUM] = (stop - start); // Create graph graph.setGraphDef(def); graph.saveAsPNG( "/time_demo" + demoNum + "-" + DNUM + ".png" ); // Default size stop = System.currentTimeMillis(); profiler.profiles[demoNum - 1].totalCreation[DNUM] = (stop - start); addTimingInfo( demoNum, Util.timeList ); } } Index: JRobinComplexGraph.java =================================================================== RCS file: /cvsroot/jrobin/src/jrobin/demo/JRobinComplexGraph.java,v retrieving revision 1.9 retrieving revision 1.10 diff -C2 -d -r1.9 -r1.10 *** JRobinComplexGraph.java 17 Oct 2003 14:46:39 -0000 1.9 --- JRobinComplexGraph.java 21 Oct 2003 19:42:00 -0000 1.10 *************** *** 33,36 **** --- 33,37 ---- import jrobin.graph.*; + import jrobin.graph2.RrdGraph; /** *************** *** 44,57 **** public static void main(String[] args) { ! GregorianCalendar start = new GregorianCalendar(2003, 7, 24, 00, 00); GregorianCalendar end = new GregorianCalendar(2003, 7, 25, 00, 00); - RrdGraphDef gDef = new RrdGraphDef(); - try { gDef.setTimePeriod(start, end); ! gDef.setTitle("Server load baseline projection"); ! //gDef.setOverlay("/pkts.png"); gDef.datasource("load", "c:/test.rrd", "serverLoad", "AVERAGE"); gDef.datasource("user", "c:/test.rrd", "serverCPUUser", "AVERAGE"); --- 45,186 ---- public static void main(String[] args) { ! GregorianCalendar start = new GregorianCalendar(2003, 7, 24, 20, 00); GregorianCalendar end = new GregorianCalendar(2003, 7, 25, 00, 00); try { + // -------------------------------------------------------- + + // Create the graphdef to be used + jrobin.graph2.RrdGraphDef gl = new jrobin.graph2.RrdGraphDef(); + gl.setTimePeriod( start, end ); + //gl.setTitleFont( new Font("Lucida Sans Typewriter", Font.PLAIN, 10) ); + gl.setTitle( "+------------------------------------------------------------------+@c" + + "| Server load...@Land@C...CPU usage |@r" + + "+------------------------------------------------------------------+@c" + ); + gl.setVerticalLabel("server load"); + gl.setBackColor( Color.DARK_GRAY ); + gl.setCanvasColor( Color.LIGHT_GRAY ); + gl.setImageBorder( Color.BLACK, 1 ); + gl.setDefaultFontColor( Color.WHITE ); + gl.setTitleFontColor( Color.GREEN ); + gl.setMajorGridColor(Color.YELLOW); + gl.setMinorGridColor( new Color( 130, 30, 30) ); + gl.setFrameColor( Color.BLACK ); + gl.setAxisColor( Color.RED ); + gl.setArrowColor( Color.GREEN ); + //gl.setGridX( false ); + //gl.setGridY( false ); + //gl.setFrontGrid(false); + gl.setShowLegend(true); + //gl.setUnitsExponent(3); + //gl.setAntiAliasing(false); + gl.setGridRange( 0, 1, false ); + + gl.datasource("load", "c:/test.rrd", "serverLoad", "AVERAGE"); + gl.datasource("user", "c:/test.rrd", "serverCPUUser", "AVERAGE"); + gl.datasource("nice", "c:/test.rrd", "serverCPUNice", "AVERAGE"); + gl.datasource("system", "c:/test.rrd", "serverCPUSystem", "AVERAGE"); + gl.datasource("idle", "c:/test.rrd", "serverCPUIdle", "AVERAGE"); + gl.datasource("total", "user,nice,+,system,+,idle,+"); + gl.datasource("busy", "user,nice,+,system,+,total,/,100,*"); + gl.datasource("p25t50", "busy,25,GT,busy,50,LE,load,0,IF,0,IF"); + gl.datasource("p50t75", "busy,50,GT,busy,75,LE,load,0,IF,0,IF"); + gl.datasource("p75t90", "busy,75,GT,busy,90,LE,load,0,IF,0,IF"); + gl.datasource("p90t100", "busy,90,GT,load,0,IF"); + + gl.comment("CPU utilization (%)\n"); + gl.comment(" "); + //gl.hrule( 7.0, Color.YELLOW, null, 10f); + gl.area("load", new Color(0x66,0x99,0xcc), " 0 - 25%"); + gl.area("p25t50", new Color(0x00,0x66,0x99), "25 - 50%"); + gl.comment(" "); + gl.gprint("busy", "MIN", "Minimum:@5.1@s%"); + gl.gprint("busy", "MAX", "Maximum: @5.1@S%"); + gl.comment("\n"); + gl.comment(" "); + gl.area("p50t75", new Color(0x66,0x66,0x00), "50 - 75%"); + gl.area("p75t90", new Color(0xff,0x66,0x00), "75 - 90%"); + gl.area("p90t100", new Color(0xcc,0x33,0x00), "90 - 100%"); + //gDef.rule(10.0, Color.ORANGE, null); + gl.gprint("busy", "AVERAGE", " Average:@5.1@s%"); + gl.gprint("busy", "LAST", "Current: @5.1@s%"); + gl.comment("\n"); + gl.comment("\n"); + gl.comment("Server load\n"); + gl.comment(" "); + gl.line("load", new Color(0x00,0x00,0x00), "Load average (5 min)" ); + //gDef.area("load", Color.RED, " hmm \n"); + //gl.stack("p75t90", Color.GREEN, " hmm"); + gl.comment(" "); + gl.gprint("load", "MIN", " Minimum: @5.2@s"); + gl.gprint("load", "MAX", "Maximum: @6.2@s"); + gl.comment("\n"); + gl.comment(" "); + gl.comment(" "); + gl.gprint("load", "AVERAGE", "Average: @5.2@s"); + gl.gprint("load", "LAST", "Current: @6.2@s\n"); + gl.comment("\n"); + gl.comment("-------------------------------------------------------------------------------@c"); + //gl.vrule( new GregorianCalendar(2003, 7, 24, 9, 00), Color.BLUE, "9am", 2f ); + //gl.vrule( new GregorianCalendar(2003, 7, 24, 17, 00), Color.BLUE, "5pm", 3f ); + gl.comment("Generated: " + new Date() + "@R"); + + // Create the actual graph + long s1 = Calendar.getInstance().getTimeInMillis(); + jrobin.graph2.RrdGraph gf = new jrobin.graph2.RrdGraph(); + + // Create image as PNG and as JPEG + gf.setGraphDef( gl ); + gf.saveAsPNG( "/demo_graph.png" ); + //gf.saveAsJPEG( "/demo_graph.jpg", 1.0f ); + + + gl = new jrobin.graph2.RrdGraphDef(); + gl.setTimePeriod( start, end ); + gl.setTitle("ahha"); + gl.datasource("in2", "c:/test.rrd", "ifInOctets", "AVERAGE"); + gl.datasource("out2", "c:/test.rrd", "ifOutOctets", "AVERAGE"); + gl.datasource("in", "in2,8,*"); + gl.datasource("out", "out2,8,*"); + gl.area("in", Color.RED, "Incoming traffic"); + gl.gprint("in", "AVERAGE", "(average: @5.2 @sbit/s)\n"); + gl.line("out", Color.BLUE, "Outgoing traffic"); + gl.gprint("out", "AVERAGE", "(average: @6.2 @sbit/s)"); + gf.setGraphDef( gl ); + + gf.saveAsPNG("/demo_graph2.png", 0, 200); + + // Wrap up + gf.closeFiles(); + + // Print out timing information for the new package API + long s2 = Calendar.getInstance().getTimeInMillis(); + System.out.println( "New package: " + (s2 - s1) + " ms" ); + // -------------------------------------------------------- + + + // -------------------------------------------------------- + RrdGraphDef gDef = new RrdGraphDef(); gDef.setTimePeriod(start, end); ! ! gDef.setTitle("Server load\nCPU usage"); ! gDef.setValueAxisLabel("server load"); ! gDef.setBackColor( Color.DARK_GRAY ); ! gDef.setCanvasColor( Color.LIGHT_GRAY ); ! gDef.setImageBorder( Color.BLACK, 1 ); ! gDef.setFontColor( Color.WHITE ); ! gDef.setMajorGridColor(Color.YELLOW); ! gDef.setMinorGridColor( new Color( 130, 30, 30) ); ! gDef.setFrameColor( Color.BLACK ); ! gDef.setAxisColor( Color.RED ); ! gDef.setArrowColor( Color.GREEN ); ! // gDef.setGridX( false ); ! // gDef.setGridY( false ); ! // gDef.setFrontGrid(false); ! gDef.setShowLegend(true); ! // gDef.setAntiAliasing(false); ! gDef.datasource("load", "c:/test.rrd", "serverLoad", "AVERAGE"); gDef.datasource("user", "c:/test.rrd", "serverCPUUser", "AVERAGE"); *************** *** 65,71 **** gDef.datasource("p75t90", "busy,75,GT,busy,90,LE,load,0,IF,0,IF"); gDef.datasource("p90t100", "busy,90,GT,load,0,IF"); gDef.comment("CPU utilization (%)\n"); gDef.comment(" "); ! gDef.hrule( 7.0, Color.YELLOW, null, 10f); gDef.area("load", new Color(0x66,0x99,0xcc), " 0 - 25%"); gDef.area("p25t50", new Color(0x00,0x66,0x99), "25 - 50%"); --- 194,201 ---- gDef.datasource("p75t90", "busy,75,GT,busy,90,LE,load,0,IF,0,IF"); gDef.datasource("p90t100", "busy,90,GT,load,0,IF"); + gDef.comment("CPU utilization (%)\n"); gDef.comment(" "); ! //gDef.hrule( 7.0, Color.YELLOW, null, 10f); gDef.area("load", new Color(0x66,0x99,0xcc), " 0 - 25%"); gDef.area("p25t50", new Color(0x00,0x66,0x99), "25 - 50%"); *************** *** 99,130 **** gDef.comment("\n"); gDef.comment("-------------------------------------------------------------------------------@c"); ! gDef.vrule( new GregorianCalendar(2003, 7, 24, 9, 00), Color.BLUE, "9am", 2f ); ! gDef.vrule( new GregorianCalendar(2003, 7, 24, 17, 00), Color.BLUE, "5pm", 3f ); gDef.comment("Generated: " + new Date() + "@r"); ! gDef.setBackColor( Color.DARK_GRAY ); ! gDef.setCanvasColor( Color.LIGHT_GRAY ); ! gDef.setValueAxisLabel("server load"); ! gDef.setFontColor( Color.WHITE ); ! //gDef.setGridX( false ); ! //gDef.setGridY( false ); ! gDef.setImageBorder( Color.BLACK, 1 ); ! //gDef.setFrontGrid(false); ! gDef.setShowLegend(true); ! gDef.setMajorGridColor(Color.YELLOW); ! gDef.setMinorGridColor( new Color( 130, 30, 30) ); ! gDef.setFrameColor( Color.BLACK ); ! gDef.setAxisColor( Color.RED ); ! gDef.setArrowColor( Color.GREEN ); //gDef.setChartLeftPadding( 40 ); - //gDef.setAntiAliasing(false); //gDef.setTimeAxis( TimeAxisUnit.HOUR, 6, TimeAxisUnit.DAY, 1, "EEEEE dd MMM", true ); //gDef.setValueAxis( 2.5, 5 ); - // Create actual graph - RrdGraph graph = new RrdGraph(gDef); - graph.saveAsPNG("/zzzzzz.png", 0, 0); - graph.saveAsJPEG("/zzzzzz.jpg", 0, 0, 1f); - //System.exit(0); // -- New graph RrdGraphDef gd = new RrdGraphDef(); --- 229,255 ---- gDef.comment("\n"); gDef.comment("-------------------------------------------------------------------------------@c"); ! //gDef.vrule( new GregorianCalendar(2003, 7, 24, 9, 00), Color.BLUE, "9am", 2f ); ! //gDef.vrule( new GregorianCalendar(2003, 7, 24, 17, 00), Color.BLUE, "5pm", 3f ); gDef.comment("Generated: " + new Date() + "@r"); ! ! // Create actual graph ! s1 = Calendar.getInstance().getTimeInMillis(); ! ! jrobin.graph.RrdGraph graph = new jrobin.graph.RrdGraph(gDef); ! graph.saveAsPNG("/zzzzzz.png", 0, 0); ! //graph.saveAsJPEG("/zzzzzz.jpg", 0, 0, 1f); ! ! //gDef.setOverlay("/pkts.png"); ! ! //gDef.setChartLeftPadding( 40 ); //gDef.setTimeAxis( TimeAxisUnit.HOUR, 6, TimeAxisUnit.DAY, 1, "EEEEE dd MMM", true ); //gDef.setValueAxis( 2.5, 5 ); + // -------------------------------------------------------- + + + // -- New graph RrdGraphDef gd = new RrdGraphDef(); *************** *** 141,147 **** gd.gprint("in", "AVERAGE", "Maximum: @6.2@s"); gd.setRigidGrid(true); ! RrdGraph graph2 = new RrdGraph(gd); graph2.saveAsPNG("/traff.png", 0, 0); ////////////////////////////// gd = new RrdGraphDef(); --- 266,281 ---- gd.gprint("in", "AVERAGE", "Maximum: @6.2@s"); gd.setRigidGrid(true); ! jrobin.graph.RrdGraph graph2 = new jrobin.graph.RrdGraph(gd); graph2.saveAsPNG("/traff.png", 0, 0); + + + // Print out timings for the old graph API + s2 = Calendar.getInstance().getTimeInMillis(); + System.out.println( "Old package: " + (s2 - s1) + " ms" ); + + System.exit(0); + + ////////////////////////////// gd = new RrdGraphDef(); *************** *** 155,159 **** gd.line("out", Color.BLUE, null); //gd.setUnitsExponent(6); ! graph2 = new RrdGraph(gd); graph2.saveAsPNG("/pkts.png", 0, 0); --- 289,293 ---- gd.line("out", Color.BLUE, null); //gd.setUnitsExponent(6); ! graph2 = new jrobin.graph.RrdGraph(gd); graph2.saveAsPNG("/pkts.png", 0, 0); *************** *** 164,168 **** gd.area("ftp", Color.BLUE, null); ! graph2 = new RrdGraph(gd); graph2.saveAsPNG("/ftp.png", 0, 0); --- 298,302 ---- gd.area("ftp", Color.BLUE, null); ! graph2 = new jrobin.graph.RrdGraph(gd); graph2.saveAsPNG("/ftp.png", 0, 0); Index: JRobinGallery.java =================================================================== RCS file: /cvsroot/jrobin/src/jrobin/demo/JRobinGallery.java,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** JRobinGallery.java 17 Oct 2003 14:41:47 -0000 1.1 --- JRobinGallery.java 21 Oct 2003 19:42:00 -0000 1.2 *************** *** 1,6 **** package jrobin.demo; ! import jrobin.graph.RrdGraphDef; ! import jrobin.graph.RrdGraph; import jrobin.core.RrdException; --- 1,6 ---- package jrobin.demo; ! import jrobin.graph2.RrdGraphDef; ! import jrobin.graph2.RrdGraph; import jrobin.core.RrdException; *************** *** 26,30 **** def.datasource("sine", "TIME," + t0 + ",-," + (t1 - t0) + ",/,7,PI,*,*,SIN"); ! def.datasource("v2", "demo.rrd", "shade", "AVERAGE"); def.datasource("cosine", "TIME," + t0 + ",-," + (t1 - t0) + ",/,3,PI,*,*,COS"); --- 26,30 ---- def.datasource("sine", "TIME," + t0 + ",-," + (t1 - t0) + ",/,7,PI,*,*,SIN"); ! def.datasource("v2", "/gallery.rrd", "shade", "AVERAGE"); def.datasource("cosine", "TIME," + t0 + ",-," + (t1 - t0) + ",/,3,PI,*,*,COS"); *************** *** 48,59 **** } def.line("v2", Color.YELLOW, null); ! def.line("v1", Color.BLUE, "Input voltage", 3); def.line("v1", Color.YELLOW, null, 1); - def.comment("fancy looking graphs@r"); def.setTitle("Voltage measurement"); ! def.setValueAxisLabel("[Volts]"); ! def.setValueStep(100); RrdGraph graph = new RrdGraph(def); ! graph.saveAsPNG("demo7.png", 400, 250); } --- 48,61 ---- } def.line("v2", Color.YELLOW, null); ! def.line("v1", Color.BLUE, "Input voltage@L", 3); def.line("v1", Color.YELLOW, null, 1); def.setTitle("Voltage measurement"); ! def.setVerticalLabel("[Volts]"); ! //def.setValueAxisLabel("[Volts]"); ! def.comment("fancy looking graphs@r"); ! //def.setValueStep(100); RrdGraph graph = new RrdGraph(def); ! graph.saveAsPNG("/demo7.png", 400, 250); ! //graph.saveAsPNG("/demo7.png"); } *************** *** 77,94 **** def.datasource("blank2", "v1,0,LT,v2,0,LT,AND,v1,v2,MAX,0,IF"); def.datasource("median", "v1,v2,+,2,/"); ! def.line("median", Color.YELLOW, "safe zone\n"); def.area("v1", Color.WHITE, null); ! def.stack("diff", Color.YELLOW, "safe zone"); def.area("blank1", Color.WHITE, null); def.area("blank2", Color.WHITE, null); def.line("v1", Color.BLUE, null, 1); def.line("v2", Color.BLUE, null, 1); - def.gprint("absdiff", "MAX", "max safe: @2V"); - def.gprint("absdiff", "AVERAGE", "avg safe: @2V"); - def.comment("fancy looking graphs@r"); def.setTitle("Voltage measurement"); ! def.setValueAxisLabel("[Volts]"); RrdGraph graph = new RrdGraph(def); ! graph.saveAsPNG("demo6.png", 400, 250); } --- 79,98 ---- def.datasource("blank2", "v1,0,LT,v2,0,LT,AND,v1,v2,MAX,0,IF"); def.datasource("median", "v1,v2,+,2,/"); ! def.line("median", Color.YELLOW, null); def.area("v1", Color.WHITE, null); ! def.stack("diff", Color.YELLOW, "safe zone\n"); def.area("blank1", Color.WHITE, null); def.area("blank2", Color.WHITE, null); def.line("v1", Color.BLUE, null, 1); def.line("v2", Color.BLUE, null, 1); def.setTitle("Voltage measurement"); ! def.setVerticalLabel("[Volts]"); ! //def.setValueAxisLabel("[Volts]"); ! def.gprint("absdiff", "MAX", "max safe: @2V"); ! def.gprint("absdiff", "AVERAGE", "avg safe: @2V@L"); ! def.comment("fancy looking graph@r"); RrdGraph graph = new RrdGraph(def); ! //graph.saveAsPNG("/demo6.png"); ! graph.saveAsPNG("/demo6.png", 400, 250); } |
From: <cob...@us...> - 2003-10-21 19:44:59
|
Update of /cvsroot/jrobin/src/jrobin/core In directory sc8-pr-cvs1:/tmp/cvs-serv2871/src/jrobin/core Modified Files: Util.java Log Message: Experimental graph2 package major update, but very unfinished Index: Util.java =================================================================== RCS file: /cvsroot/jrobin/src/jrobin/core/Util.java,v retrieving revision 1.6 retrieving revision 1.7 diff -C2 -d -r1.6 -r1.7 *** Util.java 21 Oct 2003 14:42:31 -0000 1.6 --- Util.java 21 Oct 2003 19:42:00 -0000 1.7 *************** *** 29,32 **** --- 29,34 ---- import java.util.GregorianCalendar; + import java.util.LinkedList; + /** * Class defines various utility functions used in JRobin. *************** *** 35,38 **** --- 37,45 ---- */ public class Util { + + static long s1 = System.currentTimeMillis(); + static long s2; + public static LinkedList timeList = new LinkedList(); + // pattern RRDTool uses to format doubles in XML files static final String PATTERN = "0.0000000000E00"; *************** *** 166,169 **** --- 173,193 ---- return value; } + + // Arne - timing of methods + public static void time() + { + time(-10); + } + + public static void time( int str ) + { + s2 = System.currentTimeMillis(); + if ( str >= 0 ) + timeList.addLast( str + "_" + (s2 - s1)); + //System.err.println( "[" + str + "] --- " + (s2 - s1) + " ms"); + s1 = s2; + } + } + |
Update of /cvsroot/jrobin/src/jrobin/graph In directory sc8-pr-cvs1:/tmp/cvs-serv2871/src/jrobin/graph Modified Files: RrdGraph.java Def.java PlotDef.java RrdGraphDef.java Grapher.java RrdFile.java Cdef.java Gprint.java Log Message: Experimental graph2 package major update, but very unfinished Index: RrdGraph.java =================================================================== RCS file: /cvsroot/jrobin/src/jrobin/graph/RrdGraph.java,v retrieving revision 1.6 retrieving revision 1.7 diff -C2 -d -r1.6 -r1.7 *** RrdGraph.java 15 Oct 2003 21:19:08 -0000 1.6 --- RrdGraph.java 21 Oct 2003 19:41:59 -0000 1.7 *************** *** 35,38 **** --- 35,40 ---- import java.io.Serializable; + import jrobin.core.Util; + /** * <p>Class to represent JRobin graphs. This class is a light wrapper around *************** *** 57,60 **** --- 59,63 ---- grapher = new Grapher( graphDef ); } + /** *************** *** 94,98 **** public void saveAsPNG(String path, int width, int height) throws IOException { ! ImageIO.write( (RenderedImage) getBufferedImage(width, height), "png", new File(path) ); } --- 97,106 ---- public void saveAsPNG(String path, int width, int height) throws IOException { ! Util.time(); ! RenderedImage r =(RenderedImage) getBufferedImage(width, height); ! Util.time(); ! ImageIO.write( r, "png", new File(path) ); ! Util.time(5); ! } *************** *** 176,180 **** * @param height Image height. * @param quality JPEG quality between 0 and 1. ! * @return Array of PNG bytes. * @throws IOException Thrown in case of I/O error. */ --- 184,188 ---- * @param height Image height. * @param quality JPEG quality between 0 and 1. ! * @return Array of JPEG bytes. * @throws IOException Thrown in case of I/O error. */ Index: Def.java =================================================================== RCS file: /cvsroot/jrobin/src/jrobin/graph/Def.java,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** Def.java 13 Oct 2003 22:53:33 -0000 1.3 --- Def.java 21 Oct 2003 19:41:59 -0000 1.4 *************** *** 73,79 **** --- 73,81 ---- RrdDb rrd = new RrdDb(rrdPath); long rrdStep = rrd.getRrdDef().getStep(); + FetchRequest request = rrd.createFetchRequest(consolFun, start, end + rrdStep); FetchPoint[] fetchPoints = request.fetch(); int numPoints = fetchPoints.length; + DataPoint[] points = new DataPoint[numPoints]; int dsIndex = rrd.getDsIndex(dsName); Index: PlotDef.java =================================================================== RCS file: /cvsroot/jrobin/src/jrobin/graph/PlotDef.java,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** PlotDef.java 15 Oct 2003 21:19:08 -0000 1.4 --- PlotDef.java 21 Oct 2003 19:41:59 -0000 1.5 *************** *** 28,32 **** * */ ! class PlotDef { public static final float DEFAULT_LINE_WIDTH = 1.0F; --- 28,33 ---- * */ ! class PlotDef ! { public static final float DEFAULT_LINE_WIDTH = 1.0F; *************** *** 51,55 **** this.legend = legend; } ! int getType() { return plotType; --- 52,56 ---- this.legend = legend; } ! int getType() { return plotType; Index: RrdGraphDef.java =================================================================== RCS file: /cvsroot/jrobin/src/jrobin/graph/RrdGraphDef.java,v retrieving revision 1.9 retrieving revision 1.10 diff -C2 -d -r1.9 -r1.10 *** RrdGraphDef.java 17 Oct 2003 14:46:39 -0000 1.9 --- RrdGraphDef.java 21 Oct 2003 19:41:59 -0000 1.10 *************** *** 105,109 **** * @author <a href="mailto:sa...@eu...">Sasa Markovic</a> */ ! public class RrdGraphDef { private ArrayList sources = new ArrayList(); --- 105,109 ---- * @author <a href="mailto:sa...@eu...">Sasa Markovic</a> */ ! public class RrdGraphDef implements Serializable { private ArrayList sources = new ArrayList(); *************** *** 208,212 **** * @param title Graph title. */ ! public void setTitle(String title) { this.title = title; } --- 208,212 ---- * @param title Graph title. */ ! public void setTitle(String title) throws RrdException { this.title = title; } Index: Grapher.java =================================================================== RCS file: /cvsroot/jrobin/src/jrobin/graph/Grapher.java,v retrieving revision 1.9 retrieving revision 1.10 diff -C2 -d -r1.9 -r1.10 *** Grapher.java 15 Oct 2003 21:19:08 -0000 1.9 --- Grapher.java 21 Oct 2003 19:41:59 -0000 1.10 *************** *** 106,115 **** BufferedImage createImage( int cWidth, int cHeight ) throws RrdException { - // Print out some information about development version - System.out.println( "\n\nJRobin 1.2 graph package is currently under development." ); - System.out.println( "Graphing functionality is very limited and might fail completely." ); - System.out.println( "-----------------------------------------------------------------" ); - System.out.println( "Trying to create image with chart specs: w=" + cWidth + " h=" + cHeight ); - // Set chart dimensions if not given chartWidth = ( cWidth == 0 ? DEFAULT_WIDTH : cWidth ); --- 106,109 ---- *************** *** 139,146 **** // Create the buffered image, get the graphics handle - System.out.println( "Trying to create image with dimensions: w=" + imgWidth + " h=" + imgHeight ); BufferedImage bImg = new BufferedImage( imgWidth, imgHeight, BufferedImage.TYPE_INT_RGB ); Graphics2D graphics = (Graphics2D) bImg.getGraphics(); ! // Do the actual graphing try --- 133,142 ---- // Create the buffered image, get the graphics handle BufferedImage bImg = new BufferedImage( imgWidth, imgHeight, BufferedImage.TYPE_INT_RGB ); Graphics2D graphics = (Graphics2D) bImg.getGraphics(); ! ! // DEBUG -- Prepare checkpoint ! Util.time(0); ! // Do the actual graphing try *************** *** 167,172 **** } - System.out.println( "Graph created ok." ); - // Dispose context graphics.dispose(); --- 163,166 ---- *************** *** 327,330 **** --- 321,326 ---- private void plotComments( Graphics2D g ) throws RrdException { + Util.time(); + int posy = y_offset + chartHeight + CHART_UPADDING + CHART_BPADDING + font_height; int posx = LBORDER_SPACE; *************** *** 397,400 **** --- 393,398 ---- } + + Util.time(4); } *************** *** 405,408 **** --- 403,408 ---- private void plotChart( Graphics2D graphics ) { + Util.time(); + int lux = x_offset + chart_lpadding; int luy = y_offset + CHART_UPADDING; *************** *** 508,511 **** --- 508,514 ---- if ( graphDef.getFrontGrid() ) plotChartGrid( g, tlist, vlist ); + + // DEBUG -- PlotChart checkpoint + Util.time(3); } *************** *** 589,602 **** private void calculateSeries() throws RrdException, IOException { Source[] sources = graphDef.getSources(); long startTime = graphDef.getStartTime(); long endTime = graphDef.getEndTime(); - long s1, s2, s3; - long t1, t2, t3; - // Optimizing of fetch, reparse - s1 = Calendar.getInstance().getTimeInMillis(); - String[] cfName = new String[] { "AVERAGE", "MAX", "MIN" }; --- 592,602 ---- private void calculateSeries() throws RrdException, IOException { + Util.time(); + Source[] sources = graphDef.getSources(); long startTime = graphDef.getStartTime(); long endTime = graphDef.getEndTime(); // Optimizing of fetch, reparse String[] cfName = new String[] { "AVERAGE", "MAX", "MIN" }; *************** *** 618,623 **** if ( d.cfDataSources[z].size() > 0 ) { - t1 = Calendar.getInstance().getTimeInMillis(); - int[] indices = new int[d.cfDataSources[0].size()]; String[][] names = new String[d.cfDataSources[0].size()][2]; --- 618,621 ---- *************** *** 631,636 **** FetchPoint[] fetchPoints = request.fetch(); - t2 = Calendar.getInstance().getTimeInMillis(); - for(int i = 0; i < sources.length; i++) { for (int j = 0; j < names.length; j++) --- 629,632 ---- *************** *** 639,646 **** } - t3 = Calendar.getInstance().getTimeInMillis(); - - System.err.println( "FETCHING FINISHED: " + (t3 - t1) + " ms (intermediate reached: " + (t2 - t1) +" ms)"); - } } --- 635,638 ---- *************** *** 649,662 **** // ------------------------------------------------------- - /* // ------------------------------------------------------- // Old fetching code ! for(int i = 0; i < sources.length; i++) ! sources[i].setIntervalInternal(startTime, endTime); // ------------------------------------------------------- - */ - - s3 = Calendar.getInstance().getTimeInMillis(); for (int i = 0; i < numPoints; i++) { --- 641,651 ---- // ------------------------------------------------------- // ------------------------------------------------------- // Old fetching code ! //for(int i = 0; i < sources.length; i++) ! // sources[i].setIntervalInternal(startTime, endTime); // ------------------------------------------------------- + for (int i = 0; i < numPoints; i++) { *************** *** 666,673 **** sources[j].getValueInternal(t, valueCollection); } ! ! s2 = Calendar.getInstance().getTimeInMillis(); ! ! System.err.println( "CALCULATING FINISHED: " + (s2 - s1) + " ms (intermediate reached: " + (s3 - s1) +" ms)"); } --- 655,661 ---- sources[j].getValueInternal(t, valueCollection); } ! ! // DEBUG - calculate checkpoint ! Util.time(1); } *************** *** 729,732 **** --- 717,722 ---- private void plotImageBackground( Graphics2D g ) { + Util.time(); + // Background color g.setColor( graphDef.getBackColor() ); *************** *** 768,771 **** --- 758,764 ---- plotImageTitle( g ); plotVerticalAxisLabels( g ); + + // DEBUG -- Image background checkpoint + Util.time(2); } *************** *** 799,802 **** --- 792,798 ---- commentLines++; } + + // DEBUG -- Calculate comment block checkpoint + //Util.time("CalcCommentBlock"); return commentLines * (font_height + LINE_PADDING) - LINE_PADDING; Index: RrdFile.java =================================================================== RCS file: /cvsroot/jrobin/src/jrobin/graph/RrdFile.java,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** RrdFile.java 13 Oct 2003 22:53:33 -0000 1.1 --- RrdFile.java 21 Oct 2003 19:41:59 -0000 1.2 *************** *** 40,44 **** public Vector[] cfDataSources = new Vector[3]; ! public RrdFile() { for (int i = 0; i < cfDataSources.length; i++) --- 40,44 ---- public Vector[] cfDataSources = new Vector[3]; ! public RrdFile( ) { for (int i = 0; i < cfDataSources.length; i++) Index: Cdef.java =================================================================== RCS file: /cvsroot/jrobin/src/jrobin/graph/Cdef.java,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** Cdef.java 4 Sep 2003 13:27:14 -0000 1.1 --- Cdef.java 21 Oct 2003 19:41:59 -0000 1.2 *************** *** 32,36 **** class Cdef extends Source { private String[] rpnTokens; ! Cdef(String name, String rpn) { super(name); --- 32,36 ---- class Cdef extends Source { private String[] rpnTokens; ! Cdef(String name, String rpn) { super(name); Index: Gprint.java =================================================================== RCS file: /cvsroot/jrobin/src/jrobin/graph/Gprint.java,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** Gprint.java 17 Oct 2003 14:46:39 -0000 1.4 --- Gprint.java 21 Oct 2003 19:41:59 -0000 1.5 *************** *** 56,60 **** String prefixStr = " "; String uniformPrefixStr = " "; ! String[] group = m.group(1).split("\\."); int len = -1, numDec = 0; --- 56,60 ---- String prefixStr = " "; String uniformPrefixStr = " "; ! String[] group = m.group(1).split("\\."); int len = -1, numDec = 0; *************** *** 101,104 **** --- 101,105 ---- } } + int diff = len - valueStr.length(); |
From: <cob...@us...> - 2003-10-21 19:43:45
|
Update of /cvsroot/jrobin/src/jrobin/graph2 In directory sc8-pr-cvs1:/tmp/cvs-serv2835/src/jrobin/graph2 Log Message: Directory /cvsroot/jrobin/src/jrobin/graph2 added to the repository |
From: <sa...@us...> - 2003-10-21 17:38:04
|
Update of /cvsroot/jrobin/src/jrobin/inspector In directory sc8-pr-cvs1:/tmp/cvs-serv14516/jrobin/inspector Modified Files: HeaderTableModel.java Log Message: Two nice graphs... Index: HeaderTableModel.java =================================================================== RCS file: /cvsroot/jrobin/src/jrobin/inspector/HeaderTableModel.java,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** HeaderTableModel.java 6 Oct 2003 08:58:08 -0000 1.1 --- HeaderTableModel.java 21 Oct 2003 12:53:05 -0000 1.2 *************** *** 34,38 **** class HeaderTableModel extends AbstractTableModel { private static final Object[] DESCRIPTIONS = {"path", "signature", "step", "last timestamp", ! "datasources", "archives"}; private static final String[] COLUMN_NAMES = {"description", "value"}; --- 34,38 ---- class HeaderTableModel extends AbstractTableModel { private static final Object[] DESCRIPTIONS = {"path", "signature", "step", "last timestamp", ! "datasources", "archives", "size"}; private static final String[] COLUMN_NAMES = {"description", "value"}; *************** *** 81,87 **** String datasources = "" + header.getDsCount(); String archives = "" + header.getArcCount(); rrd.close(); values = new Object[] { ! path, signature, step, lastTimestamp, datasources, archives }; fireTableDataChanged(); --- 81,88 ---- String datasources = "" + header.getDsCount(); String archives = "" + header.getArcCount(); + String size = rrd.getRrdFile().getFileSize() + " bytes"; rrd.close(); values = new Object[] { ! path, signature, step, lastTimestamp, datasources, archives, size }; fireTableDataChanged(); |