DisplayReportAction.java

  1. /*
  2.  * This software was designed and created by Jason Carroll.
  3.  * Copyright (c) 2002, 2003, 2004 Jason Carroll.
  4.  * The author can be reached at jcarroll@cowsultants.com
  5.  * ITracker website: http://www.cowsultants.com
  6.  * ITracker forums: http://www.cowsultants.com/phpBB/index.php
  7.  *
  8.  * This program is free software; you can redistribute it and/or modify
  9.  * it only under the terms of the GNU General Public License as published by
  10.  * the Free Software Foundation; either version 2 of the License, or
  11.  * (at your option) any later version.
  12.  *
  13.  * This program is distributed in the hope that it will be useful,
  14.  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15.  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  16.  * GNU General Public License for more details.
  17.  */

  18. package org.itracker.web.actions.report;

  19. import net.sf.jasperreports.engine.*;
  20. import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
  21. import net.sf.jasperreports.engine.export.JRCsvExporter;
  22. import net.sf.jasperreports.engine.export.JRHtmlExporter;
  23. import net.sf.jasperreports.engine.export.JRPdfExporter;
  24. import net.sf.jasperreports.engine.export.JRXlsExporter;
  25. import org.apache.commons.beanutils.PropertyUtils;
  26. import org.apache.commons.lang.StringUtils;
  27. import org.apache.log4j.Logger;
  28. import org.apache.struts.action.*;
  29. import org.itracker.ReportException;
  30. import org.itracker.core.resources.ITrackerResourceBundle;
  31. import org.itracker.core.resources.ITrackerResources;
  32. import org.itracker.model.*;
  33. import org.itracker.model.util.ReportUtilities;
  34. import org.itracker.services.ConfigurationService;
  35. import org.itracker.services.IssueService;
  36. import org.itracker.services.ReportService;
  37. import org.itracker.web.actions.base.ItrackerBaseAction;
  38. import org.itracker.web.util.*;

  39. import javax.servlet.ServletException;
  40. import javax.servlet.ServletOutputStream;
  41. import javax.servlet.http.HttpServletRequest;
  42. import javax.servlet.http.HttpServletResponse;
  43. import javax.servlet.http.HttpSession;
  44. import java.io.ByteArrayInputStream;
  45. import java.io.File;
  46. import java.io.IOException;
  47. import java.text.SimpleDateFormat;
  48. import java.util.*;


  49. public class DisplayReportAction extends ItrackerBaseAction {
  50.     private static final Logger log = Logger.getLogger(DisplayReportAction.class);

  51.     public DisplayReportAction() {
  52.     }

  53.     public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  54.         ActionMessages errors = new ActionMessages();

  55.         try {
  56.             HttpSession session = request.getSession(false);
  57.             Locale userLocale = LoginUtilities.getCurrentLocale(request);

  58.             List<Issue> reportingIssues = new ArrayList<Issue>();
  59.             String reportType = (String) PropertyUtils.getSimpleProperty(form, "type");
  60.             log.info("execute: report type was " + reportType);

  61.             final Integer[] projectIds = (Integer[]) PropertyUtils.getSimpleProperty(form, "projectIds");
  62.             final IssueService issueService = ServletContextUtils.getItrackerServices().getIssueService();
  63.             final ConfigurationService configurationService = ServletContextUtils.getItrackerServices().getConfigurationService();
  64.             final ReportService reportService = ServletContextUtils.getItrackerServices().getReportService();

  65.             if ("all".equalsIgnoreCase(reportType)) {
  66.                 // Export all of the issues in the system
  67.                 User currUser = (User) session.getAttribute(Constants.USER_KEY);
  68.                 if (!currUser.isSuperUser()) {
  69.                     errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("itracker.web.error.unauthorized"));
  70.                     throw new ReportException();
  71.                 }
  72.                 reportingIssues = issueService.getAllIssues();
  73.                 Collections.sort(reportingIssues, Issue.ID_COMPARATOR);
  74.             } else if ("project".equalsIgnoreCase(reportType)) {
  75.                 if (projectIds != null && projectIds.length > 0) {
  76.                     // This wasn't a regular search.  So instead, take all the selected projects and find all the
  77.                     // issues for them, check which ones the user can see, and then create a new array of issues
  78.                     List<Issue> reportDataList = new ArrayList<>();

  79.                     List<Issue> issues;
  80.                    for (Integer projectId : projectIds) {
  81.                       issues = issueService.getIssuesByProjectId(projectId);
  82.                       for (Issue issue: issues) {
  83.                          if (LoginUtilities.canViewIssue(issue))
  84.                              reportDataList.add(issue);

  85.                       }
  86.                    }
  87.                     reportingIssues = reportDataList;
  88.                     Collections.sort(reportingIssues, Issue.ID_COMPARATOR);

  89.                 } else {
  90.                     throw new ReportException("", "itracker.web.error.projectrequired");
  91.                 }
  92.             } else {
  93.                 // This must be a regular search, look for a search query result.
  94.                 // must be loaded with current session (lazy loading)
  95.                 IssueSearchQuery isqm = (IssueSearchQuery) session.getAttribute(Constants.SEARCH_QUERY_KEY);
  96.                 for (Issue issue : isqm.getResults()) {
  97.                     reportingIssues.add(issueService.getIssue(issue.getId()));
  98.                 }
  99.             }

  100.             log.debug("Report data contains " + reportingIssues.size() + " elements.");

  101.             if (reportingIssues.isEmpty()) {
  102.                 errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("itracker.web.error.noreportdata"));
  103.                 throw new ReportException();
  104.             }

  105.             Integer reportId = (Integer) PropertyUtils.getSimpleProperty(form, "reportId");
  106.             String reportOutput = (String) PropertyUtils.getSimpleProperty(form, "reportOutput");
  107.             if (null == reportId) {
  108.                 log.debug("Invalid report id: " + reportId + " requested.");
  109.                 errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("itracker.web.error.invalidreport"));
  110.             } else if (ReportUtilities.REPORT_EXPORT_XML == reportId.intValue()) {
  111.                 log.debug("Issue export requested.");

  112.                 SystemConfiguration config = configurationService.getSystemConfiguration(ImportExportTags.EXPORT_LOCALE);

  113.                 if (!ImportExportUtilities.exportIssues(reportingIssues, config, request, response)) {
  114.                     errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("itracker.web.error.system"));
  115.                 } else {
  116.                    return null;
  117.                 }
  118.             } else if (reportId.intValue() > 0) {
  119.                 log.debug("Defined report (" + reportId + ") requested.");

  120.                 Report reportModel = reportService.getReportDAO().findByPrimaryKey(reportId);

  121.                 log.debug("Report " + reportModel + " found.");

  122.                 Project project = null;
  123.                 log.debug("Processing report.");
  124.                 outputReport(reportingIssues, project, reportModel, userLocale, reportOutput, response);
  125.                 return null;

  126.             }
  127.         } catch (ReportException re) {
  128.             log.debug("Error for report", re);
  129.             if (!StringUtils.isEmpty(re.getErrorKey())) {
  130.                 errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(re.getErrorKey()));
  131.             } else {
  132.                 errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("itracker.web.error.details", re.getMessage()));
  133.             }

  134.         } catch (Exception e) {
  135.             log.warn("Error in report processing: " + e.getMessage(), e);
  136.             errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("itracker.web.error.system"));
  137.             errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("itracker.web.error.details", e.getMessage()));
  138.         }

  139.         if (!errors.isEmpty()) {
  140.             saveErrors(request, errors);
  141.         }

  142.         return mapping.findForward("error");
  143.     }





  144.     private static JasperPrint generateReport(Report report,
  145.                                        Map<String, Object> parameters, JRDataSource datasource)
  146.     throws ReportException{
  147.         try {

  148.             JasperReport jasperReport = JasperCompileManager.compileReport(new ByteArrayInputStream(report.getFileData()));
  149.             JasperPrint jasperPrint = JasperFillManager.fillReport(
  150.                     jasperReport,
  151.                     parameters,
  152.                     datasource);


  153.             return jasperPrint;
  154.         } catch (JRException e) {
  155.             throw new ReportException(e);
  156.         }

  157.     }

  158.     /**
  159.      *
  160.      */
  161.     public static void outputReport(List<Issue> reportDataArray, Project project, Report report,
  162.                           Locale userLocale, String reportOutput,
  163.                           HttpServletResponse response) throws ReportException {

  164.         try {
  165.             // hack, we have to find a more structured way to support
  166.             // various types of queries
  167.             final JRBeanCollectionDataSource beanCollectionDataSource = new JRBeanCollectionDataSource(
  168.                     reportDataArray);

  169.             final Map<String, Object> parameters = new HashMap<String, Object>();
  170.             String reportTitle = report.getName();
  171.             if (project != null) {
  172.                 reportTitle += " - " + project.getName();
  173.                 if (report.getNameKey() != null) {
  174.                     reportTitle = ITrackerResources.getString(report.getNameKey(), project.getName());
  175.                 }
  176.             } else if (report.getNameKey() != null) {
  177.                 reportTitle = ITrackerResources.getString(report.getNameKey());
  178.             }
  179.             parameters.put("ReportTitle", reportTitle);
  180.             parameters.put("BaseDir", new File("."));
  181.             parameters.put("REPORT_LOCALE", userLocale);
  182.             parameters.put("REPORT_RESOURCE_BUNDLE", ITrackerResourceBundle.getBundle(userLocale));

  183.             final JasperPrint jasperPrint = generateReport(report, parameters,
  184.                     beanCollectionDataSource);


  185.             final ServletOutputStream out = response.getOutputStream();
  186.             final JRExporter x;
  187.             if (ReportUtilities.REPORT_OUTPUT_PDF.equals(reportOutput)) {

  188.                 response.setHeader("Content-Type", "application/pdf");
  189.                 response.setHeader("Content-Disposition", "attachment; filename=\"" + report.getName()
  190.                         + new SimpleDateFormat("-yyyy-MM-dd").format(new Date())
  191.                         + ".pdf\"");
  192.                 x = new JRPdfExporter();

  193.             } else if (ReportUtilities.REPORT_OUTPUT_XLS.equals(reportOutput)) {
  194.                 response.setHeader("Content-Type", "application/xls");
  195.                 response.setHeader("Content-Disposition", "attachment; filename=\"" + report.getName()
  196.                            + new SimpleDateFormat("-yyyy-MM-dd").format(new Date())
  197.                            + ".xls\"");
  198.                 x = new JRXlsExporter();

  199.             } else if (ReportUtilities.REPORT_OUTPUT_CSV.equals(reportOutput)) {

  200.                 response.setHeader("Content-Type", "text/csv");
  201.                 response.setHeader("Content-Disposition", "attachment; filename=\"" + report.getName()
  202.                         + new SimpleDateFormat("-yyyy-MM-dd").format(new Date())
  203.                         + ".csv\"");
  204.                 x = new JRCsvExporter();

  205.             } else if (ReportUtilities.REPORT_OUTPUT_HTML.equals(reportOutput)) {
  206.                 response.setHeader("Content-Type", "text/html");
  207.                 response.setHeader("Content-Disposition", "attachment; filename=\"" + report.getName()
  208.                         + new SimpleDateFormat("-yyyy-MM-dd").format(new Date())
  209.                         + ".html\"");
  210.                 x = new JRHtmlExporter();

  211.             } else {
  212.                 log.error("Invalid report output format: " + reportOutput);
  213.                 throw new ReportException("Invalid report type.", "itracker.web.error.invalidreportoutput");
  214.             }
  215.             x.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
  216.             x.setParameter(JRExporterParameter.OUTPUT_STREAM, out);

  217.             x.exportReport();

  218.             out.flush();
  219.             out.close();
  220.         } catch (JRException e) {
  221.             throw new ReportException(e);
  222.         } catch (IOException e) {
  223.             throw new ReportException(e);
  224.         }

  225.     }

  226. }
  227.