KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > pentaho > plugin > jasperreports > JasperReportsComponent


1 /*
2  * Copyright 2006 Pentaho Corporation. All rights reserved.
3  * This software was developed by Pentaho Corporation and is provided under the terms
4  * of the Mozilla Public License, Version 1.1, or any later version. You may not use
5  * this file except in compliance with the license. If you need a copy of the license,
6  * please go to http://www.mozilla.org/MPL/MPL-1.1.txt. The Original Code is the Pentaho
7  * BI Platform. The Initial Developer is Pentaho Corporation.
8  *
9  * Software distributed under the Mozilla Public License is distributed on an "AS IS"
10  * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. Please refer to
11  * the license for the specific language governing your rights and limitations.
12 */

13 package org.pentaho.plugin.jasperreports;
14
15 import java.io.File JavaDoc;
16 import java.io.OutputStream JavaDoc;
17 import java.sql.Connection JavaDoc;
18 import java.sql.DriverManager JavaDoc;
19 import java.sql.SQLException JavaDoc;
20 import java.util.ArrayList JavaDoc;
21 import java.util.HashMap JavaDoc;
22 import java.util.HashSet JavaDoc;
23 import java.util.Iterator JavaDoc;
24 import java.util.List JavaDoc;
25 import java.util.Map JavaDoc;
26 import java.util.Set JavaDoc;
27
28 import javax.naming.NamingException JavaDoc;
29 import javax.sql.DataSource JavaDoc;
30 import net.sf.jasperreports.engine.JRException;
31 import net.sf.jasperreports.engine.JRExporter;
32 import net.sf.jasperreports.engine.JRExporterParameter;
33 import net.sf.jasperreports.engine.JRParameter;
34 import net.sf.jasperreports.engine.JasperCompileManager;
35 import net.sf.jasperreports.engine.JasperFillManager;
36 import net.sf.jasperreports.engine.JasperPrint;
37 import net.sf.jasperreports.engine.JasperReport;
38 import net.sf.jasperreports.engine.export.JRCsvExporter;
39 import net.sf.jasperreports.engine.export.JRHtmlExporter;
40 import net.sf.jasperreports.engine.export.JRHtmlExporterParameter;
41 import net.sf.jasperreports.engine.export.JRPdfExporter;
42 import net.sf.jasperreports.engine.export.JRXlsExporter;
43 import net.sf.jasperreports.engine.export.JRXlsExporterParameter;
44 import net.sf.jasperreports.engine.export.JRXmlExporter;
45 import net.sf.jasperreports.engine.util.JRLoader;
46 import org.apache.commons.logging.Log;
47 import org.apache.commons.logging.LogFactory;
48 import org.pentaho.core.repository.IContentItem;
49 import org.pentaho.core.runtime.IActionParameter;
50 import org.pentaho.core.solution.IActionResource;
51 import org.pentaho.core.system.PentahoSystem;
52 import org.pentaho.core.util.DatasourceHelper;
53 import org.pentaho.messages.Messages;
54 import org.pentaho.plugin.ComponentBase;
55 import org.pentaho.plugin.core.StandardSettings;
56
57 /**
58  * @author James Dixon and Barry Klawans
59  *
60  * JasperReports runner for Pentaho.
61  *
62  * This class implements a Pentaho Component that runs JasperReports. It
63  * includes full support for parameterization and output in PDF and HTML.
64  *
65  * This is a Beta version, with a number of open issues. 1) Data sources must be
66  * specified in the config file for EACH report. There should be a default
67  * source in the jasper reports configuration. 2) Support for JNDI defined data
68  * source has not been added yet. 3) Images are written to the Pentaho temp
69  * directory and never cleaned up. They should probably be moved into Session
70  * related storage. 4) Support should be added so a Filled report can be
71  * persisited into the Pentaho repository and exported repeatedly.
72  *
73  * @author Radek Maciaszek <radek@m3.net>
74  *
75  * Added handling multiple reports in batch mode which allow to create excel reports with
76  * multiple worksheets
77  */

78 public class JasperReportsComponent extends ComponentBase {
79
80     private static final String JavaDoc REMOVE_EMPTY_ROWS = "remove-empty-rows"; //$NON-NLS-1$
81

82     private static final String JavaDoc IMAGE_URL = "image-url"; //$NON-NLS-1$
83

84     private static final String JavaDoc IMAGE_DIR = "image-dir"; //$NON-NLS-1$
85

86     private static final String JavaDoc REPORT_OUTPUT = "report-output"; //$NON-NLS-1$
87

88     private static final long serialVersionUID = -4422766007912720969L;
89
90     /**
91      * The extension of the JasperReports reports to run. Currently only designs
92      * saved as an XML file are supported, not searilized JasperDesign objects.
93      */

94     public final static String JavaDoc JASPER_REPORTS_DESIGN_EXTENSION = ".jrxml"; //$NON-NLS-1$
95

96     private static Log logger = LogFactory.getLog(JasperReportsComponent.class);
97     
98     /**
99      * The extension of a compiled JasperReports file.
100      */

101     public final static String JavaDoc COMPILED_JASPER_REPORTS_EXTENSION = ".jasper"; //$NON-NLS-1$
102

103     public Log getLogger() {
104         return logger;
105     }
106
107     /**
108      * Validates the settings in the jasper reports configuration file.
109      * <p>
110      * Currently the mandatory settings are imageHandling/imageUrl and
111      * imageHandling/imageDir, which specify where to store images generated by
112      * the report (ie charts) and how to access the images inside an HTML page.
113      */

114     protected boolean validateSystemSettings() {
115         // make sure that the system settings are valid.
116
// In production this will only be called when they have changed, for
117
// development purposes we are calling it every time
118

119         // get and validate system settings
120
String JavaDoc imageUrl = PentahoSystem.getSystemSetting("jasperreports/jasperreports-conf.xml", "jasperreports/imageHandling/imageUrl", null); //$NON-NLS-1$ //$NON-NLS-2$
121
String JavaDoc imageDir = PentahoSystem.getSystemSetting("jasperreports/jasperreports-conf.xml", "jasperreports/imageHandling/imageDir", null); //$NON-NLS-1$ //$NON-NLS-2$
122
String JavaDoc removeEmptyRows = PentahoSystem.getSystemSetting("jasperreports/jasperreports-conf.xml", "jasperreports/htmlExportOptions/removeEmptySpaceBetweenRows", "false"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
123

124         if (debug) {
125             debug(Messages.getString("JasperReport.DEBUG_IMAGE_URL") + imageUrl); //$NON-NLS-1$
126
debug(Messages.getString("JasperReport.DEBUG_IMAGE_DIRECTORY") + imageDir); //$NON-NLS-1$
127
debug(Messages.getString("JasperReport.DEBUG_REMOVE_EMPTRY_ROWS") + removeEmptyRows); //$NON-NLS-1$
128
}
129
130         if (imageUrl == null) {
131             error(Messages.getErrorString("JasperReport.ERROR_0001_IMAGE_URL_NOT_DEFINED")); //$NON-NLS-1$
132
return false;
133         }
134         if (imageDir == null) {
135             error(Messages.getErrorString("JasperReport.ERROR_0002_IMAGE_DIRECTORY_INVALID")); //$NON-NLS-1$
136
return false;
137         }
138
139         saveSetting(IMAGE_URL, imageUrl);
140         saveSetting(IMAGE_DIR, imageDir);
141         saveSetting(REMOVE_EMPTY_ROWS, removeEmptyRows);
142
143         // set a property for these, they will be cached and be available at
144
// execution time
145
return true;
146     }
147
148     /**
149      * NOTE: The comments from Pentaho state that in production this will not be
150      * called during execution. If so, this info needs to be moved into the
151      * execute path as well.
152      */

153     public boolean validateAction() {
154
155         // In production this will only be called during validation and publish,
156
// it will not be called before report executions
157
// for now it is called before every execution
158

159         // get report connection setting
160
boolean jndiDefined = isDefinedInput(StandardSettings.JNDI);
161
162         // Validate settings are passed. Treat the password as optional.
163
if (!jndiDefined) {
164             if (!isDefinedInput(StandardSettings.DRIVER)) {
165                 error(Messages.getErrorString("JasperReport.ERROR_0003_JDBC_DRIVER_NOT_SPECIFIED")); //$NON-NLS-1$
166
return false;
167             }
168             if (!isDefinedInput(StandardSettings.CONNECTION)) {
169                 error(Messages.getErrorString("JasperReport.ERROR_0004_JDBC_CONNECTION_NOT_SPECIFIED")); //$NON-NLS-1$
170
return false;
171             }
172             if (!isDefinedInput(StandardSettings.USERID)) {
173                 error(Messages.getErrorString("JasperReport.ERROR_0005_JDBC_USER_NOT_SPECIFIED")); //$NON-NLS-1$
174
return false;
175             }
176         }
177         // check the inputs, we cannot reply on input values during validation
178
if (!isDefinedInput("output-type")) { //$NON-NLS-1$
179
error(Messages.getErrorString("JasperReport.ERROR_0006_OUTPUT_TYPE_NOT_SPECIFIED")); //$NON-NLS-1$
180
return false;
181         }
182
183         // check the resources
184
if (getResourceNames().isEmpty()) {
185             error(Messages.getErrorString("JasperReport.ERROR_0007_REPORT_DEFINITION_NOT_SPECIFIED")); //$NON-NLS-1$
186
return false;
187         }
188
189         return true;
190     }
191
192     /**
193      * Creates and initializes the appropriate exporter for producing output.
194      * All channel specific export options will be set for the exporter.
195      *
196      * @param outputType
197      * the channel (pdf or html) to use when exporting
198      * @param reportName
199      * used to create a unique name for the directory to store images
200      * in. Should be something unique to the invocation, such as the
201      * session id, but I don't know how to get that from the Pentaho
202      * API yet.
203      *
204      * @return the exporter to use, or <code>null</code> if the output type is
205      * not valid.
206      *
207      * TODO: replace reportName with something unique, like session id.
208      */

209     private JRExporter getExporter(String JavaDoc outputType, String JavaDoc reportName) {
210         JRExporter exporter = null;
211         if ("html".equals(outputType)) { //$NON-NLS-1$
212
String JavaDoc removeEmptyRows = getStringSetting("removeEmptyRows"); //$NON-NLS-1$
213
exporter = new JRHtmlExporter();
214             exporter.setParameter(JRHtmlExporterParameter.IS_USING_IMAGES_TO_ALIGN, new Boolean JavaDoc(false));
215             if (removeEmptyRows != null && "true".equalsIgnoreCase(removeEmptyRows)) { //$NON-NLS-1$
216
exporter.setParameter(JRHtmlExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS, new Boolean JavaDoc(true));
217             }
218             String JavaDoc imageUrl = PentahoSystem.getApplicationContext().getBaseUrl() + getStringSetting(IMAGE_URL);
219             String JavaDoc imagePath = PentahoSystem.getApplicationContext().getSolutionPath(getStringSetting(IMAGE_DIR));
220             if (!imagePath.endsWith(File.separator))
221                 imagePath = imagePath + File.separator;
222             imagePath = imagePath + reportName + File.separator;
223             File JavaDoc imageDir = new File JavaDoc(imagePath);
224             imageDir.mkdirs();
225             exporter.setParameter(JRHtmlExporterParameter.IMAGES_DIR, imageDir);
226             // exporter.setParameter(JRHtmlExporter.IMAGES_URI, imageUrl +
227
// reportName ); //$NON-NLS-1$
228
exporter.setParameter(JRHtmlExporterParameter.IMAGES_URI, imageUrl + reportName + "/"); //$NON-NLS-1$
229
exporter.setParameter(JRHtmlExporterParameter.IS_OUTPUT_IMAGES_TO_DIR, new Boolean JavaDoc(true));
230             if (debug)
231                 debug(Messages.getString("JasperReport.DEBUG_IMAGE_DIRECTORY", imagePath)); //$NON-NLS-1$
232
} else if ("pdf".equals(outputType)) { //$NON-NLS-1$
233
exporter = new JRPdfExporter();
234         } else if ("xls".equals(outputType)) { //$NON-NLS-1$
235
exporter = new JRXlsExporter();
236             // Some cleaning in order to make excel reports look better
237
exporter.setParameter(JRXlsExporterParameter.IS_AUTO_DETECT_CELL_TYPE, new Boolean JavaDoc(true));
238             exporter.setParameter(JRXlsExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS, new Boolean JavaDoc(true));
239             exporter.setParameter(JRXlsExporterParameter.IS_WHITE_PAGE_BACKGROUND, new Boolean JavaDoc(true));
240             exporter.setParameter(JRXlsExporterParameter.IS_ONE_PAGE_PER_SHEET, Boolean.FALSE);
241         } else if ("csv".equals(outputType)) { //$NON-NLS-1$
242
exporter = new JRCsvExporter();
243         } else if ("xml".equals(outputType)) { //$NON-NLS-1$
244
exporter = new JRXmlExporter();
245         }
246         return exporter;
247     }
248
249     /**
250      * Runs a report.
251      */

252     public boolean executeAction() {
253
254         // perform runtime validation of the output type
255
String JavaDoc reportOutputType = getInputStringValue("output-type"); //$NON-NLS-1$
256
if (debug)
257             debug(Messages.getString("JasperReport.DEBUG_OUTPUT_TYPE", reportOutputType)); //$NON-NLS-1$
258
String JavaDoc mimeType = null;
259         if ("html".equals(reportOutputType)) { //$NON-NLS-1$
260
mimeType = "text/html"; //$NON-NLS-1$
261
} else if ("pdf".equals(reportOutputType)) { //$NON-NLS-1$
262
mimeType = "application/pdf"; //$NON-NLS-1$
263
} else if ("xls".equals(reportOutputType)) { //$NON-NLS-1$
264
mimeType = "application/vnd.ms-excel"; //$NON-NLS-1$
265
} else if ("csv".equals(reportOutputType)) { //$NON-NLS-1$
266
mimeType = "text/text"; //$NON-NLS-1$
267
} else if ("xml".equals(reportOutputType)) { //$NON-NLS-1$
268
mimeType = "text/xml"; //$NON-NLS-1$
269
}
270         String JavaDoc extension = "." + reportOutputType; //$NON-NLS-1$
271
if (mimeType == null) {
272             error(Messages.getErrorString("JasperReport.ERROR_0011_OUTPUT_TYPE_INVALID")); //$NON-NLS-1$
273
return false;
274         }
275         
276         // Store parameters for all reports
277
HashMap JavaDoc allReportParameters = new HashMap JavaDoc();
278         
279         // get the real location of the report
280
//IActionResource resource = getResource("report-definition"); //$NON-NLS-1$
281
String JavaDoc resourceName = new String JavaDoc();
282         
283         Set JavaDoc resources = getResourceNames();
284         HashSet JavaDoc compiledReportPaths = new HashSet JavaDoc();
285         
286         Iterator JavaDoc resourcesIterator = resources.iterator();
287         
288         while (resourcesIterator.hasNext()) {
289             resourceName = (String JavaDoc) resourcesIterator.next();
290             IActionResource resource = getResource(resourceName);
291             
292             // Compile every report
293
String JavaDoc reportDefinitionPath;
294             if (resource.getSourceType() == IActionResource.SOLUTION_FILE_RESOURCE) {
295                 reportDefinitionPath = PentahoSystem.getApplicationContext().getSolutionPath(resource.getAddress());
296             } else {
297                 reportDefinitionPath = resource.getAddress();
298             }
299             if (reportDefinitionPath == null) {
300                 error(Messages.getErrorString("JasperReport.ERROR_0008_REPORT_DEFINITION_UNREADABLE")); //$NON-NLS-1$
301
return false;
302             }
303     
304             if (debug)
305                 debug(Messages.getString("JasperReport.DEBUG_RUNNING_REPORT", reportDefinitionPath)); //$NON-NLS-1$
306

307             // See if we have a compiled report or a report definition. If its a
308
// definition, see if a compiled version exists, and if not, compile it.
309
// get the base name of the report.
310
String JavaDoc compiledReportPath = null;
311     
312             // Parse the path and get the name of the report.
313
File JavaDoc sourceFile = new File JavaDoc(reportDefinitionPath);
314             String JavaDoc reportBaseName = sourceFile.getName();
315             int extensionIdx = reportBaseName.lastIndexOf("."); //$NON-NLS-1$
316
if (extensionIdx > 0)
317                 reportBaseName = reportBaseName.substring(0, extensionIdx);
318     
319             // If we are handed a .jasper file, just use it as the compiled report
320
// definition.
321
if (reportDefinitionPath.endsWith(COMPILED_JASPER_REPORTS_EXTENSION)) {
322                 compiledReportPath = reportDefinitionPath;
323             } else {
324                 // Assume its a .jrxml
325
if (!sourceFile.exists()) {
326                     error(Messages.getErrorString("JasperReport.ERROR_0009_REPORT_DEFINITION_MISSING", reportDefinitionPath)); //$NON-NLS-1$
327
return false;
328                 }
329                 if (debug)
330                     debug(Messages.getString("JasperReport.DEBUG_REPORT_FILE_FOUND")); //$NON-NLS-1$
331
// Get the directory where the report source is, and compile to
332
// same directory
333
String JavaDoc reportDirectory = sourceFile.getParent();
334                 if (!reportDirectory.endsWith(File.separator)) {
335                     reportDirectory = reportDirectory + File.separator;
336                 }
337                 compiledReportPath = reportDirectory + reportBaseName + COMPILED_JASPER_REPORTS_EXTENSION;
338                 compiledReportPaths.add(compiledReportPath);
339     
340                 if (debug)
341                     debug(Messages.getString("JasperReport.DEBUG_COMPILED_REPORT_LOCATION", compiledReportPath)); //$NON-NLS-1$
342
// make sure the report is compiled
343
File JavaDoc compiledReportFile = new File JavaDoc(compiledReportPath);
344     
345                 // We compile if the compiled file doesn't exist, or the source is
346
// newer
347
if (!compiledReportFile.exists() || sourceFile.lastModified() > compiledReportFile.lastModified()) {
348                     if (debug)
349                         debug(Messages.getString("JasperReport.DEBUG_COMPILING_REPORT")); //$NON-NLS-1$
350
// We are currently ignoring any error conditions with compiled
351
// files
352
// that exist but aren't readable.
353

354                     // Use the jdt compiler
355
System.setProperty("jasper.reports.compiler.class", "net.sf.jasperreports.engine.design.JRJdtCompiler"); //$NON-NLS-1$ //$NON-NLS-2$
356

357                     // Compile the report design
358
try {
359                         JasperCompileManager.compileReportToFile(reportDefinitionPath, compiledReportPath);
360                     } catch (JRException jre) {
361                         error(Messages.getErrorString("JasperReport.ERROR_0010_UNABLE_TO_COMPILE", reportDefinitionPath, compiledReportPath), jre); //$NON-NLS-1$
362
return false;
363                     }
364                     if (debug)
365                         debug(Messages.getString("JasperReport.DEBUG_COMPILED_OK")); //$NON-NLS-1$
366
}
367             }
368             
369             // We have a compiled reports, ready to run.
370

371             // See if we have the require runtime report parameters
372
// Any non-system parameter in the report design that is marked
373
// as "is prompt for input" will be prompted for.
374
Map JavaDoc reportParameters = new HashMap JavaDoc();
375
376             // Load the compiled report design and get the parameters from it
377
if (debug)
378                 debug(Messages.getString("JasperReport.DEBUG_LOADING_REPORT_DESIGN")); //$NON-NLS-1$
379
JasperReport jrreport = null;
380             try {
381                 jrreport = (JasperReport) JRLoader.loadObject(compiledReportPath);
382             } catch (JRException jre) {
383                 error(Messages.getErrorString("JasperReport.ERROR_0012_REPORT_DESIGN_NO_LOADABLE", compiledReportPath), jre); //$NON-NLS-1$
384
return false;
385             }
386             
387             JRParameter[] jrparams = jrreport.getParameters();
388             if (debug)
389                 debug(Messages.getString("JasperReport.DEBUG_LOADED_DESIGN", Integer.toString(jrparams.length))); //$NON-NLS-1$
390

391             // Look for parameters marked as being prompted for
392
// TODO: Handle non-String type parameters
393
boolean needToPrompt = false;
394             for (int i = 0; i < jrparams.length; i++) {
395                 JRParameter param = jrparams[i];
396                 if (param.isSystemDefined())
397                     continue;
398                 String JavaDoc parameterName = param.getName();
399                 String JavaDoc parameterValue = null;
400                 if (isDefinedInput(parameterName)) {
401                     parameterValue = getInputStringValue(parameterName);
402                 }
403                 if (parameterValue != null && parameterValue.length() != 0) {
404                     // give the parameter value to the report engine...
405
if (debug)
406                         debug(Messages.getString("JasperReport.DEBUG_ADDING_PARAMETER", parameterName, parameterValue)); //$NON-NLS-1$
407
reportParameters.put(parameterName, parameterValue);
408                 }
409                 // Check for unspecified parameters that need to be specified
410
else if (param.isForPrompting()) {
411                     if (debug)
412                         debug(Messages.getString("JasperReport.DEBUG_PARAMETER_NEEDED", parameterName)); //$NON-NLS-1$
413
// see if we can prompt for this...
414
if (feedbackAllowed()) {
415
416                         IActionParameter paramParameter = getInputParameter(parameterName);
417                         if (paramParameter.getPromptStatus() != IActionParameter.PROMPT_PENDING) {
418                             String JavaDoc displayName = param.getDescription();
419                             if (displayName == null || displayName.trim().length() == 0)
420                                 displayName = parameterName;
421                             String JavaDoc defaultValue = ""; //$NON-NLS-1$
422
createFeedbackParameter(parameterName, displayName, "", defaultValue, true); //$NON-NLS-1$
423
}
424                         needToPrompt = true;
425                     }
426                 }
427             }
428
429             // If we have parameters to prompt for, have Pentaho create the
430
// parameter
431
// page for us.
432
if (needToPrompt) {
433                 // make sure the type parameter comes back to us...
434
// context.createFeedbackParameter( "type", "type",
435
// reportOutputType, false ); //$NON-NLS-1$ //$NON-NLS-1$
436
// //$NON-NLS-2$
437
// Isn't the parameter page always HTML?
438
setFeedbackMimeType("text/html"); //$NON-NLS-1$
439
return true;
440             }
441             else if (getRuntimeContext().isPromptPending() ) {
442                     return true;
443             }
444             allReportParameters.put(compiledReportPath, reportParameters);
445         }
446         
447         // Try to get the output from the action-sequence document.
448
// execute the report here...
449
OutputStream JavaDoc outputStream = getDefaultOutputStream();
450         if (isDefinedOutput(REPORT_OUTPUT)) {
451             outputStream = getOutputStream(REPORT_OUTPUT, mimeType, extension);
452         } else if (getOutputNames().size() == 1) {
453             String JavaDoc outputName = (String JavaDoc) getOutputNames().iterator().next();
454             IContentItem contentItem = getOutputContentItem(outputName);
455             contentItem.setMimeType(mimeType);
456             try {
457                 outputStream = contentItem.getOutputStream(getActionName());
458             } catch (Exception JavaDoc e) {
459             }
460         }
461         if (getOutputNames().size() == 0) {
462             // There was no output in the action-sequence document, so make a
463
// default
464
// outputStream.
465
warn(Messages.getString("Base.WARN_NO_OUTPUT_STREAM")); //$NON-NLS-1$
466
outputStream = getDefaultOutputStream();
467             if (outputStream != null) {
468                 setOutputMimeType(mimeType);
469             }
470         }
471         if (outputStream == null) {
472             error(Messages.getErrorString("JasperReport.ERROR_0013_OUTPUT_STREAM_INVALID")); //$NON-NLS-1$
473
return false;
474         }
475         Connection JavaDoc conn = getConnection();
476         if (conn == null)
477             return false;
478         try {
479             
480             String JavaDoc reportBaseName = new String JavaDoc();
481             List JavaDoc jasperPrintList = new ArrayList JavaDoc();
482
483             Iterator JavaDoc compiledReportPathIterator = compiledReportPaths.iterator();
484             
485             while(compiledReportPathIterator.hasNext()) {
486                 String JavaDoc compiledReportPath = (String JavaDoc) compiledReportPathIterator.next();
487                 
488                 // Fill reports
489
// TODO: Read reportParameters from HashMap
490
Map JavaDoc reportParameters = (Map JavaDoc) allReportParameters.get(compiledReportPath);
491                 JasperPrint jrprint = JasperFillManager.fillReport(compiledReportPath, reportParameters, conn);
492                 //jasperPrintList.add(JRLoader.loadObject(compiledReportPath));
493
jasperPrintList.add(jrprint);
494     
495                 // Get a configure exporter for the desired output format.
496
String JavaDoc lastReportBaseName = compiledReportPath;
497                 int extensionIdx = lastReportBaseName.lastIndexOf("."); //$NON-NLS-1$
498
if (extensionIdx > 0)
499                     lastReportBaseName = lastReportBaseName.substring(0, extensionIdx);
500                 
501                 reportBaseName = reportBaseName.concat(lastReportBaseName);
502             }
503             
504             JRExporter exporter = getExporter(reportOutputType, reportBaseName);
505             
506             // Reverse jasperPrintList order so first resource will appear as first report
507
List JavaDoc jasperPrintListReversed = new ArrayList JavaDoc();
508             for (int i = jasperPrintList.size() - 1; i >= 0; i--) {
509                 jasperPrintListReversed.add(jasperPrintList.get(i));
510             }
511             
512             // Set the filled report and output stream.
513
exporter.setParameter(JRExporterParameter.JASPER_PRINT_LIST, jasperPrintListReversed);
514             exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, outputStream);
515             
516             // Go!
517
exporter.exportReport();
518         } catch (JRException jre) {
519             error(Messages.getErrorString("JasperReport.ERROR_0014_REPORT_EXECUTION_FAILED"), jre); //$NON-NLS-1$
520
return false;
521         } finally {
522             try {
523                 conn.close();
524             } catch (SQLException JavaDoc ignored) {
525             }
526         }
527         return true;
528     }
529
530     public boolean init() {
531         // TODO any initialization you need to do before execution
532

533         return true;
534     }
535
536     public void done() {
537         // perform any cleanup necessary
538
}
539
540     private Connection JavaDoc getConnection() {
541         try {
542             // get the report settings
543
// String reportSetting1 = getProperty( "report-setting-1" );
544
// if( debug ) debug( "Running report with a setting of
545
// "+reportSetting1 );
546
String JavaDoc jndiUrl = getInputStringValue(StandardSettings.JNDI);
547             Connection JavaDoc conn = null;
548             if (jndiUrl != null) {
549                 DataSource JavaDoc ds = DatasourceHelper.getDataSourceFromJndi(jndiUrl);
550                 return ds.getConnection();
551             } else {
552                 String JavaDoc driver = getInputStringValue(StandardSettings.DRIVER);
553                 String JavaDoc connectString = getInputStringValue(StandardSettings.CONNECTION);
554                 String JavaDoc user = getInputStringValue(StandardSettings.USERID);
555                 String JavaDoc password = getInputStringValue(StandardSettings.PASSWORD);
556                 Class.forName(driver);
557                 conn = DriverManager.getConnection(connectString, user, password);
558             }
559             return conn;
560         } catch (ClassNotFoundException JavaDoc cnfe) {
561             error(Messages.getErrorString("JasperReport.ERROR_0015_JDBC_DRIVER_LOAD_FAILED")); //$NON-NLS-1$
562
} catch (SQLException JavaDoc se) {
563             error(Messages.getErrorString("JasperReport.ERROR_0016_DATABASE_CONNECTION_FAILED"), se); //$NON-NLS-1$
564
} catch (NamingException JavaDoc ne) {
565             error(Messages.getErrorString("JasperReport.ERROR_0016_DATABASE_CONNECTION_FAILED"), ne); //$NON-NLS-1$
566
}
567         return null;
568     }
569 }
570
Popular Tags