KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > openi > web > controller > RDBMSController


1 /*********************************************************************************
2  * The contents of this file are subject to the OpenI Public License Version 1.0
3  * ("License"); You may not use this file except in compliance with the
4  * License. You may obtain a copy of the License at
5  * http://www.openi.org/docs/LICENSE.txt
6  *
7  * Software distributed under the License is distributed on an "AS IS" basis,
8  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
9  * the specific language governing rights and limitations under the License.
10  *
11  * The Original Code is: OpenI Open Source
12  *
13  * The Initial Developer of the Original Code is Loyalty Matrix, Inc.
14  * Portions created by Loyalty Matrix, Inc. are
15  * Copyright (C) 2005 Loyalty Matrix, Inc.; All Rights Reserved.
16  *
17  * Contributor(s): ______________________________________.
18  *
19  ********************************************************************************/

20 package org.openi.web.controller;
21
22 import net.sf.jasperreports.engine.JRExporter;
23 import net.sf.jasperreports.engine.JRExporterParameter;
24 import net.sf.jasperreports.engine.JRParameter;
25 import net.sf.jasperreports.engine.JRRuntimeException;
26 import net.sf.jasperreports.engine.JasperCompileManager;
27 import net.sf.jasperreports.engine.JasperExportManager;
28 import net.sf.jasperreports.engine.JasperFillManager;
29 import net.sf.jasperreports.engine.JasperPrint;
30 import net.sf.jasperreports.engine.JasperReport;
31 import net.sf.jasperreports.engine.export.JRCsvExporter;
32 import net.sf.jasperreports.engine.export.JRHtmlExporter;
33 import net.sf.jasperreports.engine.export.JRHtmlExporterParameter;
34 import net.sf.jasperreports.engine.export.JRPdfExporter;
35 import net.sf.jasperreports.engine.export.JRRtfExporter;
36 import net.sf.jasperreports.engine.export.JRXlsExporter;
37 import net.sf.jasperreports.engine.export.JRXlsExporterParameter;
38 import net.sf.jasperreports.engine.export.JRXmlExporter;
39 import net.sf.jasperreports.engine.util.JRLoader;
40 import net.sf.jasperreports.j2ee.servlets.ImageServlet;
41
42 import org.apache.log4j.Logger;
43 import org.openi.project.ProjectContext;
44 import org.springframework.web.servlet.ModelAndView;
45 import org.springframework.web.servlet.mvc.AbstractController;
46 import java.io.*;
47 import java.net.URL JavaDoc;
48 import java.sql.Connection JavaDoc;
49 import java.sql.DriverManager JavaDoc;
50 import java.text.DateFormat JavaDoc;
51 import java.util.Enumeration JavaDoc;
52 import java.util.HashMap JavaDoc;
53 import java.util.Map JavaDoc;
54
55 import javax.activation.FileTypeMap JavaDoc;
56 import javax.servlet.http.HttpServletRequest JavaDoc;
57 import javax.servlet.http.HttpServletResponse JavaDoc;
58 import javax.servlet.http.HttpSession JavaDoc;
59 import javax.xml.transform.Source JavaDoc;
60 import javax.xml.transform.stream.StreamSource JavaDoc;
61
62 import org.openi.project.JdbcDatasource;
63 import org.openi.xml.XMLTransformer;
64
65 /**
66  * @author Dipendra Pokhrel <br>
67  * @version $Revision: 1.3.2.11 $ $Date: 2006/05/19 12:48:56 $ <br>
68  *
69  * Spring controller to render jasper report
70  *
71  */

72 public class RDBMSController extends AbstractController {
73     private static Logger logger = Logger.getLogger(RDBMSController.class);
74     
75     private static final String JavaDoc TYPE_PDF = "pdf";
76     private static final String JavaDoc TYPE_XLS = "xls";
77     private static final String JavaDoc TYPE_RTF = "rtf";
78     private static final String JavaDoc TYPE_XML = "xml";
79     private static final String JavaDoc TYPE_CSV = "csv";
80     
81     private ProjectContext projectContext = null;
82     
83     /**
84      * Process the request and return a ModelAndView object which the
85      * DispatcherServlet will render.
86      *
87      * @param httpServletRequest
88      * HttpServletRequest
89      * @param httpServletResponse
90      * HttpServletResponse
91      * @return ModelAndView
92      * @throws Exception
93      */

94     protected ModelAndView handleRequestInternal(HttpServletRequest JavaDoc request,
95             HttpServletResponse JavaDoc response) throws Exception JavaDoc {
96             
97         Map JavaDoc model;
98         HttpSession JavaDoc session;
99         
100         if(request.getParameter("Cancel") != null )
101         {
102             response.sendRedirect("splash.htm");
103             return null;
104         }
105         
106         try {
107             model = new HashMap JavaDoc();
108             
109             session = request.getSession();
110             
111             String JavaDoc content = request.getParameter("jrxml");
112             
113             // if content is available
114

115             projectContext = (ProjectContext) session
116                                 .getAttribute("projectContext");
117             
118             String JavaDoc jrxmlFile = null;
119             String JavaDoc jasperFile = null;
120             
121             if (content != null) {
122                 JdbcDatasource datasource = null;
123                 jrxmlFile = projectContext.getProjectDirectory() + "/" + content;
124                 if (content.endsWith(".jrxml")
125                         && request.getParameter("Submit") == null
126                         && request.getParameter("Cancel") == null) {
127                     
128                     if (getDatasource(content) == null) {
129                         throw new Exception JavaDoc(
130                         "No datasource available for current jasper report");
131                     } else {
132                         
133                         logger.debug("compiling jasper file :" + jrxmlFile);
134                         
135                         jasperFile = compileJasperTemplate(jrxmlFile);
136                         //reset jasper print object
137

138                         String JavaDoc xslFile = request.getRealPath("WEB-INF/openi/jasper_paramui.xsl");
139                         String JavaDoc html = getParamsHTML(jrxmlFile, xslFile).trim();
140                         request.getSession().setAttribute("jasperFile", jasperFile);
141                         request.getSession().setAttribute("jrxmlFile", content);
142                         request.getSession().setAttribute(
143                                 ImageServlet.DEFAULT_JASPER_PRINT_SESSION_ATTRIBUTE, null);
144                         
145                         if(html!=null && !"".equals(html)) {
146                             model.put("done", Boolean.FALSE);
147                             model.put("jasperOutput", html);
148                         }
149                     }
150                 }
151             }
152             if (model.get("jasperOutput") == null) {
153                 model.put("done", Boolean.TRUE);
154                 
155                 if(request.getSession().getAttribute(ImageServlet.DEFAULT_JASPER_PRINT_SESSION_ATTRIBUTE) != null
156                         && request.getParameter("export")!= null) {
157                     
158                     String JavaDoc exportType = request.getParameter("exportType");
159                     JasperPrint jasperPrint = null;
160                     jasperPrint = (JasperPrint)request.getSession().getAttribute(ImageServlet.DEFAULT_JASPER_PRINT_SESSION_ATTRIBUTE);
161                     String JavaDoc fileName = jasperPrint.getName();
162                     
163                     if(fileName == null || "".equals(fileName))
164                         fileName = "report." + exportType;
165                     else
166                         fileName = fileName + "." + exportType;
167                     
168                     FileTypeMap JavaDoc map = FileTypeMap.getDefaultFileTypeMap();
169                     response.setContentType(map.getContentType(fileName));
170                     response.setHeader("Pragma", "no-cache");
171                     response.setHeader("Content-Disposition",
172                             "attachement; filename=\"" + fileName + "\"");
173                     try {
174                         exportReport(jasperPrint, response.getOutputStream(), exportType, -1);
175                     } catch(Throwable JavaDoc e) {
176                         logger.error("An error occured while exporting report", e);
177                     }
178                     return null;
179                    
180                 } else {
181                     if(request.getParameter("Submit") !=null )
182                         request.getSession().setAttribute(ImageServlet.DEFAULT_JASPER_PRINT_SESSION_ATTRIBUTE, null);
183                     writeJasperOutput(model, request);
184                 }
185             }
186             return new ModelAndView("rdbmsView", "model", model);
187         } catch (Exception JavaDoc e) {
188             logger.error("Exception:", e);
189             throw e;
190         }
191     }
192     
193     private String JavaDoc getParamsHTML(String JavaDoc jasperFile, String JavaDoc xslFile)
194             throws Exception JavaDoc {
195         Source JavaDoc xml = new StreamSource JavaDoc(new File(jasperFile));
196         Source JavaDoc xslt = new StreamSource JavaDoc(new File(xslFile));
197         return XMLTransformer.transform(xslt, xml);
198     }
199     
200     private JdbcDatasource getDatasource(String JavaDoc content) {
201         JdbcDatasource datasource = projectContext.getJasperDatasource(content);
202         if (datasource == null) {
203             datasource =
204                 (JdbcDatasource) projectContext.getJdbcDatasourceMap().get("jasper");
205         }
206         return datasource;
207     }
208     /**
209      * export report to specified format
210      * @param jasperPrint JasperPrint reference
211      * @param writer writer to export the report
212      * @param exportFormat export format
213      * @param pageNo page number to be exported. '-1' for all pages
214      * @throws Exception
215      */

216     private void exportReport(JasperPrint jasperPrint,
217                                 OutputStream outstream,
218                                 String JavaDoc exportFormat,
219                                 int pageNo) throws Exception JavaDoc{
220         
221         JRExporter exporter = null;
222         if (TYPE_PDF.equals(exportFormat)) {
223             exporter = new JRPdfExporter();
224         } else if(TYPE_XLS.equals(exportFormat)) {
225             exporter = new JRXlsExporter();
226             exporter.setParameter(JRXlsExporterParameter.IS_ONE_PAGE_PER_SHEET, Boolean.TRUE);
227         } else if(TYPE_RTF.equals(exportFormat)) {
228             exporter = new JRRtfExporter();
229         } else if(TYPE_XML.equals(exportFormat)) {
230             exporter = new JRXmlExporter();
231         } else if(TYPE_CSV.equals(exportFormat)) {
232             exporter = new JRCsvExporter();
233         } else {
234             throw new Exception JavaDoc("unknown export format '" + exportFormat + "'");
235         }
236         exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
237     
238         exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, outstream);
239         
240         if(pageNo != -1)
241             exporter.setParameter(JRExporterParameter.PAGE_INDEX, new Integer JavaDoc(pageNo));
242         exporter.exportReport();
243         
244     }
245     
246     /**
247      * loads, fills and renders compiled jasper report
248      * @param model
249      * @param request
250      * @param datasource
251      * @throws Exception
252      */

253     private void writeJasperOutput(Map JavaDoc model,
254                 HttpServletRequest JavaDoc request)
255                 throws Exception JavaDoc {
256         
257         JasperPrint jasperPrint =
258             (JasperPrint) request.getSession().getAttribute(
259                     ImageServlet.DEFAULT_JASPER_PRINT_SESSION_ATTRIBUTE);
260         
261         if(jasperPrint != null
262                 && "true".equals(request.getParameter("reload")))
263             jasperPrint = null;
264         
265         String JavaDoc jrxmlFile = (String JavaDoc)request.getSession().getAttribute("jrxmlFile");
266         String JavaDoc jasperFile = (String JavaDoc)request.getSession().getAttribute("jasperFile");
267         
268         if(jrxmlFile == null || jasperFile == null) {
269             throw new Exception JavaDoc("Invalid request");
270         }
271         
272         JdbcDatasource datasource = getDatasource(jrxmlFile);
273         //set full path of jrxml file
274
jrxmlFile = projectContext.getProjectDirectory() + "/" + jrxmlFile;
275         
276         if (jasperPrint == null
277                 || "true".equals(request.getParameter("reload"))) {
278             File reportFile = new File(jasperFile);
279             if (!reportFile.exists())
280                 throw new JRRuntimeException("File '" + jasperFile + "' not found.");
281             
282             JasperReport jasperReport =
283                 (JasperReport) JRLoader.loadObject(reportFile.getPath());
284             
285             Map JavaDoc paramMap = new HashMap JavaDoc();
286             JRParameter[] jrparams = jasperReport.getParameters();
287             
288             for(int i=0; i < jrparams.length; i++) {
289                 if(jrparams[i].isForPrompting()) {
290                     paramMap.put(jrparams[i].getName(),jrparams[i]);
291                 }
292             }
293             
294             Map JavaDoc parameters = new HashMap JavaDoc();
295             parameters.put(JRParameter.REPORT_CLASS_LOADER,
296                     new CustomClassLoader(new File(jrxmlFile).getParentFile().getCanonicalPath() + "/"));
297             
298             
299             if(request.getParameter("Submit") != null) {
300                 jasperFile = request.getParameter("jasperFile");
301                 Enumeration JavaDoc keysEnum = request.getParameterNames();
302                 while (keysEnum.hasMoreElements()) {
303                     String JavaDoc key = (String JavaDoc)keysEnum.nextElement();
304                     if(paramMap.containsKey(key)) {
305                         String JavaDoc val = request.getParameterValues(key)[0];
306                         JRParameter jrParam = (JRParameter)paramMap.get(key);
307                         //skip if there is default value that has not been changed by user
308
if(val != null
309                                 && !"".equals(val)
310                                 && jrParam.getDefaultValueExpression()!= null
311                                 && val.equals(jrParam.getDefaultValueExpression().getText()))
312                             continue;
313                         //set new value for the parameter
314
try {
315                             parameters.put(key, convertParameterType(val, jrParam.getValueClassName()));
316                         } catch(Exception JavaDoc e) {
317                             throw new
318                                 Exception JavaDoc("Could not convert parameter '"
319                                         + key + "' into type '"
320                                         + jrParam.getValueClassName() + "'", e);
321                         }
322                     }
323                 }
324             }
325             
326             if(datasource == null ) {
327                 String JavaDoc content = request.getParameter("jrxml");
328                 datasource = projectContext.getJasperDatasource(content);
329                 if (datasource == null) {
330                     datasource = (JdbcDatasource) projectContext
331                     .getJdbcDatasourceMap().get("jasper");
332                 }
333                 
334                 if (datasource == null) {
335                     throw new Exception JavaDoc(
336                     "No datasource available for current jasper report");
337                 }
338             }
339             
340             Connection JavaDoc connection = null;
341             
342             try {
343                 // Properties properties = context.getJdbcDataSource();
344
logger.info("Loading jdbc driver "
345                         + datasource.getDriverClassName());
346                 Class.forName(datasource.getDriverClassName());
347                 logger
348                 .info("Getting connection for url "
349                         + datasource.getUrl());
350                 connection = DriverManager.getConnection(datasource.getUrl(),
351                         datasource.getUsername(), datasource.getPassword());
352             } catch (ClassNotFoundException JavaDoc ex) {
353                 throw new ClassNotFoundException JavaDoc("Driver class not found", ex);
354             } catch (Exception JavaDoc ex) {
355                 throw ex;
356             }
357             
358             jasperPrint = JasperFillManager.fillReport(jasperReport,
359                     parameters, connection);
360             
361             request.getSession().setAttribute(
362                     ImageServlet.DEFAULT_JASPER_PRINT_SESSION_ATTRIBUTE,
363                     jasperPrint);
364             
365         }
366         
367         
368         JRHtmlExporter exporter = new JRHtmlExporter();
369         
370         int pageIndex = 0;
371         int lastPageIndex = 0;
372         if (jasperPrint.getPages() != null) {
373             lastPageIndex = jasperPrint.getPages().size() - 1;
374         }
375         
376         String JavaDoc pageStr = request.getParameter("page");
377         try {
378             pageIndex = Integer.parseInt(pageStr);
379         } catch (Exception JavaDoc e) {
380         }
381         
382         if (pageIndex < 0) {
383             pageIndex = 0;
384         }
385         
386         if (pageIndex > lastPageIndex) {
387             pageIndex = lastPageIndex;
388         }
389         
390         StringBuffer JavaDoc sbuffer = new StringBuffer JavaDoc();
391         
392         exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
393         exporter
394         .setParameter(JRExporterParameter.OUTPUT_STRING_BUFFER, sbuffer);
395         exporter.setParameter(JRHtmlExporterParameter.IMAGES_URI,
396         "servlets/image?image=");
397         exporter.setParameter(JRExporterParameter.PAGE_INDEX, new Integer JavaDoc(
398                 pageIndex));
399         exporter.setParameter(JRHtmlExporterParameter.HTML_HEADER, "");
400         exporter.setParameter(JRHtmlExporterParameter.BETWEEN_PAGES_HTML, "");
401         exporter.setParameter(JRHtmlExporterParameter.HTML_FOOTER, "");
402         
403         if(jasperPrint.getPages().size() != 0)
404             exporter.exportReport();
405         
406         model.put("jasperOutput", sbuffer.toString());
407         model.put("pageIndex", new Integer JavaDoc(pageIndex));
408         model.put("lastPageIndex", new Integer JavaDoc(lastPageIndex));
409         
410     }
411     
412     private Object JavaDoc convertParameterType(String JavaDoc paramVal, String JavaDoc type)
413             throws Exception JavaDoc {
414         if("java.lang.String".equals(type)) {
415             return paramVal;
416         } else if("java.lang.Integer".equals(type)) {
417             return Integer.valueOf(paramVal);
418         } else if("java.lang.Float".equals(type)) {
419             return Float.valueOf(paramVal);
420         } else if("java.lang.Short".equals(type)) {
421             return Short.valueOf(paramVal);
422         } else if("java.lang.Double".equals(type)) {
423             return Double.valueOf(paramVal);
424         } else if("java.lang.Long".equals(type)) {
425             return Long.valueOf(paramVal);
426         } else if("java.lang.Byte".equals(type)) {
427             return Byte.valueOf(paramVal);
428         } else if("java.util.Date".equals(type)) {
429             return DateFormat.getInstance().parse(paramVal);
430         } else if("java.lang.Boolean".equals(type)) {
431             return Boolean.valueOf(paramVal);
432         }
433         return paramVal;
434     }
435     
436     /**
437      * compiles jasper report into temp location
438      * @param file
439      * @return filemname with full path of the compiled report
440      * @throws Exception
441      */

442     private String JavaDoc compileJasperTemplate(String JavaDoc file) throws Exception JavaDoc {
443         
444         String JavaDoc tmpPath = getJasperTempDir();
445         File tmpDir = new File(tmpPath);
446         if(!tmpDir.exists()) {
447             tmpDir.mkdir();
448         }
449         File jrxmlFile = new File(file);
450         
451         String JavaDoc jasperFile = tmpPath + getNamePart(jrxmlFile.getName()) + ".jasper";
452         
453         logger.debug("compiling report : " + file );
454         
455         JasperCompileManager.compileReportToFile(file, jasperFile);
456         
457         return jasperFile;
458     }
459     
460     /**
461      * returns the name part of the file - not extension
462      * @param fileName
463      * @return
464      */

465     private String JavaDoc getNamePart(String JavaDoc fileName) {
466         int index = fileName.lastIndexOf(".");
467         if(index != -1) {
468             fileName = fileName.substring(0, index);
469         }
470         return fileName;
471     }
472     
473     /**
474      * class loader required to resolve subreport path for jasper filling.
475      * This class is also resposible to compile the sub report if found any
476      * @author Dipendra Pokhrel
477      *
478      */

479     class CustomClassLoader extends ClassLoader JavaDoc {
480         
481         String JavaDoc baseDir = null;
482         /**
483          *
484          * @param baseDir base directory of jrxml file
485          */

486         public CustomClassLoader(String JavaDoc baseDir) {
487             this.baseDir = baseDir;
488         }
489         /**
490          * do care for .jasper resource. If requested, it compiles and then constructs its path
491          * based on temp location to make jasper engine happy
492          */

493         public URL JavaDoc getResource(String JavaDoc name) {
494             if(name.endsWith(".jasper")) {
495                 String JavaDoc jrxml = name.substring(0, name.length()-6) + "jrxml";
496                 File jrxmlFile = new File(baseDir + jrxml);
497                 
498                 if(!jrxmlFile.exists())
499                     throw new RuntimeException JavaDoc("Could not find subreport '"+ jrxml + "'");
500                 logger.debug("found sub report :" + name);
501                 
502                 try {
503                     compileJasperTemplate(jrxmlFile.getCanonicalPath());
504                     return new File(getJasperTempDir() + name).toURL();
505                 } catch(Exception JavaDoc e) {
506                     throw new RuntimeException JavaDoc("An error occured while compiling sub report '" + name + "'", e);
507                 }
508             }
509             return super.getResource(name);
510         }
511         
512     }
513     
514     /**
515      * return temp jasper location to compile jrxml
516      * @return
517      */

518     private String JavaDoc getJasperTempDir() {
519         String JavaDoc tmpPath = System.getProperty("java.io.tmpdir");
520         tmpPath = tmpPath.replace('\\','/');
521         
522         if(tmpPath.endsWith("/"))
523             tmpPath = tmpPath + "jasper/";
524         else
525             tmpPath = tmpPath + "/jasper/";
526         return tmpPath;
527     }
528 }
529
Popular Tags