1 /**
2 *
3 */
4 package ar.com.jiji.kaya.reports;
5
6 import java.util.List;
7 import java.util.Map;
8
9 import javax.servlet.http.HttpServletResponse;
10
11 import net.sf.jasperreports.engine.JRDataSource;
12 import ognl.Ognl;
13 import ognl.OgnlException;
14
15 import org.apache.tapestry.request.ResponseOutputStream;
16
17 import ar.com.jiji.kaya.utils.ValidateUtils;
18
19 /**
20 * TODO: documentar y hacer tests
21 *
22 * @author lparra
23 *
24 */
25 public class ReportsFacade {
26
27 public static final String REPORT_SPECS = "reports";
28
29 private ReportSpecManager specManager;
30
31 /**
32 * Crea una instancia del facade. Lee la definicion de los reportes desde el
33 * resource en el classpath "/reports.properties".
34 *
35 * @throws ReportException
36 * @see #ReportsFacade(String)
37 */
38 public ReportsFacade() throws ReportException {
39 this(REPORT_SPECS);
40 }
41
42 /**
43 * Crea una instancia del facade.
44 *
45 * @param resource
46 * El nombre del resource en el classpath que tiene la definicion
47 * de los reportes.
48 * @throws ReportException
49 * @see ReportSpecManager
50 */
51 public ReportsFacade(String resource) throws ReportException {
52 specManager = new ReportSpecManager(resource);
53 }
54
55 protected JRDataSource getDataSource(ReportSpec spec, Map ctx)
56 throws ReportException {
57 List data = getData(spec, ctx);
58
59 ReportDSFactory dsFactory = AbstractReportDSFactory.getFactory();
60 return dsFactory.getDataSource(data, spec.getColumns());
61 }
62
63 protected List getData(ReportSpec spec, Map ctx) throws ReportException {
64 List result = null;
65 ValidateUtils.notNull(spec);
66 Object ognl = spec.getDsExtractor();
67
68 try {
69 Object aux = Ognl.getValue(ognl, ctx, (Object) null);
70 if (aux != null && !(aux instanceof List))
71 throw new ReportException("Expected List, but "
72 + aux.getClass() + " returned");
73 result = (List) aux;
74 } catch (OgnlException e) {
75 throw new ReportException(e);
76 }
77
78 return result;
79 }
80
81
82 public void export(String reportName, Map dsArgs, Map params,
83 HttpServletResponse res, ResponseOutputStream output,
84 ReportFormat format, boolean download) throws ReportException {
85
86 ReportSpec report = specManager.get(reportName);
87 if (report == null)
88 throw new ReportException("Report " + reportName + " not found");
89
90 export(report, dsArgs, params, res, output, format, download);
91 }
92
93
94 public void export(ReportSpec report, Map dsArgs, Map params,
95 HttpServletResponse res, ResponseOutputStream output,
96 ReportFormat format, boolean download) throws ReportException {
97 JRDataSource ds = getDataSource(report, dsArgs);
98
99 if (download) {
100 res.addHeader("Content-Disposition", "attachment; filename=\""
101 + report.getDownloadName() + format.getExtension() + "\"");
102 }
103 output.setContentType(format.getMimeType());
104
105 JasperFacade.export(format, report.getLocation(), params, ds, output);
106 }
107 }