KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > efs > openreports > engine > ChartReportEngine


1 /*
2  * Copyright (C) 2003 Erik Swenson - erik@oreports.com
3  *
4  * This program is free software; you can redistribute it and/or modify it under
5  * the terms of the GNU General Public License as published by the Free Software
6  * Foundation; either version 2 of the License, or (at your option) any later
7  * version.
8  *
9  * This program is distributed in the hope that it will be useful, but WITHOUT
10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
11  * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
12  * details.
13  *
14  * You should have received a copy of the GNU General Public License along with
15  * this program; if not, write to the Free Software Foundation, Inc., 59 Temple
16  * Place - Suite 330, Boston, MA 02111-1307, USA.
17  *
18  */

19
20 package org.efs.openreports.engine;
21
22 import java.awt.Color JavaDoc;
23 import java.awt.image.BufferedImage JavaDoc;
24 import java.io.IOException JavaDoc;
25 import java.sql.Connection JavaDoc;
26 import java.sql.PreparedStatement JavaDoc;
27 import java.sql.ResultSet JavaDoc;
28 import java.util.Map JavaDoc;
29 import java.util.Vector JavaDoc;
30
31 import net.sf.jasperreports.engine.design.JRDesignQuery;
32 import net.sf.jasperreports.engine.util.JRQueryExecuter;
33
34 import org.apache.log4j.Logger;
35 import org.efs.openreports.engine.input.ReportEngineInput;
36 import org.efs.openreports.engine.output.ChartEngineOutput;
37 import org.efs.openreports.engine.output.ReportEngineOutput;
38 import org.efs.openreports.objects.ReportChart;
39 import org.efs.openreports.objects.ReportDataSource;
40 import org.efs.openreports.objects.chart.CategoryChartValue;
41 import org.efs.openreports.objects.chart.ChartValue;
42 import org.efs.openreports.objects.chart.PieChartValue;
43 import org.efs.openreports.objects.chart.TimeChartValue;
44 import org.efs.openreports.objects.chart.XYChartValue;
45 import org.efs.openreports.providers.DataSourceProvider;
46 import org.efs.openreports.providers.DirectoryProvider;
47 import org.efs.openreports.providers.PropertiesProvider;
48 import org.efs.openreports.providers.ProviderException;
49 import org.efs.openreports.util.LocalStrings;
50 import org.efs.openreports.util.ORUtil;
51 import org.jfree.chart.ChartFactory;
52 import org.jfree.chart.ChartRenderingInfo;
53 import org.jfree.chart.JFreeChart;
54 import org.jfree.chart.encoders.EncoderUtil;
55 import org.jfree.chart.encoders.ImageFormat;
56 import org.jfree.chart.entity.StandardEntityCollection;
57 import org.jfree.chart.plot.PlotOrientation;
58 import org.jfree.data.category.CategoryDataset;
59 import org.jfree.data.category.DefaultCategoryDataset;
60 import org.jfree.data.general.DefaultPieDataset;
61 import org.jfree.data.general.PieDataset;
62 import org.jfree.data.time.Second;
63 import org.jfree.data.time.TimeSeries;
64 import org.jfree.data.time.TimeSeriesCollection;
65 import org.jfree.data.xy.XYDataset;
66 import org.jfree.data.xy.XYSeries;
67 import org.jfree.data.xy.XYSeriesCollection;
68
69 /**
70  * ChartReport ReportEngine implementation. Charts are generated using
71  * the JFreeReport library.
72  *
73  * @author Erik Swenson
74  *
75  */

76
77 public class ChartReportEngine extends ReportEngine
78 {
79     protected static Logger log = Logger.getLogger(ChartReportEngine.class.getName());
80
81     public ChartReportEngine(DataSourceProvider dataSourceProvider,
82             DirectoryProvider directoryProvider, PropertiesProvider propertiesProvider)
83     {
84         super(dataSourceProvider, directoryProvider, propertiesProvider);
85     }
86     
87     /**
88      * Generates a ChartEngineOutput from a ReportEngineInput. The output consists
89      * of a byte[] containing a JPEG image.
90      */

91     public ReportEngineOutput generateReport(ReportEngineInput input)
92             throws ProviderException
93     {
94         ChartValue[] values = getChartValues(input.getReport().getReportChart(), input.getParameters());
95         return createChartOutput(input.getReport().getReportChart(), values);
96     }
97
98     /**
99      * Executes the Chart query and builds an array of ChartValues from the results.
100      */

101     public ChartValue[] getChartValues(ReportChart reportChart, Map JavaDoc parameters)
102             throws ProviderException
103     {
104         Connection JavaDoc conn = null;
105         PreparedStatement JavaDoc pStmt = null;
106         ResultSet JavaDoc rs = null;
107
108         try
109         {
110             ReportDataSource dataSource = reportChart.getDataSource();
111             conn = dataSourceProvider.getConnection(dataSource.getId());
112
113             // Use JasperReports Query logic to parse parameters in chart
114
// queries
115

116             JRDesignQuery query = new JRDesignQuery();
117             query.setText(reportChart.getQuery());
118
119             // convert parameters to JRDesignParameters so they can be parsed
120
Map JavaDoc jrParameters = ORUtil.buildJRDesignParameters(parameters);
121
122             pStmt = JRQueryExecuter.getStatement(query, jrParameters, parameters, conn);
123
124             rs = pStmt.executeQuery();
125
126             Vector JavaDoc v = new Vector JavaDoc();
127
128             int chartType = reportChart.getChartType();
129             if (chartType == ReportChart.BAR_CHART)
130             {
131                 while (rs.next())
132                 {
133                     CategoryChartValue catValue = new CategoryChartValue();
134
135                     catValue.setValue(rs.getDouble(1));
136                     catValue.setSeries(rs.getString(2));
137                     catValue.setCategory(rs.getString(3));
138
139                     v.add(catValue);
140                 }
141             }
142             else if (chartType == ReportChart.PIE_CHART
143                     || chartType == ReportChart.RING_CHART)
144             {
145                 while (rs.next())
146                 {
147                     PieChartValue pieValue = new PieChartValue();
148
149                     pieValue.setValue(rs.getDouble(1));
150                     pieValue.setKey(rs.getString(2));
151
152                     v.add(pieValue);
153                 }
154             }
155             else if (chartType == ReportChart.XY_CHART)
156             {
157                 while (rs.next())
158                 {
159                     XYChartValue xyValue = new XYChartValue();
160
161                     xyValue.setSeries(rs.getString(1));
162                     xyValue.setValue(rs.getDouble(2));
163                     xyValue.setSecondValue(rs.getDouble(3));
164
165                     v.add(xyValue);
166                 }
167             }
168             else if (chartType == ReportChart.TIME_CHART)
169             {
170                 while (rs.next())
171                 {
172                     TimeChartValue timeValue = new TimeChartValue();
173
174                     timeValue.setSeries(rs.getString(1));
175                     timeValue.setValue(rs.getDouble(2));
176                     timeValue.setTime(rs.getTimestamp(3));
177
178                     v.add(timeValue);
179                 }
180             }
181
182             ChartValue[] values = new ChartValue[v.size()];
183             v.copyInto(values);
184
185             return values;
186         }
187         catch (Exception JavaDoc e)
188         {
189             e.printStackTrace();
190             throw new ProviderException(LocalStrings
191                     .getString(LocalStrings.ERROR_CHARTQUERY_INVALID)
192                     + ": " + e.toString());
193         }
194         finally
195         {
196             try
197             {
198                 if (rs != null) rs.close();
199                 if (pStmt != null) pStmt.close();
200                 if (conn != null) conn.close();
201             }
202             catch (Exception JavaDoc c)
203             {
204                 log.error("Error closing");
205             }
206         }
207     }
208     
209     private static ChartEngineOutput createChartOutput(ReportChart reportChart, ChartValue[] values)
210     {
211         JFreeChart chart = null;
212
213         switch (reportChart.getChartType())
214         {
215             case ReportChart.BAR_CHART :
216                 chart = createBarChart(reportChart, values);
217                 break;
218             case ReportChart.PIE_CHART :
219                 chart = createPieChart(reportChart, values);
220                 break;
221             case ReportChart.XY_CHART :
222                 chart = createXYChart(reportChart, values);
223                 break;
224             case ReportChart.TIME_CHART :
225                 chart = createTimeChart(reportChart, values);
226                 break;
227             case ReportChart.RING_CHART :
228                 chart = createRingChart(reportChart, values);
229                 break;
230         }
231
232         if (chart == null) return null;
233         
234         chart.setBackgroundPaint(Color.WHITE);
235         
236         ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());
237
238         BufferedImage JavaDoc bufferedImage = chart.createBufferedImage(reportChart.getWidth(), reportChart.getHeight(),info);
239         byte[] image = null;
240         
241         try
242         {
243             image = EncoderUtil.encode(bufferedImage, ImageFormat.JPEG);
244         }
245         catch(IOException JavaDoc ioe)
246         {
247             log.warn(ioe);
248         }
249             
250         ChartEngineOutput chartOutput = new ChartEngineOutput();
251         chartOutput.setContent(image);
252         chartOutput.setContentType(ReportEngineOutput.CONTENT_TYPE_JPEG);
253         chartOutput.setChartRenderingInfo(info);
254         chartOutput.setChartValues(values);
255         
256         return chartOutput;
257     }
258     
259     private static JFreeChart createBarChart(ReportChart reportChart, ChartValue[] values)
260     {
261         CategoryDataset dataset = createCategoryDataset(values);
262
263         PlotOrientation orientation = PlotOrientation.VERTICAL;
264         if (reportChart.getPlotOrientation() == ReportChart.HORIZONTAL)
265         {
266             orientation = PlotOrientation.HORIZONTAL;
267         }
268         
269         JFreeChart chart = ChartFactory.createBarChart3D(reportChart.getTitle(),
270                 reportChart.getXAxisLabel(), reportChart.getYAxisLabel(), dataset,
271                 orientation, reportChart.isShowLegend(), true, false);
272
273         return chart;
274     }
275
276     private static JFreeChart createPieChart(ReportChart reportChart, ChartValue[] values)
277     {
278         PieDataset dataset = createPieDataset(values);
279
280         JFreeChart chart = ChartFactory.createPieChart3D(reportChart.getTitle(),
281                 dataset, reportChart.isShowLegend(), true, false);
282
283         return chart;
284     }
285     
286     private static JFreeChart createRingChart(ReportChart reportChart, ChartValue[] values)
287     {
288         PieDataset dataset = createPieDataset(values);
289
290         JFreeChart chart = ChartFactory.createRingChart(reportChart.getTitle(),
291                 dataset, reportChart.isShowLegend(), true, false);
292
293         return chart;
294     }
295
296     private static JFreeChart createXYChart(ReportChart reportChart, ChartValue[] values)
297     {
298         XYDataset dataset = createXYDataset(values);
299         
300         PlotOrientation orientation = PlotOrientation.VERTICAL;
301         if (reportChart.getPlotOrientation() == ReportChart.HORIZONTAL)
302         {
303             orientation = PlotOrientation.HORIZONTAL;
304         }
305
306         JFreeChart chart = ChartFactory.createXYLineChart(reportChart.getTitle(),
307                 reportChart.getXAxisLabel(), reportChart.getYAxisLabel(), dataset,
308                 orientation, reportChart.isShowLegend(), true, false);
309
310         return chart;
311     }
312
313     private static JFreeChart createTimeChart(ReportChart reportChart, ChartValue[] values)
314     {
315         XYDataset dataset = createTimeDataset(values);
316
317         JFreeChart chart = ChartFactory.createTimeSeriesChart(reportChart
318                 .getTitle(), reportChart.getXAxisLabel(), reportChart
319                 .getYAxisLabel(), dataset, reportChart.isShowLegend(), true, false);
320
321         return chart;
322     }
323
324     private static CategoryDataset createCategoryDataset(ChartValue[] values)
325     {
326         DefaultCategoryDataset dataset = new DefaultCategoryDataset();
327
328         for (int i = 0; i < values.length; i++)
329         {
330             CategoryChartValue value = (CategoryChartValue) values[i];
331             dataset.addValue(value.getValue(), value.getSeries(), value.getCategory());
332         }
333
334         return dataset;
335     }
336
337     private static PieDataset createPieDataset(ChartValue[] values)
338     {
339         DefaultPieDataset dataset = new DefaultPieDataset();
340
341         for (int i = 0; i < values.length; i++)
342         {
343             PieChartValue value = (PieChartValue) values[i];
344             dataset.setValue(value.getKey(), value.getValue());
345         }
346
347         return dataset;
348     }
349
350     private static XYDataset createXYDataset(ChartValue[] values)
351     {
352         XYSeries series = null;
353         XYSeriesCollection seriesCollection = new XYSeriesCollection();
354
355         for (int i = 0; i < values.length; i++)
356         {
357             XYChartValue value = (XYChartValue) values[i];
358
359             if (series == null || !series.getKey().equals(value.getSeries()))
360             {
361                 if (series != null)
362                 {
363                     seriesCollection.addSeries(series);
364                 }
365
366                 series = new XYSeries(value.getSeries());
367             }
368
369             series.add(value.getValue(), value.getSecondValue());
370         }
371
372         seriesCollection.addSeries(series);
373
374         return seriesCollection;
375     }
376
377     private static XYDataset createTimeDataset(ChartValue[] values)
378     {
379         TimeSeries series = null;
380         TimeSeriesCollection seriesCollection = new TimeSeriesCollection();
381
382         for (int i = 0; i < values.length; i++)
383         {
384             TimeChartValue value = (TimeChartValue) values[i];
385
386             if (series == null || !series.getKey().equals(value.getSeries()))
387             {
388                 if (series != null)
389                 {
390                     seriesCollection.addSeries(series);
391                 }
392
393                 series = new TimeSeries(value.getSeries(), Second.class);
394             }
395
396             series.add(new Second(value.getTime()), value.getValue());
397         }
398
399         seriesCollection.addSeries(series);
400
401         return seriesCollection;
402     }
403 }
Popular Tags