KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jrobin > graph > RrdGraphDef


1 /* ============================================================
2  * JRobin : Pure java implementation of RRDTool's functionality
3  * ============================================================
4  *
5  * Project Info: http://www.jrobin.org
6  * Project Lead: Sasa Markovic (saxon@jrobin.org)
7  *
8  * Developers: Sasa Markovic (saxon@jrobin.org)
9  * Arne Vandamme (cobralord@jrobin.org)
10  *
11  * (C) Copyright 2003, by Sasa Markovic.
12  *
13  * This library is free software; you can redistribute it and/or modify it under the terms
14  * of the GNU Lesser General Public License as published by the Free Software Foundation;
15  * either version 2.1 of the License, or (at your option) any later version.
16  *
17  * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
18  * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
19  * See the GNU Lesser General Public License for more details.
20  *
21  * You should have received a copy of the GNU Lesser General Public License along with this
22  * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
23  * Boston, MA 02111-1307, USA.
24  */

25 package org.jrobin.graph;
26
27 import java.io.*;
28 import java.awt.Font JavaDoc;
29 import java.awt.Color JavaDoc;
30 import java.awt.BasicStroke JavaDoc;
31 import java.util.*;
32 import java.text.SimpleDateFormat JavaDoc;
33 import java.text.DateFormat JavaDoc;
34
35 import org.jrobin.core.RrdException;
36 import org.jrobin.core.XmlWriter;
37
38 /**
39  * <p>Class used to collect information for a JRobin graph. JRobin graphs have many
40  * options and this class has methods and properties to set them.</p>
41  *
42  * <p>The JRobin graph package was designed to create graphs that have the same look as the
43  * RRDTool counter parts. Almost all the same graphing options are available, with some extra's
44  * like more advanced text alignment and custom point-to-point lines and area's.</p>
45  *
46  * <p>To learn more about RDTool's graphs see RRDTool's
47  * <a HREF="../../../../man/rrdgraph.html" target="man">rrdgraph man page</a>. This man page
48  * is important: JRobin uses the same concept of graph sources definition (DEF directives)
49  * and supports RPN extensions in complex datasource definitions (RRDTool's CDEF directives).</p>
50  *
51  * <p><code>RrdGraphDef</code> class does not actually create any graph. It just collects necessary information.
52  * Graph will be created when you pass <code>RrdGraphDef</code> object to a {@link org.jrobin.graph.RrdGraph RrdGraph}, either
53  * by passing it to the constructor or using the <code>setGraphDef()</code> method.</p>
54  *
55  * @author Arne Vandamme (arne.vandamme@jrobin.org)
56  * @author Sasa Markovic (saxon@jrobin.org)
57  */

58 public class RrdGraphDef extends RrdExportDef implements Serializable
59 {
60     // ================================================================
61
// -- Members
62
// ================================================================
63
private Title title = null; // no title
64
private String JavaDoc valueAxisLabel = null; // no vertical label
65
private TimeAxisLabel timeAxisLabel = null; // no horizontal label
66

67     private boolean lazyGeneration = false; // generate only if the file is outdated
68
private boolean gridX = true; // hide entire X axis grid (default: no)
69
private boolean gridY = true; // hide entire Y axis grid (default: no)
70
private boolean minorGridX = true; // hide minor X axis grid (default: no)
71
private boolean minorGridY = true; // hide minor Y axis grid (default: no)
72
private boolean majorGridX = true; // hide major X axis grid with labels (default: no)
73
private boolean majorGridY = true; // hide major Y axis grid with labels (default: no)
74
private boolean frontGrid = true; // show grid in front of the chart (default: yes)
75
private boolean antiAliasing = true; // use anti-aliasing for the chart (default: yes)
76
private boolean showLegend = true; // show legend and comments (default: yes)
77
private boolean drawSignature = true; // show JRobin url signature (default: yes)
78

79     private Color JavaDoc backColor = new Color JavaDoc( 245, 245, 245 ); // variation of light gray
80
private Color JavaDoc canvasColor = Color.WHITE; // white
81
private Color JavaDoc borderColor = Color.LIGHT_GRAY; // light gray, only applicable with a borderStroke
82
private Color JavaDoc normalFontColor = Color.BLACK; // black
83
private Color JavaDoc titleFontColor = Color.BLACK; // black
84
private Color JavaDoc majorGridColor = new Color JavaDoc(130,30,30); // variation of dark red
85
private Color JavaDoc minorGridColor = new Color JavaDoc(140,140,140); // variation of gray
86
private Color JavaDoc axisColor = new Color JavaDoc(130,30,30); // variation of dark red
87
private Color JavaDoc arrowColor = Color.RED; // red
88
private Color JavaDoc frameColor = Color.LIGHT_GRAY; // light gray
89

90     private Font JavaDoc titleFont = null; // use default 'grapher' font
91
private Font JavaDoc normalFont = null; // use default 'grapher' font
92

93     private File background = null; // no background image by default
94
private File overlay = null; // no overlay image by default
95

96     private int chart_lpadding = Grapher.CHART_LPADDING; // padding space on the left of the chart area
97

98     private int firstDayOfWeek = TimeAxisUnit.MONDAY; // first day of a calendar week, default: monday
99

100     private double baseValue = ValueFormatter.DEFAULT_BASE; // unit base value to use (default: 1000)
101
private int scaleIndex = ValueFormatter.NO_SCALE; // fixed units exponent value to use
102

103     private BasicStroke JavaDoc borderStroke = null; // defaults to standard beveled border
104
private TimeAxisUnit tAxis = null; // custom time axis grid, defaults to no custom
105
private ValueAxisUnit vAxis = null; // custom value axis grid, defaults to no custom
106
private GridRange gridRange = null; // custom value range definition, defaults to auto-scale
107

108     // -- Non-settable members
109
private int commentLines = 0; // number of complete lines in the list of comment items
110
private int commentLineShift = 0; // modifier to add to get minimum one complete line of comments
111

112     private ArrayList plotDefs = new ArrayList( 10 ); // holds the list of PlotDefs
113
private ArrayList comments = new ArrayList( 10 ); // holds the list of comment items
114

115         
116     // ================================================================
117
// -- Constructors
118
// ================================================================
119
/**
120      * Constructs a new default JRobin graph object.
121      */

122     public RrdGraphDef() {
123     }
124     
125     /**
126      * Constructs a new JRobin graph object, with a specified time span to be presented on the graph.
127      * Using timestamps defined as number of seconds since the epoch.
128      * @param startTime Starting timestamp in seconds.
129      * @param endTime Ending timestamp in seconds.
130      * @throws RrdException Thrown if invalid parameters are supplied.
131      */

132     public RrdGraphDef( long startTime, long endTime ) throws RrdException
133     {
134         setTimePeriod( startTime, endTime );
135     }
136     
137     /**
138      * Constructs a new JRobin graph object, with a specified time span to be presented on the graph.
139      * Time spam defined using <code>java.util.Date</code> objects.
140      * @param start Starting time.
141      * @param end Ending time.
142      * @throws RrdException Thrown in case of invalid parameters.
143      */

144     public RrdGraphDef( Date start, Date end) throws RrdException
145     {
146         setTimePeriod( start, end );
147     }
148     
149     /**
150      * Constructs a new JRobin graph object, with a specified time span to be presented on the graph.
151      * Time spam defined using <code>java.util.GregorianCalendar</code> objects.
152      * @param start Starting time.
153      * @param end Ending time.
154      * @throws RrdException Thrown in case of invalid parameters.
155      */

156     public RrdGraphDef( GregorianCalendar start, GregorianCalendar end ) throws RrdException
157     {
158         setTimePeriod( start, end );
159     }
160
161
162     // ================================================================
163
// -- Public methods
164
// ================================================================
165
/**
166      * Sets the 'lazy' flag for this GraphDef. This means that upon graph generation and saving to a file,
167      * JRobin will first check that if that file already exists, the 'last modified' timestamp
168      * of the file is smaller than 'last update' timestamp of the used datasources. Only if that is indeed
169      * the case and the image file is outdated, will the graph be generated.
170      *
171      * @param lazyGeneration True if the script should only generate.
172      */

173     public void setLazy( boolean lazyGeneration )
174     {
175         this.lazyGeneration = lazyGeneration;
176     }
177
178     /**
179      * Sets graph title.
180      * @param title Graph title.
181      */

182     public void setTitle( String JavaDoc title ) throws RrdException
183     {
184         this.title = new Title( title );
185     }
186
187     /**
188      * Sets vertical (value) axis label.
189      * @param label Vertical axis label.
190      */

191     public void setVerticalLabel( String JavaDoc label)
192     {
193         this.valueAxisLabel = label;
194     }
195     
196     /**
197      * Sets horizontal (time) axis label.
198      * <p>
199      * A horizontal axis label is always center aligned by default, with an extra linefeed to add
200      * some space before the regular comment lines start. If you wish to remove the extra line of whitespace
201      * you should specify the alignment in the label using @c, @l or @r. Using the @C, @L or @R markers will
202      * align the text appropriately, and leave the extra line of whitespace intact.
203      * </p>
204      * <p>
205      * It is possible to use multiple lines and multiple alignment markers for the axis label, in that case
206      * you should specify alignment for every part of the label to get it to display correctly. When using multiple
207      * lines, no markers will be added to the end of the last line by default.
208      * </p>
209      * @param label Horizontal axis label.
210      */

211     public void setTimeAxisLabel( String JavaDoc label ) throws RrdException
212     {
213         if ( label != null )
214         {
215             timeAxisLabel = new TimeAxisLabel( label );
216             commentLines += timeAxisLabel.getLineCount();
217             commentLineShift = (timeAxisLabel.isCompleteLine() ? 0 : 1);
218             
219             comments.add( 0, timeAxisLabel );
220         }
221     }
222     
223     /**
224      * Sets image background color. If not set, back color defaults to a very light gray.
225      * @param backColor Graph background color.
226      */

227     public void setBackColor( Color JavaDoc backColor )
228     {
229         this.backColor = backColor;
230     }
231
232     /**
233      * Sets chart area background color. If not set, canvas color defaults to white.
234      * @param canvasColor Chart area background color.
235      */

236     public void setCanvasColor( Color JavaDoc canvasColor )
237     {
238         this.canvasColor = canvasColor;
239     }
240     
241     /**
242      * Specifies the settings of the image border.
243      * Default is sort of beveled border around the image.
244      * To disable the image border, just specify a pixel width of 0.
245      * @param c Bordercolor of the image.
246      * @param w Pixel width of the image border.
247      */

248     public void setImageBorder( Color JavaDoc c, int w )
249     {
250         this.borderStroke = new BasicStroke JavaDoc( w );
251         if ( c != null )
252             this.borderColor = c;
253     }
254     
255     /**
256      * Sets the color of the title font used in the graph as a <code>java.awt.Color</code> object.
257      * Default title font color is black.
258      * @param c The color to be used.
259      */

260     public void setTitleFontColor( Color JavaDoc c )
261     {
262         this.titleFontColor = c;
263     }
264     
265     /**
266      * Sets the color of the default font used in the graph as a <code>java.awt.Color</code> object.
267      * Default font color is black.
268      * @param c The color to be used.
269      */

270     public void setDefaultFontColor( Color JavaDoc c )
271     {
272         this.normalFontColor = c;
273     }
274     
275     /**
276      * Sets the font to be used for the graph title as a <code>java.awt.Font</code> object.
277      * Default title font is "Lucida Sans Typewriter", with BOLD attributes and a size of 12 points.
278      * @param f The Font to be used.
279      */

280     public void setTitleFont( Font JavaDoc f )
281     {
282         this.titleFont = f;
283     }
284     
285     /**
286      * Sets the default font to be used in the graph as a <code>java.awt.Font</code> object.
287      * Default font is "Lucida Sans Typewriter", with PLAIN attributes and a size of 10 points.
288      * @param f The Font to be used.
289      */

290     public void setDefaultFont( Font JavaDoc f )
291     {
292         this.normalFont = f;
293     }
294     
295     /**
296      * Sets the color of the chart's major grid.
297      * Grid labels have the same color as the default font.
298      * @param c Color to use.
299      */

300     public void setMajorGridColor( Color JavaDoc c )
301     {
302         this.majorGridColor = c;
303     }
304
305     /**
306      * Determines the color of chart's the minor grid.
307      * @param c Color to use.
308      */

309     public void setMinorGridColor( Color JavaDoc c )
310     {
311         this.minorGridColor = c;
312     }
313
314     /**
315      * Determines the color of chart area frame.
316      * @param c Color to use.
317      */

318     public void setFrameColor( Color JavaDoc c )
319     {
320         this.frameColor = c;
321     }
322
323     /**
324      * Determines the color of chart X axis.
325      * @param c Color to use.
326      */

327     public void setAxisColor( Color JavaDoc c )
328     {
329         this.axisColor = c;
330     }
331
332     /**
333      * Determines the color of the small axis arrow on the chart X axis.
334      * @param c Color to use.
335      */

336     public void setArrowColor( Color JavaDoc c )
337     {
338         this.arrowColor = c;
339     }
340     
341     /**
342      * Determines if the minor grid for the X axis needs to be drawn.
343      * @param visible True if minor grid needs to be drawn, false if not.
344      */

345     public void setMinorGridX( boolean visible )
346     {
347         this.minorGridX = visible;
348     }
349
350     /**
351      * Determines if the minor grid for the Y axis needs to be drawn.
352      * @param visible True if minor grid needs to be drawn, false if not.
353      */

354     public void setMinorGridY( boolean visible )
355     {
356         this.minorGridY = visible;
357     }
358
359     /**
360      * Determines if the major grid with labels for the X axis needs to be drawn.
361      * @param visible True if major grid needs to be drawn, false if not.
362      */

363     public void setMajorGridX( boolean visible )
364     {
365         this.majorGridX = visible;
366     }
367
368     /**
369      * Determines if the major grid with labels for the Y axis needs to be drawn.
370      * @param visible True if major grid needs to be drawn, false if not.
371      */

372     public void setMajorGridY( boolean visible )
373     {
374         this.majorGridY = visible;
375     }
376
377     /**
378      * Determines if the X axis grid should be drawn.
379      * @param visible True if grid needs to be drawn, false if not.
380      */

381     public void setGridX( boolean visible )
382     {
383         this.gridX = visible;
384     }
385
386     /**
387      * Determines if the Y axis grid should be drawn.
388      * @param visible True if grid needs to be drawn, false if not.
389      */

390     public void setGridY( boolean visible )
391     {
392         this.gridY = visible;
393     }
394
395     /**
396      * Determine if the graph grid is in front of the chart itself, or behind it.
397      * Default is in front of the chart.
398      * @param frontGrid True if the grid is in front of the chart.
399      */

400     public void setFrontGrid( boolean frontGrid )
401     {
402         this.frontGrid = frontGrid;
403     }
404
405     /**
406      * Determine if the legend should be visible or not, default: visible.
407      * Invisible legend area means no comments will be plotted, and the graph will be smaller
408      * in height.
409      * @param showLegend True if the legend is visible.
410      */

411     public void setShowLegend( boolean showLegend )
412     {
413         this.showLegend = showLegend;
414     }
415     
416     /**
417      * Determine if the default JRobin signature should be visible, default: yes.
418      * The signature text is "www.jrobin.org" and the signature is centered at the bottom of the graph.
419      * Unless you have a good reason not to draw the signature, please be so kind as to leave the
420      * signature visible. Disabling the signature can give a minor performance boost.
421      * @param showSignature True if the signature is visible.
422      */

423     public void setShowSignature( boolean showSignature )
424     {
425         this.drawSignature = showSignature;
426     }
427     
428     /**
429      * Set the anti-aliasing option for the drawing area of the graph.
430      * Default uses anti-aliasing.
431      * @param aa True if anti-aliasing is on, false if off
432      */

433     public void setAntiAliasing( boolean aa )
434     {
435         this.antiAliasing = aa;
436     }
437     
438     /**
439      * Set the number of pixels on the left of the chart area ( value marker space ).
440      * @param lp Number of pixels used, defaults to 50.
441      */

442     public void setChartLeftPadding( int lp )
443     {
444         this.chart_lpadding = lp;
445     }
446     
447     /**
448      * Sets a background image to use for the graph.
449      * The image can be any of the supported imageio formats,
450      * default <i>.gif, .jpg or .png</i>.
451      *
452      * Please note: if the provided file does not exit at graph creation time, the
453      * corresponding graph will be created without the background image, and without
454      * any exception being thrown.
455      *
456      * @param fileName Filename of the image to use
457      */

458     public void setBackground( String JavaDoc fileName )
459     {
460         File bgFile = new File( fileName );
461         if ( bgFile.exists() )
462             this.background = bgFile;
463     }
464
465     /**
466      * Sets a overlay image to use for the graph.
467      * The image can be any of the supported imageio formats,
468      * default <i>.gif, .jpg or .png</i>. All pixels with the color white
469      * RGB (255, 255, 255) will be treated as transparent.
470      *
471      * Please note: if the provided file does not exit at graph creation time, the
472      * corresponding graph will be created without the overlay image, and without
473      * any exception being thrown.
474      *
475      * @param fileName Filename of the image to use
476      */

477     public void setOverlay( String JavaDoc fileName )
478     {
479         File ovFile = new File( fileName );
480         if ( ovFile.exists() )
481             this.overlay = ovFile;
482     }
483
484     /**
485      * Sets the base for value scaling.
486      * If you are graphing memory this should be set to 1024 so that one Kb is 1024 bytes.
487      * As a default the base value is set to 1000, under the assumption you will be measuring
488      * network traffic, in wich case 1 kb/s equals 1000 b/s.
489      * @param base Value to set as base for scaling.
490      */

491     public void setBaseValue( double base )
492     {
493         this.baseValue = base;
494     }
495
496     /**
497      * This sets the 10** exponent scaling of the Y-axis values.
498      * Normally values will be scaled to the appropriate units (k, M, etc.).
499      * However you may wish to display units always in k (Kilo, 10e3) even if the data is in the
500      * M (Mega, 10e6) range for instance. Value should be an integer which is a multiple of 3
501      * between -18 and 18 inclusive. It is the exponent on the units you which to use.
502      * For example, use 3 to display the y-axis values in k (Kilo, 10e3, thousands),
503      * use -6 to display the y-axis values in u (Micro, 10e-6, millionths). Use a value of 0 to
504      * prevent any scaling of the y-axis values.
505      * @param e Exponent value to use
506      */

507     public void setUnitsExponent( int e )
508     {
509         this.scaleIndex = (6 - e / 3); // Index in the scale table
510
}
511
512     int getUnitsExponent() {
513         return (6 - scaleIndex) * 3;
514     }
515
516     /**
517      * Sets value range that will be presented in the graph. If not set, graph limits will be autoscaled.
518      * If you wish to specify one limit but leave the other auto-scaled, specify the value as Double.NaN
519      * fot the limit that should be auto-scaled.
520      * @param lower Lower limit.
521      * @param upper Upper limit.
522      * @param rigid Rigid grid, won't autoscale limits.
523      */

524
525     public void setGridRange( double lower, double upper, boolean rigid )
526     {
527         gridRange = new GridRange( lower, upper, rigid );
528     }
529
530     /**
531      * This sets the lower limit of the grid to the specified value, see {@link RrdGraphDef#setGridRange(double, double, boolean)}.
532      * This is the equivalent of: <code>setGridRange( lower, Double.NaN, false );</code>
533      * @param lower Lower limit.
534      */

535     public void setLowerLimit( double lower )
536     {
537         gridRange = new GridRange( lower, Double.NaN, false );
538     }
539
540     /**
541      * This sets the grid and labels on the Y axis.
542      * Minor grid lines appear at <code>gridStep</code>, major grid lines accompanied by a label
543      * will appear every <code>labelStep</code> value.
544      * @param gridStep Value step on which a minor grid line will appear.
545      * @param labelStep Value step on which a major grid line with value label will appear.
546      */

547     public void setValueAxis( double gridStep, double labelStep )
548     {
549         vAxis = new ValueAxisUnit( gridStep, labelStep );
550     }
551
552     /**
553      * This sets the grid and labels on the X axis.
554      * There are both minor and major grid lines, the major lines are accompanied by a time label.
555      *
556      * To define a grid line you must define a specific time unit, and a number of time steps.
557      * A grid line will appear everey steps*unit. Possible units are defined in the
558      * {@link org.jrobin.graph.TimeAxisUnit TimeAxisUnit} class, and are <i>SECOND, MINUTE, HOUR, DAY,
559      * WEEK, MONTH</i> and <i>YEAR</i>.
560      *
561      * @param minGridTimeUnit Time unit for the minor grid lines.
562      * @param minGridUnitSteps Time unit steps for the minor grid lines.
563      * @param majGridTimeUnit Time unit for the major grid lines.
564      * @param majGridUnitSteps Time unit steps for the major grid lines.
565      * @param dateFormat Format string of the time labels, according to <code>java.text.SimpleDateFormat</code> specifications.
566      * @param centerLabels True if the time label should be centered in the area between two major grid lines.
567      */

568     public void setTimeAxis( int minGridTimeUnit,
569                                 int minGridUnitSteps,
570                                 int majGridTimeUnit,
571                                 int majGridUnitSteps,
572                                 String JavaDoc dateFormat,
573                                 boolean centerLabels )
574     {
575         this.tAxis = new TimeAxisUnit( minGridTimeUnit,
576                                                 minGridUnitSteps,
577                                                 majGridTimeUnit,
578                                                 majGridUnitSteps,
579                                                 new SimpleDateFormat JavaDoc( dateFormat ),
580                                                 centerLabels ,
581                                                 firstDayOfWeek
582                                             );
583     }
584     
585     /**
586      * Sets the first day of a calendar week, defaults to monday if not set.
587      *
588      * @param day Weekday, 0 for sunday, 6 for saturday.
589      */

590     public void setFirstDayOfWeek( int day )
591     {
592         firstDayOfWeek = day;
593     }
594
595     /**
596      * Adds line plot to the graph definition, using the specified color and legend. This method
597      * takes exactly the same parameters as RRDTool's LINE1 directive (line width
598      * is set to 1). The legend allows for the same
599      * alignment options as <code>gprint</code> or <code>comment</code>.
600      *
601      * @param sourceName Graph source name.
602      * @param color Line collor to be used.
603      * @param legend Legend to be printed on the graph.
604      * @throws RrdException Thrown if invalid graph source name is supplied.
605      */

606     public void line( String JavaDoc sourceName, Color JavaDoc color, String JavaDoc legend ) throws RrdException
607     {
608         plotDefs.add( new Line(sourceName, color) );
609         addLegend( legend, color );
610     }
611     
612     /**
613      * Adds line plot to the graph definition, using the specified color, legend and line width.
614      * This method takes exactly the same parameters as RRDTool's LINE directive. The legend allows for the same
615      * alignment options as <code>gprint</code> or <code>comment</code>.
616      *
617      * @param sourceName Graph source name.
618      * @param color Line color to be used.
619      * @param legend Legend to be printed on the graph.
620      * @param lineWidth Width of the line in pixels.
621      * @throws RrdException Thrown if invalid graph source name is supplied.
622      */

623     public void line( String JavaDoc sourceName, Color JavaDoc color, String JavaDoc legend, int lineWidth ) throws RrdException
624     {
625         plotDefs.add( new Line(sourceName, color, lineWidth) );
626         addLegend( legend, color );
627     }
628     
629     /**
630      * Adds line plot to the graph definition, based on two points.
631      * Start and end point of the line are specified. The legend allows for the same
632      * alignment options as <code>gprint</code> or <code>comment</code>.
633      * @param t1 Timestamp (X axis) of the start point of the line.
634      * @param v1 Value (Y axis) of the start point of the line.
635      * @param t2 Timestamp (X axis) of the end point of the line.
636      * @param v2 Value (Y axis) of the end point of the line.
637      * @param color Line color to be used.
638      * @param legend Legend to be printed on the graph.
639      * @param lineWidth Width of the line in pixels.
640      * @throws RrdException Thrown if invalid graph source name is supplied.
641      */

642     public void line( GregorianCalendar t1, double v1, GregorianCalendar t2, double v2, Color JavaDoc color, String JavaDoc legend, int lineWidth ) throws RrdException
643     {
644         plotDefs.add( new CustomLine( t1.getTimeInMillis() / 1000, v1, t2.getTimeInMillis() / 1000, v2, color, lineWidth ) );
645         addLegend( legend, color );
646     }
647     
648     /**
649      * Adds area plot to the graph definition,
650      * using the specified color and legend. This method
651      * takes exactly the same parameters as RRDTool's AREA directive. The legend allows for the same
652      * alignment options as <code>gprint</code> or <code>comment</code>.
653      *
654      * @param sourceName Graph source name.
655      * @param color Filling collor to be used for area plot.
656      * @param legend Legend to be printed on the graph.
657      * @throws RrdException Thrown if invalid graph source name is supplied.
658      */

659     public void area( String JavaDoc sourceName, Color JavaDoc color, String JavaDoc legend ) throws RrdException
660     {
661         plotDefs.add( new Area(sourceName, color) );
662         addLegend( legend, color );
663     }
664     
665     /**
666      * Adds area plot to the graph definition, based on two points.
667      * Points specified are the bottom-left corner and the upper-right corner.
668      * When stacked onto such an area, a stack is always placed on top of the "upper border" of the
669      * rectangle (value of the second point). The legend allows for the same
670      * alignment options as <code>gprint</code> or <code>comment</code>.
671      * @param t1 Timestamp (X axis) of the bottom-left corner of the area.
672      * @param v1 Value (Y axis) of the bottom-left corner of the area.
673      * @param t2 Timestamp (X axis) of the upper-right corner of the area.
674      * @param v2 Value (Y axis) of the upper-right corner of the area.
675      * @param color Filling collor to be used for area plot.
676      * @param legend Legend to be printed on the graph.
677      * @throws RrdException Thrown if invalid graph source name is supplied.
678      */

679     public void area( GregorianCalendar t1, double v1, GregorianCalendar t2, double v2, Color JavaDoc color, String JavaDoc legend ) throws RrdException
680     {
681         plotDefs.add( new CustomArea( t1.getTimeInMillis() / 1000, v1, t2.getTimeInMillis() / 1000, v2, color ) );
682         addLegend( legend, color );
683     }
684     
685     /**
686      * Adds stacked plot to the graph definition,
687      * using the specified color and legend. This method
688      * takes exactly the same parameters as RRDTool's STACK directive. The legend allows for the same
689      * alignment options as <code>gprint</code> or <code>comment</code>.
690      * @param sourceName Graph source name.
691      * @param color Collor to be used.
692      * @param legend Legend to be printed on the graph.
693      * @throws RrdException Thrown if invalid graph source name is supplied.
694      */

695     public void stack( String JavaDoc sourceName, Color JavaDoc color, String JavaDoc legend ) throws RrdException
696     {
697         plotDefs.add( new Stack(sourceName, color) );
698         addLegend( legend, color );
699     }
700     
701     /**
702      * Adds horizontal rule to the graph definition. The legend allows for the same
703      * alignment options as <code>gprint</code> or <code>comment</code>.
704      * @param value Rule posiotion.
705      * @param color Rule color.
706      * @param legend Legend to be added to the graph.
707      * @throws RrdException Thrown in case of JRobin specific error.
708      */

709     public void hrule(double value, Color JavaDoc color, String JavaDoc legend) throws RrdException {
710         plotDefs.add( new CustomLine( Long.MIN_VALUE, value, Long.MAX_VALUE, value, color ) );
711         addLegend( legend, color );
712     }
713
714     /**
715      * Adds horizontal rule to the graph definition. The legend allows for the same
716      * alignment options as <code>gprint</code> or <code>comment</code>.
717      * @param value Rule posiotion.
718      * @param color Rule color.
719      * @param legend Legend to be added to the graph.
720      * @param lineWidth Width of the hrule line in pixels.
721      * @throws RrdException Thrown in case of JRobin specific error.
722      */

723     public void hrule(double value, Color JavaDoc color, String JavaDoc legend, int lineWidth) throws RrdException {
724         plotDefs.add( new CustomLine( Long.MIN_VALUE, value, Long.MAX_VALUE, value, color, lineWidth ) );
725         addLegend( legend, color );
726     }
727     
728     /**
729      * Adds a vertical rule to the graph definition. The legend allows for the same
730      * alignment options as <code>gprint</code> or <code>comment</code>.
731      * @param timestamp Rule position (specific moment in time)
732      * @param color Rule color.
733      * @param legend Legend to be added to the graph.
734      */

735     public void vrule( GregorianCalendar timestamp, Color JavaDoc color, String JavaDoc legend ) throws RrdException {
736         long timeSecs = timestamp.getTimeInMillis() / 1000;
737         plotDefs.add( new CustomLine( timeSecs, Double.MIN_VALUE, timeSecs, Double.MAX_VALUE, color ) );
738         addLegend( legend, color );
739     }
740
741     /**
742      * Adds a vertical rule to the graph definition. The legend allows for the same
743      * alignment options as <code>gprint</code> or <code>comment</code>.
744      *
745      * @param timestamp Rule position (specific moment in time)
746      * @param color Rule color.
747      * @param legend Legend to be added to the graph.
748      * @param lineWidth Width of the vrule in pixels.
749      */

750     public void vrule( GregorianCalendar timestamp, Color JavaDoc color, String JavaDoc legend, int lineWidth ) throws RrdException {
751         long timeSecs = timestamp.getTimeInMillis() / 1000;
752         plotDefs.add( new CustomLine( timeSecs, Double.MIN_VALUE, timeSecs, Double.MAX_VALUE, color, lineWidth ) );
753         addLegend( legend, color );
754     }
755     
756     /**
757      * Adds comment to the graph definition. A comment on the graph will be left, center or right aligned
758      * if the format string ends with <code>@l</code>, <code>@c</code> or <code>@r</code>,
759      * respectively. It is also possible to align text without adding a linefeed by using
760      * <code>@L</code>, <code>@R</code> and <code>@C</code> as markers. After a GPRINT some
761      * whitespace is appended by default. To suppress this whitespace put a <code>@G</code>
762      * marker at the very end of the string. By putting a <code>@g</code> marker instead all
763      * whitespace inside the string at very beginning or end will be removed also.
764      *
765      * @param text Comment
766      * @throws RrdException Thrown in case of JRobin specific error.
767      */

768     public void comment(String JavaDoc text) throws RrdException {
769         addComment( new Comment(text) );
770     }
771
772     /**
773      * Adds a comment that will contain the current time, to the graph definition. Normal comment codes
774      * apply, but a special marker <code>@t</code> should be present for the location of the timestamp.
775      * The actual format of the printed timestamp is determined by the pattern parameter, for information
776      * on possible patterns, see <em>java.text.SimpleDateFormat</em>.
777      *
778      * @param text Comment text (must contain @t marker).
779      * @param pattern SimpleDateFormat pattern to format the timestamp with.
780      * @throws RrdException Thrown in case of JRobin specific error.
781      */

782     public void time( String JavaDoc text, String JavaDoc pattern ) throws RrdException {
783         addComment( new TimeText( text, pattern ) );
784     }
785
786     /**
787      * Adds a comment that will contain the current time, to the graph definition. Normal comment codes
788      * apply, but a special marker <code>@t</code> should be present for the location of the timestamp.
789      * The actual format of the printed timestamp is determined by the DateFormat passed as a parameter.
790      *
791      * @param text Comment text (must contain @t marker).
792      * @param format DateFormat object to format the timestamp with.
793      * @throws RrdException Thrown in case of JRobin specific error.
794      */

795     public void time( String JavaDoc text, DateFormat JavaDoc format ) throws RrdException {
796         addComment( new TimeText( text, format ) );
797     }
798
799     /**
800      * Adds a comment that will contain the given timestamp, to the graph definition. Normal comment codes
801      * apply, but a special marker <code>@t</code> should be present for the location of the timestamp.
802      * The actual format of the printed timestamp is determined by the pattern parameter, for information
803      * on possible patterns, see <em>java.text.SimpleDateFormat</em>.
804      *
805      * @param text Comment text (must contain @t marker).
806      * @param pattern SimpleDateFormat pattern to format the timestamp with.
807      * @param timestamp Timestamp (in seconds) that should be formatted.
808      * @throws RrdException Thrown in case of JRobin specific error.
809      */

810     public void time( String JavaDoc text, String JavaDoc pattern, long timestamp ) throws RrdException {
811         addComment( new TimeText( text, pattern, timestamp ) );
812     }
813
814     /**
815      * Adds a comment that will contain the given timestamp, to the graph definition. Normal comment codes
816      * apply, but a special marker <code>@t</code> should be present for the location of the timestamp.
817      * The actual format of the printed timestamp is determined by the DateFormat passed as a parameter.
818      *
819      * @param text Comment text (must contain @t marker).
820      * @param format DateFormat object to format the timestamp with.
821      * @param timestamp Timestamp (in seconds) that should be formatted.
822      * @throws RrdException Thrown in case of JRobin specific error.
823      */

824     public void time( String JavaDoc text, DateFormat JavaDoc format, long timestamp ) throws RrdException {
825         addComment( new TimeText( text, format, timestamp ) );
826     }
827
828     /**
829      * Adds a comment that will contain the given timestamp, to the graph definition. Normal comment codes
830      * apply, but a special marker <code>@t</code> should be present for the location of the timestamp.
831      * The actual format of the printed timestamp is determined by the pattern parameter, for information
832      * on possible patterns, see <em>java.text.SimpleDateFormat</em>.
833      *
834      * @param text Comment text (must contain @t marker).
835      * @param pattern SimpleDateFormat pattern to format the timestamp with.
836      * @param date Timestamp (as Date object) that should be formatted.
837      * @throws RrdException Thrown in case of JRobin specific error.
838      */

839     public void time( String JavaDoc text, String JavaDoc pattern, Date date ) throws RrdException {
840         addComment( new TimeText( text, pattern, date ) );
841     }
842
843     /**
844      * Adds a comment that will contain the given timestamp, to the graph definition. Normal comment codes
845      * apply, but a special marker <code>@t</code> should be present for the location of the timestamp.
846      * The actual format of the printed timestamp is determined by the DateFormat passed as a parameter.
847      *
848      * @param text Comment text (must contain @t marker).
849      * @param format DateFormat object to format the timestamp with.
850      * @param date Timestamp (as Date object) that should be formatted.
851      * @throws RrdException Thrown in case of JRobin specific error.
852      */

853     public void time( String JavaDoc text, DateFormat JavaDoc format, Date date ) throws RrdException {
854         addComment( new TimeText( text, format, date ) );
855     }
856
857     /**
858      * Adds a comment that will contain the given timestamp, to the graph definition. Normal comment codes
859      * apply, but a special marker <code>@t</code> should be present for the location of the timestamp.
860      * The actual format of the printed timestamp is determined by the pattern parameter, for information
861      * on possible patterns, see <em>java.text.SimpleDateFormat</em>.
862      *
863      * @param text Comment text (must contain @t marker).
864      * @param pattern SimpleDateFormat pattern to format the timestamp with.
865      * @param cal Timestamp (as Calendar) that should be formatted.
866      * @throws RrdException Thrown in case of JRobin specific error.
867      */

868     public void time( String JavaDoc text, String JavaDoc pattern, Calendar cal) throws RrdException {
869         addComment( new TimeText( text, pattern, cal ) );
870     }
871
872     /**
873      * Adds a comment that will contain the given timestamp, to the graph definition. Normal comment codes
874      * apply, but a special marker <code>@t</code> should be present for the location of the timestamp.
875      * The actual format of the printed timestamp is determined by the DateFormat passed as a parameter.
876      *
877      * @param text Comment text (must contain @t marker).
878      * @param format DateFormat object to format the timestamp with.
879      * @param cal Timestamp (as Calendar) that should be formatted.
880      * @throws RrdException Thrown in case of JRobin specific error.
881      */

882     public void time( String JavaDoc text, DateFormat JavaDoc format, Calendar cal) throws RrdException {
883         addComment( new TimeText( text, format, cal ) );
884     }
885     
886     /**
887      * <p>Calculate the chosen consolidation function <code>consolFun</code> over
888      * the graph <code>sourceName</code> and prints the result
889      * on the graph using the specified <code>format</code> string.</p>
890      *
891      * <p>In the format string there should be a
892      * <code>@n</code> marker (replace <code>n</code> with the desired number of decimals)
893      * in the place where the number should be printed. If an additional <code>@s</code> is
894      * found in the format, the value will be scaled and an appropriate SI magnitude
895      * unit will be printed in place of the <code>@s</code> marker. If you specify
896      * <code>@S</code> instead of <code>@s</code>, the value will be scaled with the scale
897      * factor used in the last gprint directive (uniform value scaling).</p>
898      *
899      * <p>The text printed on the graph will be left, center or right aligned
900      * if the format string ends with <code>@l</code>, <code>@c</code> or <code>@r</code>,
901      * respectively. It is also possible to align text without adding a linefeed by using
902      * <code>@L</code>, <code>@R</code> and <code>@C</code> as markers. After a GPRINT some
903      * whitespace is appended by default. To suppress this whitespace put a <code>@G</code>
904      * marker at the very end of the string. By putting a <code>@g</code> marker instead all
905      * whitespace inside the string at very beginning or end will be removed also.</p>
906      *
907      * @param sourceName Graph source name
908      * @param consolFun Consolidation function to be used for calculation ("AVERAGE",
909      * "MIN", "MAX", "LAST" or "TOTAL" (since 1.3.1)
910      * @param format Format string. For example: "speed is @5.2 @sbits/sec@c",
911      * "temperature = @0 degrees"
912      * @throws RrdException Thrown in case of JRobin specific error
913      */

914     public void gprint(String JavaDoc sourceName, String JavaDoc consolFun, String JavaDoc format) throws RrdException
915     {
916         addComment( new Gprint(sourceName, consolFun, format) );
917     }
918     
919     /**
920      * <p>See the {@link #gprint(java.lang.String, java.lang.String, java.lang.String) gprint()} method for more details.
921      * This gprint implementation allows a specific base value to be specified for this particular gprint only, the specified
922      * base value can be different than the global base value used through the entire graph for the drawing. The resulting value of the gprint
923      * will be formatted according to the specified base value.
924      * </p>
925      *
926      * @param sourceName Graph source name
927      * @param consolFun Consolidation function to be used for calculation ("AVERAGE", "MIN", "MAX", "LAST"
928      * or "TOTAL" (since 1.3.1)
929      * @param format Format string. For example: "speed is @5.2 @sbits/sec@c", "temperature = @0 degrees"
930      * @param base Base value for the formatting, defaults to the graphing base value
931      * @throws RrdException Thrown in case of JRobin specific error
932      */

933     public void gprint( String JavaDoc sourceName, String JavaDoc consolFun, String JavaDoc format, double base ) throws RrdException
934     {
935         addComment( new Gprint(sourceName, consolFun, format, base) );
936     }
937
938     /**
939      * Exports RrdGraphDef (graph definition) object in XML format to output stream.
940      * Generated code can be parsed with {@link RrdGraphDefTemplate} class.
941      * @param stream Output stream to send XML code to
942      */

943     public void exportXmlTemplate(OutputStream stream) {
944         XmlWriter xml = new XmlWriter(stream);
945         xml.startTag("rrd_graph_def");
946         // SPAN
947
xml.startTag("span");
948         xml.writeTag("start", getStartTime() );
949         xml.writeTag("end", getEndTime() );
950         xml.closeTag(); // span
951
// OPTIONS
952
xml.startTag("options");
953         xml.writeTag("anti_aliasing", antiAliasing);
954         xml.writeTag("arrow_color", arrowColor);
955         xml.writeTag("axis_color", axisColor);
956         xml.writeTag("back_color", backColor);
957         if(background != null) {
958             xml.writeTag("background", background);
959         }
960         xml.writeTag("base_value", baseValue);
961         xml.writeTag("canvas", canvasColor);
962         xml.writeTag("left_padding", chart_lpadding);
963         if(normalFont != null) {
964             xml.writeTag("default_font", normalFont);
965         }
966         xml.writeTag("default_font_color", normalFontColor);
967         xml.writeTag("frame_color", frameColor);
968         xml.writeTag("front_grid", frontGrid);
969         if(gridRange != null) {
970             gridRange.exportXmlTemplate(xml);
971         }
972         xml.writeTag("grid_x", gridX);
973         xml.writeTag("grid_y", gridY);
974         if(borderStroke != null) {
975             xml.startTag("border");
976             xml.writeTag("color", borderColor);
977             xml.writeTag("width", (int)borderStroke.getLineWidth());
978             xml.closeTag(); // border
979
}
980         xml.writeTag("major_grid_color", majorGridColor);
981         xml.writeTag("major_grid_x", majorGridX);
982         xml.writeTag("major_grid_y", majorGridY);
983         xml.writeTag("minor_grid_color", minorGridColor);
984         xml.writeTag("minor_grid_x", minorGridX);
985         xml.writeTag("minor_grid_y", minorGridY);
986         if(overlay != null) {
987             xml.writeTag("overlay", overlay);
988         }
989         xml.writeTag("show_legend", showLegend);
990         xml.writeTag("show_signature", drawSignature);
991         if(tAxis != null) {
992             tAxis.exportXmlTemplate(xml);
993         }
994         if(timeAxisLabel != null) {
995             timeAxisLabel.exportXmlTemplate(xml);
996         }
997         if(title != null) {
998             title.exportXmlTemplate(xml);
999         }
1000        if(titleFont != null) {
1001            xml.writeTag("title_font", titleFont);
1002        }
1003        xml.writeTag("title_font_color", titleFontColor);
1004        if(scaleIndex != ValueFormatter.NO_SCALE) {
1005            xml.writeTag("units_exponent", getUnitsExponent());
1006        }
1007        if(vAxis != null) {
1008            vAxis.exportXmlTemplate(xml);
1009        }
1010        if(valueAxisLabel != null) {
1011            xml.writeTag("vertical_label", valueAxisLabel);
1012        }
1013        xml.closeTag(); // options
1014
// DATASOURCES
1015
xml.startTag("datasources");
1016        // defs
1017
for ( int i = 0; i < fetchSources.size(); i++ )
1018            fetchSources.get( i ).exportXml(xml);
1019        // cdefs and sdefs
1020
for (int i = 0; i < cdefList.size(); i++ ) {
1021            Cdef cdef = (Cdef) cdefList.get(i);
1022            cdef.exportXml(xml);
1023        }
1024        xml.closeTag(); // datasources
1025
xml.startTag("graph");
1026        for ( int i = 0; i < comments.size(); i++ )
1027        {
1028            Comment cmt = (Comment) comments.get(i);
1029            if ( cmt.commentType == Comment.CMT_LEGEND || cmt.commentType == Comment.CMT_NOLEGEND)
1030            {
1031                PlotDef pDef = (PlotDef) plotDefs.get( ((Legend) cmt).getPlofDefIndex() );
1032                pDef.exportXmlTemplate(xml, cmt.text);
1033            }
1034            else if(cmt instanceof TimeAxisLabel) {
1035                // NOP: already exported in the options section
1036
}
1037            else {
1038                cmt.exportXmlTemplate(xml);
1039            }
1040        }
1041        xml.closeTag(); // graph
1042
xml.closeTag(); // rrd_graph_def
1043
xml.flush();
1044    }
1045
1046    // ================================================================
1047
// -- Protected (package) methods
1048
// ================================================================
1049
protected boolean isLazy() {
1050        return lazyGeneration;
1051    }
1052    
1053    protected Title getTitle() {
1054        return title;
1055    }
1056    
1057    protected String JavaDoc getVerticalLabel() {
1058        return valueAxisLabel;
1059    }
1060    
1061    protected Color JavaDoc getBackColor() {
1062        return backColor;
1063    }
1064    
1065    protected Color JavaDoc getCanvasColor() {
1066        return canvasColor;
1067    }
1068    
1069    protected Color JavaDoc getImageBorderColor() {
1070        return borderColor;
1071    }
1072    
1073    protected BasicStroke JavaDoc getImageBorderStroke() {
1074        return borderStroke;
1075    }
1076    
1077    protected Color JavaDoc getTitleFontColor() {
1078        return titleFontColor;
1079    }
1080
1081    protected Color JavaDoc getDefaultFontColor() {
1082        return normalFontColor;
1083    }
1084    
1085    protected Font JavaDoc getTitleFont() {
1086        return titleFont;
1087    }
1088    
1089    protected Font JavaDoc getDefaultFont() {
1090        return normalFont;
1091    }
1092    
1093    protected Color JavaDoc getMajorGridColor() {
1094        return majorGridColor;
1095    }
1096    
1097    protected Color JavaDoc getMinorGridColor() {
1098        return minorGridColor;
1099    }
1100    
1101    protected Color JavaDoc getFrameColor() {
1102        return frameColor;
1103    }
1104    
1105    protected Color JavaDoc getAxisColor() {
1106        return axisColor;
1107    }
1108
1109    protected Color JavaDoc getArrowColor() {
1110        return arrowColor;
1111    }
1112    
1113    protected Color JavaDoc getBorderColor() {
1114        return borderColor;
1115    }
1116    
1117    protected BasicStroke JavaDoc getBorderStroke() {
1118        return borderStroke;
1119    }
1120    
1121    protected boolean showMinorGridX() {
1122        return minorGridX;
1123    }
1124    
1125    protected boolean showMinorGridY() {
1126        return minorGridY;
1127    }
1128    
1129    protected boolean showMajorGridX() {
1130        return majorGridX;
1131    }
1132    
1133    protected boolean showMajorGridY() {
1134        return majorGridY;
1135    }
1136
1137    protected boolean showGridX() {
1138        return gridX;
1139    }
1140    
1141    protected boolean showGridY() {
1142        return gridY;
1143    }
1144    
1145    protected boolean drawFrontGrid() {
1146        return frontGrid;
1147    }
1148    
1149    protected boolean showLegend() {
1150        return showLegend;
1151    }
1152    
1153    protected boolean showSignature() {
1154        return drawSignature;
1155    }
1156    
1157    protected boolean isFrontGrid() {
1158        return frontGrid;
1159    }
1160    
1161    protected boolean useAntiAliasing() {
1162        return antiAliasing;
1163    }
1164    
1165    protected int getChartLeftPadding() {
1166        return chart_lpadding;
1167    }
1168    
1169    protected File getBackground() {
1170        return background;
1171    }
1172    
1173    protected File getOverlay() {
1174        return overlay;
1175    }
1176    
1177    protected double getBaseValue() {
1178        return baseValue;
1179    }
1180
1181    protected int getScaleIndex() {
1182        return scaleIndex;
1183    }
1184
1185    protected GridRange getGridRange() {
1186        return gridRange;
1187    }
1188    
1189    protected ValueAxisUnit getValueAxis() {
1190        return vAxis;
1191    }
1192    
1193    protected TimeAxisUnit getTimeAxis() {
1194        return tAxis;
1195    }
1196    
1197    protected int getFirstDayOfWeek() {
1198        return firstDayOfWeek;
1199    }
1200    
1201    protected PlotDef[] getPlotDefs()
1202    {
1203        return (PlotDef[]) plotDefs.toArray( new PlotDef[] {} );
1204    }
1205    
1206    protected Comment[] getComments()
1207    {
1208        return (Comment[]) comments.toArray( new Comment[] {} );
1209    }
1210    
1211    protected int getCommentLineCount()
1212    {
1213        return ( comments.size() > 0 ? commentLines + commentLineShift : 0 );
1214    }
1215
1216    // ================================================================
1217
// -- Private methods
1218
// ================================================================
1219
private void addComment( Comment cmt )
1220    {
1221        commentLines += cmt.getLineCount();
1222        commentLineShift = (cmt.isCompleteLine() ? 0 : 1);
1223        comments.add( cmt );
1224    }
1225    
1226    private void addLegend( String JavaDoc legend, Color JavaDoc color ) throws RrdException
1227    {
1228        // Always add the item, even if it's empty, always add the index
1229
// of the graph this legend is for
1230
addComment( new Legend(legend, color, plotDefs.size() - 1 ) );
1231    }
1232}
1233
Popular Tags