KickJava   Java API By Example, From Geeks To Geeks.

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


1 /*
2  * Copyright (C) 2006 Erik Swenson - erik@oreports.com
3  *
4  * This program is free software; you can redistribute it and/or modify it
5  * under the terms of the GNU General Public License as published by the Free
6  * Software Foundation; either version 2 of the License, or (at your option)
7  * any later 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
11  * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
12  * more 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.io.ByteArrayOutputStream JavaDoc;
23 import java.sql.Connection JavaDoc;
24 import java.sql.PreparedStatement JavaDoc;
25 import java.sql.ResultSet JavaDoc;
26 import java.util.HashMap JavaDoc;
27 import java.util.Iterator JavaDoc;
28 import java.util.List JavaDoc;
29 import java.util.Map JavaDoc;
30
31 import net.sf.jasperreports.engine.JRAbstractExporter;
32 import net.sf.jasperreports.engine.JREmptyDataSource;
33 import net.sf.jasperreports.engine.JRExporterParameter;
34 import net.sf.jasperreports.engine.JRField;
35 import net.sf.jasperreports.engine.JasperCompileManager;
36 import net.sf.jasperreports.engine.JasperFillManager;
37 import net.sf.jasperreports.engine.JasperPrint;
38 import net.sf.jasperreports.engine.JasperReport;
39 import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
40 import net.sf.jasperreports.engine.design.JRDesignBand;
41 import net.sf.jasperreports.engine.design.JRDesignExpression;
42 import net.sf.jasperreports.engine.design.JRDesignField;
43 import net.sf.jasperreports.engine.design.JRDesignQuery;
44 import net.sf.jasperreports.engine.design.JRDesignStaticText;
45 import net.sf.jasperreports.engine.design.JRDesignTextField;
46 import net.sf.jasperreports.engine.design.JasperDesign;
47 import net.sf.jasperreports.engine.export.JExcelApiExporter;
48 import net.sf.jasperreports.engine.export.JRCsvExporter;
49 import net.sf.jasperreports.engine.export.JRHtmlExporter;
50 import net.sf.jasperreports.engine.export.JRHtmlExporterParameter;
51 import net.sf.jasperreports.engine.export.JRPdfExporter;
52 import net.sf.jasperreports.engine.export.JRRtfExporter;
53 import net.sf.jasperreports.engine.export.JRTextExporter;
54 import net.sf.jasperreports.engine.export.JRTextExporterParameter;
55 import net.sf.jasperreports.engine.export.JRXlsExporter;
56 import net.sf.jasperreports.engine.export.JRXlsExporterParameter;
57 import net.sf.jasperreports.engine.util.JRLoader;
58 import net.sf.jasperreports.engine.util.JRQueryExecuter;
59
60 import org.apache.commons.beanutils.DynaProperty;
61 import org.apache.commons.beanutils.RowSetDynaClass;
62 import org.apache.log4j.Logger;
63 import org.efs.openreports.engine.input.ReportEngineInput;
64 import org.efs.openreports.engine.output.JasperReportEngineOutput;
65 import org.efs.openreports.engine.output.ReportEngineOutput;
66 import org.efs.openreports.objects.Report;
67 import org.efs.openreports.objects.ReportDataSource;
68 import org.efs.openreports.objects.ReportExportOption;
69 import org.efs.openreports.objects.ReportParameterMap;
70 import org.efs.openreports.providers.DataSourceProvider;
71 import org.efs.openreports.providers.DirectoryProvider;
72 import org.efs.openreports.providers.PropertiesProvider;
73 import org.efs.openreports.providers.ProviderException;
74 import org.efs.openreports.util.ORUtil;
75
76 /**
77  * JasperReports ReportEngine implementation. Report generation is separated
78  * into fillReport and exportReport methods in order to provide direct access
79  * to the JasperPrint object when required.
80  *
81  * @author Erik Swenson
82  *
83  */

84 public class JasperReportEngine extends ReportEngine
85 {
86     protected static Logger log = Logger.getLogger(JasperReportEngine.class.getName());
87
88     public JasperReportEngine(DataSourceProvider dataSourceProvider,
89             DirectoryProvider directoryProvider, PropertiesProvider propertiesProvider)
90     {
91         super(dataSourceProvider, directoryProvider, propertiesProvider);
92     }
93     
94     public ReportEngineOutput generateReport(ReportEngineInput input)
95             throws ProviderException
96     {
97         JasperPrint jasperPrint = fillReport(input);
98
99         ReportEngineOutput engineOutput = exportReport(jasperPrint,
100                 input.getExportType(), input.getReport().getReportExportOption(), input
101                         .getImagesMap(), input.isInlineImages());
102         
103         return engineOutput;
104     }
105     
106     public JasperPrint fillReport(ReportEngineInput input) throws ProviderException
107     {
108         Connection JavaDoc conn = null;
109
110         Report report = input.getReport();
111         Map JavaDoc parameters = input.getParameters();
112         
113         ReportDataSource dataSource = report.getDataSource();
114
115         try
116         {
117             JasperReport jr = null;
118
119             if (report.isQueryReport()) return fillQueryReport(report, parameters, input.getExportType());
120
121             jr = (JasperReport) JRLoader
122                     .loadObject(directoryProvider.getReportDirectory() + report.getFile());
123
124             List JavaDoc subReports = report.getSubReportParameters();
125             if (subReports != null && subReports.size() > 0)
126             {
127                 Iterator JavaDoc iterator = report.getSubReportParameters().iterator();
128                 while (iterator.hasNext())
129                 {
130                     ReportParameterMap rpMap = (ReportParameterMap) iterator.next();
131
132                     JasperReport subReport = (JasperReport) JRLoader.loadObject(directoryProvider
133                             .getReportDirectory()
134                             + rpMap.getReportParameter().getData());
135
136                     parameters.put(rpMap.getReportParameter().getName(), subReport);
137                 }
138             }
139
140             JasperPrint jp = null;
141
142             // create new HashMap to send to JasperReports in order to
143
// fix serialization problems
144
Map JavaDoc jasperReportMap = new HashMap JavaDoc(parameters);
145
146             if (dataSource == null)
147             {
148
149                 jp = JasperFillManager.fillReport(jr, jasperReportMap, new JREmptyDataSource());
150             }
151             else
152             {
153                 conn = dataSourceProvider.getConnection(dataSource.getId());
154                 jp = JasperFillManager.fillReport(jr, jasperReportMap, conn);
155             }
156
157             if (jp == null || jp.getPages().size() < 1) throw new ProviderException("Report Empty");
158
159             return jp;
160         }
161         catch (Exception JavaDoc e)
162         {
163             String JavaDoc errorMessage;
164             if (e.getCause() instanceof java.io.InvalidClassException JavaDoc)
165             {
166                 errorMessage = "Error creating report: " + report.getName()
167                         + " was compiled with a different version of JasperReports.";
168             }
169             else
170             {
171                 errorMessage = "Error creating report: " + e.toString();
172             }
173
174             log.error(errorMessage, e);
175             throw new ProviderException(errorMessage);
176
177         }
178         finally
179         {
180             try
181             {
182                 if (conn != null) conn.close();
183             }
184             catch (Exception JavaDoc ex)
185             {
186                 log.error("Error closing connection: " + ex.getMessage());
187             }
188         }
189     }
190     
191     public ReportEngineOutput exportReport(JasperPrint jasperPrint, int exportType,
192             ReportExportOption exportOptions, Map JavaDoc imagesMap, boolean inlineImages) throws ProviderException
193     {
194         JasperReportEngineOutput engineOutput = new JasperReportEngineOutput();
195         ByteArrayOutputStream JavaDoc outputStream = new ByteArrayOutputStream JavaDoc();
196         
197         JRAbstractExporter exporter = null;
198         
199         try
200         {
201             if (exportType == ReportEngine.EXPORT_PDF)
202             {
203                 engineOutput.setContentType(ReportEngineOutput.CONTENT_TYPE_PDF);
204                 
205                 exporter = new JRPdfExporter();
206             }
207             else if (exportType == ReportEngine.EXPORT_XLS
208                     || exportType == ReportEngine.EXPORT_EXCEL)
209             {
210                 engineOutput.setContentType(ReportEngineOutput.CONTENT_TYPE_XLS);
211                 
212                 if (exportType == ReportEngine.EXPORT_XLS)
213                 {
214                     exporter = new JRXlsExporter();
215                 }
216                 else if (exportType == ReportEngine.EXPORT_EXCEL)
217                 {
218                     exporter = new JExcelApiExporter();
219                 }
220
221                 exporter.setParameter(
222                         JRXlsExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS,
223                         new Boolean JavaDoc(exportOptions.isXlsRemoveEmptySpaceBetweenRows()));
224
225                 exporter.setParameter(JRXlsExporterParameter.IS_ONE_PAGE_PER_SHEET,
226                         new Boolean JavaDoc(exportOptions.isXlsOnePagePerSheet()));
227
228                 exporter.setParameter(JRXlsExporterParameter.IS_DETECT_CELL_TYPE,
229                         new Boolean JavaDoc(exportOptions.isXlsAutoDetectCellType()));
230
231                 exporter.setParameter(JRXlsExporterParameter.IS_WHITE_PAGE_BACKGROUND,
232                         new Boolean JavaDoc(exportOptions.isXlsWhitePageBackground()));
233             }
234             else if (exportType == ReportEngine.EXPORT_CSV)
235             {
236                 engineOutput.setContentType(ReportEngineOutput.CONTENT_TYPE_CSV);
237                 
238                 exporter = new JRCsvExporter();
239             }
240             else if (exportType == ReportEngine.EXPORT_TEXT)
241             {
242                 engineOutput.setContentType(ReportEngineOutput.CONTENT_TYPE_TEXT);
243                 
244                 exporter = new JRTextExporter();
245                 exporter.setParameter(JRTextExporterParameter.CHARACTER_WIDTH,
246                         new Integer JavaDoc(10));
247                 exporter.setParameter(JRTextExporterParameter.CHARACTER_HEIGHT,
248                         new Integer JavaDoc(10));
249             }
250             else if (exportType == ReportEngine.EXPORT_RTF)
251             {
252                 engineOutput.setContentType(ReportEngineOutput.CONTENT_TYPE_RTF);
253                 
254                 exporter = new JRRtfExporter();
255             }
256             else
257             {
258                 engineOutput.setContentType(ReportEngineOutput.CONTENT_TYPE_HTML);
259                 
260                 exporter = new JRHtmlExporter();
261
262                 exporter.setParameter(
263                         JRHtmlExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS,
264                         new Boolean JavaDoc(exportOptions.isHtmlRemoveEmptySpaceBetweenRows()));
265
266                 exporter.setParameter(JRHtmlExporterParameter.IS_USING_IMAGES_TO_ALIGN,
267                         new Boolean JavaDoc(exportOptions.isHtmlUsingImagesToAlign()));
268
269                 exporter.setParameter(JRHtmlExporterParameter.IS_WHITE_PAGE_BACKGROUND,
270                         new Boolean JavaDoc(exportOptions.isHtmlWhitePageBackground()));
271
272                 exporter.setParameter(JRHtmlExporterParameter.IS_WRAP_BREAK_WORD,
273                         new Boolean JavaDoc(exportOptions.isHtmlWrapBreakWord()));
274                 
275                 if (imagesMap == null) imagesMap = new HashMap JavaDoc();
276                 exporter.setParameter(JRHtmlExporterParameter.IMAGES_MAP, imagesMap);
277                 
278                 if (inlineImages)
279                 {
280                     exporter.setParameter(JRHtmlExporterParameter.IMAGES_URI, "cid:");
281                 }
282                 else
283                 {
284                     //see ImageLoaderAction for more information
285
exporter.setParameter(JRHtmlExporterParameter.IMAGES_URI,
286                         "imageLoader.action?imageName=");
287                 }
288             }
289
290             exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
291             exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, outputStream);
292             exporter.exportReport();
293         }
294         catch (Exception JavaDoc e)
295         {
296             throw new ProviderException(e.toString());
297         }
298         
299         engineOutput.setImagesMap(imagesMap);
300         engineOutput.setContent(outputStream.toByteArray());
301         
302         return engineOutput;
303     }
304     
305     /*
306      * Creates a default JasperPrint from a QueryReport. This method is used when
307      * a scheduled QueryReport is executed.
308      */

309     private JasperPrint fillQueryReport(Report report, Map JavaDoc map, int exportType) throws Exception JavaDoc
310     {
311         Connection JavaDoc conn = null;
312         PreparedStatement JavaDoc pStmt = null;
313         ResultSet JavaDoc rs = null;
314
315         // create new HashMap to send to JasperReports in order to
316
// fix serialization problems
317
Map JavaDoc parameters = new HashMap JavaDoc(map);
318         
319         List JavaDoc results = null;
320         DynaProperty[] properties = null;
321
322         try
323         {
324             ReportDataSource dataSource = report.getDataSource();
325             conn = dataSourceProvider.getConnection(dataSource.getId());
326
327             if (parameters == null || parameters.isEmpty())
328             {
329                 pStmt = conn.prepareStatement(report.getQuery());
330             }
331             else
332             {
333                 // Use JasperReports Query logic to parse parameters in chart
334
// queries
335

336                 JRDesignQuery query = new JRDesignQuery();
337                 query.setText(report.getQuery());
338
339                 // convert parameters to JRDesignParameters so they can be
340
// parsed
341
Map JavaDoc jrParameters = ORUtil.buildJRDesignParameters(parameters);
342
343                 pStmt = JRQueryExecuter.getStatement(query, jrParameters, parameters, conn);
344             }
345
346             rs = pStmt.executeQuery();
347
348             RowSetDynaClass rowSetDynaClass = new RowSetDynaClass(rs);
349
350             results = rowSetDynaClass.getRows();
351             properties = rowSetDynaClass.getDynaProperties();
352
353             rs.close();
354         }
355         catch (Exception JavaDoc e)
356         {
357             throw new ProviderException("Error executing report query: " + e.getMessage());
358         }
359         finally
360         {
361             try
362             {
363                 if (pStmt != null) pStmt.close();
364                 if (conn != null) conn.close();
365             }
366             catch (Exception JavaDoc c)
367             {
368                 log.error("Error closing");
369             }
370         }
371
372         JasperDesign jasperDesign = new JasperDesign();
373         jasperDesign.setName(report.getName().replaceAll(" ", "_"));
374         
375         int width = jasperDesign.getPageWidth();
376         int height = jasperDesign.getPageHeight();
377         
378         jasperDesign.setOrientation(JasperDesign.ORIENTATION_LANDSCAPE);
379         jasperDesign.setPageHeight(width);
380         jasperDesign.setPageWidth(height);
381
382         for (int i = 0; i < properties.length; i++)
383         {
384
385             JRDesignField field = new JRDesignField();
386             field.setName((String JavaDoc) properties[i].getName());
387             field.setValueClass((Class JavaDoc) properties[i].getType());
388
389             try
390             {
391                 jasperDesign.addField(field);
392             }
393             catch (Exception JavaDoc e)
394             {
395                 log.warn(e);
396             }
397         }
398
399         if (exportType == ReportEngine.EXPORT_PDF)
400         {
401             // add title
402
JRDesignStaticText sText = new JRDesignStaticText();
403             sText.setX(0);
404             sText.setY(0);
405             sText.setWidth(jasperDesign.getPageHeight());
406             sText.setHeight(50);
407             sText.setText(jasperDesign.getName());
408             sText.setFontSize(16);
409             sText.setBold(true);
410
411             JRDesignBand band = new JRDesignBand();
412             band.setHeight(50);
413             band.addElement(sText);
414
415             jasperDesign.setTitle(band);
416         
417             // add page footer for page numbers
418
band = new JRDesignBand();
419             band.setHeight(15);
420
421             sText = new JRDesignStaticText();
422             sText.setX(0);
423             sText.setY(0);
424             sText.setHeight(15);
425             sText.setWidth(40);
426             sText.setText("Page:");
427
428             band.addElement(sText);
429
430             JRDesignExpression exp = new JRDesignExpression();
431             exp.addVariableChunk("PAGE_NUMBER");
432             exp.setValueClass(Integer JavaDoc.class);
433
434             JRDesignTextField txt = new JRDesignTextField();
435             txt.setExpression(exp);
436             txt.setX(40);
437             txt.setY(0);
438             txt.setHeight(15);
439             txt.setWidth(100);
440
441             band.addElement(txt);
442
443             jasperDesign.setPageFooter(band);
444         }
445
446         JRDesignBand emptyBand = new JRDesignBand();
447         emptyBand.setHeight(0);
448         jasperDesign.setPageHeader(emptyBand);
449         jasperDesign.setColumnFooter(emptyBand);
450         jasperDesign.setSummary(emptyBand);
451
452         JRField[] fields = jasperDesign.getFields();
453
454         // add column header and detail bands
455
JRDesignBand bandDetail = new JRDesignBand();
456         bandDetail.setHeight(20);
457
458         JRDesignBand bandHeader = new JRDesignBand();
459         bandHeader.setHeight(20);
460         
461         int fieldWidth = (jasperDesign.getPageWidth() - jasperDesign.getLeftMargin()
462                 - jasperDesign.getRightMargin() - (fields.length - 1) * jasperDesign.getColumnSpacing())
463                 / fields.length;
464
465         for (int i = 0; i < fields.length; i++)
466         {
467             try
468             {
469                 JRField field = fields[i];
470
471                 JRDesignExpression exp = new JRDesignExpression();
472                 exp.addFieldChunk(field.getName());
473                 
474                 if (field.getValueClassName().equals("java.sql.Date"))
475                 {
476                     // JasperReports does not support java.sql.Date in text field expression
477
exp.setValueClass(java.util.Date JavaDoc.class);
478                 }
479                 else
480                 {
481                     exp.setValueClass(field.getValueClass());
482                 }
483
484                 JRDesignTextField txt = new JRDesignTextField();
485                 txt.setExpression(exp);
486                 txt.setX(i * fieldWidth);
487                 txt.setY(0);
488                 txt.setHeight(20);
489                 txt.setWidth(fieldWidth);
490
491                 if (field.getValueClass().equals(Double JavaDoc.class))
492                 {
493                     txt.setPattern("0.00");
494                 }
495
496                 bandDetail.addElement(txt);
497
498                 JRDesignStaticText sText = new JRDesignStaticText();
499                 sText.setX(i * fieldWidth);
500                 sText.setY(0);
501                 sText.setHeight(20);
502                 sText.setWidth(fieldWidth);
503                 sText.setText(field.getName());
504                 sText.setUnderline(true);
505
506                 bandHeader.addElement(sText);
507             }
508             catch (Exception JavaDoc e)
509             {
510                 log.warn(e);
511             }
512         }
513
514         if (exportType == ReportEngine.EXPORT_PDF) jasperDesign.setColumnHeader(bandHeader);
515         jasperDesign.setDetail(bandDetail);
516         
517         JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign);
518         JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters,
519                 new JRBeanCollectionDataSource(results));
520
521         return jasperPrint;
522     }
523 }
Popular Tags