Reports: Use quickFind.
[online-glom:gwt-glom.git] / src / main / java / org / glom / web / server / ReportGenerator.java
1 /*
2  * Copyright (C) 2012 Openismus GmbH
3  *
4  * This file is part of GWT-Glom.
5  *
6  * GWT-Glom is free software: you can redistribute it and/or modify it
7  * under the terms of the GNU Lesser General Public License as published by the
8  * Free Software Foundation, either version 3 of the License, or (at your
9  * option) any later version.
10  *
11  * GWT-Glom is distributed in the hope that it will be useful, but WITHOUT
12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License
14  * for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public License
17  * along with GWT-Glom.  If not, see <http://www.gnu.org/licenses/>.
18  */
19
20 package org.glom.web.server;
21
22 import java.io.ByteArrayOutputStream;
23 import java.sql.Connection;
24 import java.util.HashMap;
25
26 import net.sf.jasperreports.engine.JRException;
27 import net.sf.jasperreports.engine.JasperCompileManager;
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.design.JRDesignBand;
32 import net.sf.jasperreports.engine.design.JRDesignExpression;
33 import net.sf.jasperreports.engine.design.JRDesignField;
34 import net.sf.jasperreports.engine.design.JRDesignGroup;
35 import net.sf.jasperreports.engine.design.JRDesignLine;
36 import net.sf.jasperreports.engine.design.JRDesignQuery;
37 import net.sf.jasperreports.engine.design.JRDesignSection;
38 import net.sf.jasperreports.engine.design.JRDesignStaticText;
39 import net.sf.jasperreports.engine.design.JRDesignStyle;
40 import net.sf.jasperreports.engine.design.JRDesignTextField;
41 import net.sf.jasperreports.engine.design.JasperDesign;
42 import net.sf.jasperreports.engine.export.JRHtmlExporterParameter;
43 import net.sf.jasperreports.engine.export.JRXhtmlExporter;
44
45 import org.apache.commons.lang.StringUtils;
46 import org.glom.libglom.Document;
47 import org.glom.libglom.Glom;
48 import org.glom.libglom.LayoutFieldVector;
49 import org.glom.libglom.LayoutGroup;
50 import org.glom.libglom.LayoutItemVector;
51 import org.glom.libglom.LayoutItem_Field;
52 import org.glom.libglom.LayoutItem_GroupBy;
53 import org.glom.libglom.Relationship;
54 import org.glom.libglom.Report;
55 import org.glom.libglom.SortClause;
56 import org.glom.libglom.SortFieldPair;
57 import org.glom.libglom.SqlBuilder;
58 import org.glom.libglom.SqlExpr;
59 import org.glom.libglom.Value;
60
61 /**
62  * @author Murray Cumming <murrayc@openimus.com>
63  * 
64  */
65 public class ReportGenerator {
66
67         final int height = 30; // Points, as specified later.
68         // An arbitrary width, because we must specify _some_ width:
69         final int width = 100; // Points, as specified later.
70
71         LayoutFieldVector fieldsToGet = new LayoutFieldVector();
72         SortClause sortClause = new SortClause();
73         String localeID;
74
75         final JasperDesign design = new JasperDesign();
76         JRDesignStyle titleStyle = new JRDesignStyle();
77         JRDesignStyle normalStyle = new JRDesignStyle();
78         JRDesignStyle boldStyle = new JRDesignStyle();
79
80         ReportGenerator(final String localeID) {
81                 this.localeID = StringUtils.defaultString(localeID);
82         }
83
84         /**
85          */
86         public String generateReport(final Document document, final String tableName, final Report report,
87                         final Connection connection, final String quickFind) {
88
89                 final org.glom.libglom.LayoutGroup layout_group = report.get_layout_group();
90
91                 design.setName(report.get_title(localeID)); // TODO: Actually, we want the title.
92
93                 titleStyle.setName("Sans_Title");
94                 titleStyle.setFontName("DejaVu Sans");
95                 titleStyle.setFontSize(24);
96                 normalStyle.setName("Sans_Normal");
97                 normalStyle.setDefault(true);
98                 normalStyle.setFontName("DejaVu Sans");
99                 normalStyle.setFontSize(12);
100                 normalStyle.setBlankWhenNull(true); // Avoid "null" appearing in reports.
101                 boldStyle.setName("Sans_Bold");
102                 boldStyle.setFontName("DejaVu Sans");
103                 boldStyle.setFontSize(12);
104                 boldStyle.setBold(true);
105                 try {
106                         design.addStyle(titleStyle);
107                         design.addStyle(normalStyle);
108                         design.addStyle(boldStyle);
109                 } catch (final JRException ex) {
110                         // TODO Auto-generated catch block
111                         ex.printStackTrace();
112                 }
113
114                 final JRDesignBand titleBand = new JRDesignBand();
115                 titleBand.setHeight(height);
116                 final JRDesignStaticText staticTitle = new JRDesignStaticText();
117                 staticTitle.setText(report.get_title(localeID));
118                 staticTitle.setY(0);
119                 staticTitle.setX(0);
120                 staticTitle.setWidth(width * 5); // No data will be shown without this.
121                 // staticTitle.setStretchWithOverflow(true);
122                 staticTitle.setHeight(height); // We must specify _some_ height.
123                 staticTitle.setStyle(titleStyle);
124                 titleBand.addElement(staticTitle);
125                 design.setTitle(titleBand);
126
127                 final JRDesignBand detailBand = new JRDesignBand();
128                 detailBand.setHeight(height + 20);
129
130                 final JRDesignBand headerBand = new JRDesignBand();
131                 headerBand.setHeight(height + 20);
132
133                 fieldsToGet = new LayoutFieldVector();
134                 final int x = 0;
135                 addToReport(layout_group, detailBand, x, headerBand, 0);
136
137                 design.setColumnHeader(headerBand);
138                 ((JRDesignSection) design.getDetailSection()).addBand(detailBand);
139
140                 // Later versions of libglom actually return an empty SqlExpr when quickFindValue is empty,
141                 // but let's be sure:
142                 SqlExpr whereClause;
143                 if (StringUtils.isEmpty(quickFind)) {
144                         whereClause = new SqlExpr();
145                 } else {
146                         final Value quickFindValue = new Value(quickFind);
147                         whereClause = Glom.get_find_where_clause_quick(document, tableName, quickFindValue);
148                 }
149
150                 final Relationship extraJoin = new Relationship(); // Ignored.
151                 final SqlBuilder builder = Glom.build_sql_select_with_where_clause(tableName, fieldsToGet, whereClause,
152                                 extraJoin, sortClause);
153                 final String sqlQuery = Glom.sqlbuilder_get_full_query(builder);
154
155                 final JRDesignQuery query = new JRDesignQuery();
156                 query.setText(sqlQuery); // TODO: Extra sort clause to sort the rows within the groups.
157                 design.setQuery(query);
158
159                 JasperReport jasperreport;
160                 try {
161                         jasperreport = JasperCompileManager.compileReport(design);
162                 } catch (final JRException ex) {
163                         ex.printStackTrace();
164                         return "Failed to Generate HTML: compileReport() failed.";
165                 }
166
167                 JasperPrint print;
168                 try {
169                         final HashMap<String, Object> parameters = new HashMap<String, Object>();
170                         parameters.put("ReportTitle", report.get_title(localeID)); // TODO: Use the title, not the name.
171                         print = JasperFillManager.fillReport(jasperreport, parameters, connection);
172                 } catch (final JRException ex) {
173                         ex.printStackTrace();
174                         return "Failed to Generate HTML: fillReport() failed.";
175                 }
176
177                 final ByteArrayOutputStream output = new ByteArrayOutputStream();
178
179                 // We use this because there is no JasperExportManager.exportReportToHtmlStream() method.
180                 // JasperExportManager.exportReportToXmlStream(print, output);
181                 try {
182                         final JRXhtmlExporter exporter = new JRXhtmlExporter();
183                         exporter.setParameter(JRHtmlExporterParameter.JASPER_PRINT, print);
184                         exporter.setParameter(JRHtmlExporterParameter.OUTPUT_STREAM, output);
185
186                         // Use points instead of pixels for sizes, because pixels are silly
187                         // in HTML:
188                         exporter.setParameter(JRHtmlExporterParameter.SIZE_UNIT, "pt");
189
190                         exporter.exportReport();
191                 } catch (final JRException ex) {
192                         ex.printStackTrace();
193                         return "Failed to Generate HTML: exportReport() failed.";
194                 }
195
196                 // System.out.print(output.toString() + "\n");
197                 return output.toString();
198         }
199
200         /**
201          * @param layout_group
202          * @param parentBand
203          * @param x
204          * @param fieldTitlesY
205          *            TODO
206          * @param height
207          */
208         private int addToReport(final org.glom.libglom.LayoutGroup layout_group, final JRDesignBand parentBand, int x,
209                         final JRDesignBand headerBand, final int fieldTitlesY) {
210
211                 /**
212                  * If this is a vertical group then we will layout the fields out vertically instead of horizontally.
213                  */
214                 /*
215                  * TODO: final org.glom.libglom.LayoutItem_VerticalGroup verticalGroup = LayoutItem_VerticalGroup
216                  * .cast_dynamic(layout_group); final boolean isVertical = (verticalGroup != null);
217                  */
218
219                 // Where we put the field titles depends on whether we are in a group-by:
220                 JRDesignBand fieldTitlesBand = headerBand;
221                 int thisFieldTitlesY = fieldTitlesY; // If they are in a group title the they must be lower.
222
223                 final LayoutItemVector layoutItemsVec = layout_group.get_items();
224                 final int numItems = Utils.safeLongToInt(layoutItemsVec.size());
225                 for (int i = 0; i < numItems; i++) {
226                         final org.glom.libglom.LayoutItem libglomLayoutItem = layoutItemsVec.get(i);
227
228                         final LayoutGroup libglomLayoutGroup = LayoutGroup.cast_dynamic(libglomLayoutItem);
229                         final LayoutItem_Field libglomLayoutItemField = LayoutItem_Field.cast_dynamic(libglomLayoutItem);
230                         if (libglomLayoutItemField != null) {
231                                 x = addFieldToDetailBand(parentBand, headerBand, x, libglomLayoutItemField, thisFieldTitlesY);
232                         } else if (libglomLayoutGroup != null) {
233                                 final LayoutItem_GroupBy libglomGroupBy = LayoutItem_GroupBy.cast_dynamic(libglomLayoutGroup);
234                                 if (libglomGroupBy != null) {
235                                         final LayoutItem_Field fieldGroupBy = libglomGroupBy.get_field_group_by();
236                                         if (fieldGroupBy == null)
237                                                 continue;
238
239                                         final String fieldName = addField(fieldGroupBy);
240
241                                         // We must sort by the group field,
242                                         // so that JasperReports can start a new group when its value changes.
243                                         // Note that this is not like a SQL GROUP BY.
244                                         final SortFieldPair pair = new SortFieldPair();
245                                         pair.setFirst(fieldGroupBy);
246                                         pair.setSecond(true); // Ascending.
247                                         sortClause.add(pair);
248
249                                         final JRDesignGroup group = new JRDesignGroup();
250                                         group.setName(fieldName);
251
252                                         // Show the field value:
253                                         final JRDesignExpression expression = createFieldExpression(fieldName);
254                                         group.setExpression(expression);
255
256                                         try {
257                                                 design.addGroup(group);
258                                         } catch (final JRException e) {
259                                                 // TODO Auto-generated catch block
260                                                 e.printStackTrace();
261                                         }
262
263                                         // Show the group-by field:
264                                         final JRDesignBand groupBand = new JRDesignBand();
265
266                                         // TODO: Use height instead of height*2 if there are no child fields,
267                                         // for instance if the only child is a sub group-by.
268                                         groupBand.setHeight(height * 2); // Enough height for the title and the field titles.
269                                         ((JRDesignSection) group.getGroupHeaderSection()).addBand(groupBand);
270
271                                         // Put the field titles inside the group-by instead of just at the top of the page.
272                                         // (or instead of just in the parent group-by):
273                                         fieldTitlesBand = groupBand;
274                                         thisFieldTitlesY = height;
275
276                                         /*
277                                          * final JRDesignBand footerBand = new JRDesignBand(); footerBand.setHeight(height);
278                                          * ((JRDesignSection) group.getGroupFooterSection()).addBand(footerBand);
279                                          */
280
281                                         int groupX = addFieldToGroupBand(groupBand, x, fieldGroupBy);
282
283                                         // Show the secondary fields:
284                                         final LayoutGroup groupSecondaries = libglomGroupBy.get_secondary_fields();
285                                         if (groupSecondaries != null)
286                                                 groupX = addSecondaryFieldsToGroupBand(groupSecondaries, groupBand, groupX);
287
288                                         final JRDesignLine line = new JRDesignLine();
289                                         final int lineheight = 1;
290                                         line.setX(0);
291
292                                         // TODO: Automatically place it below the text, though that needs us to know how much height the
293                                         // text really needs.
294                                         line.setY(height - 15);
295
296                                         // TODO: Make it as wide as needed by the details band.
297                                         line.setWidth(groupX);
298                                         line.setHeight(lineheight);
299                                         groupBand.addElement(line);
300                                 }
301
302                                 // Recurse into sub-groups:
303                                 x = addToReport(libglomLayoutGroup, parentBand, x, fieldTitlesBand, thisFieldTitlesY);
304                         }
305                 }
306
307                 return x;
308         }
309
310         private int addSecondaryFieldsToGroupBand(final org.glom.libglom.LayoutGroup layout_group,
311                         final JRDesignBand groupBand, int x) {
312                 final LayoutItemVector layoutItemsVec = layout_group.get_items();
313                 final int numItems = Utils.safeLongToInt(layoutItemsVec.size());
314                 for (int i = 0; i < numItems; i++) {
315                         final org.glom.libglom.LayoutItem libglomLayoutItem = layoutItemsVec.get(i);
316
317                         final LayoutGroup libglomLayoutGroup = LayoutGroup.cast_dynamic(libglomLayoutItem);
318                         final LayoutItem_Field libglomLayoutItemField = LayoutItem_Field.cast_dynamic(libglomLayoutItem);
319                         if (libglomLayoutItemField != null) {
320                                 x = addFieldToGroupBand(groupBand, x, libglomLayoutItemField);
321                         } else if (libglomLayoutGroup != null) {
322                                 // We do not expect LayoutItem_GroupBy in the secondary fields:
323                                 // final LayoutItem_GroupBy libglomGroupBy = LayoutItem_GroupBy.cast_dynamic(libglomLayoutGroup);
324
325                                 // Recurse into sub-groups:
326                                 x = addSecondaryFieldsToGroupBand(libglomLayoutGroup, groupBand, x);
327                         }
328                 }
329
330                 return x;
331         }
332
333         /**
334          * @param fieldName
335          * @return
336          */
337         private JRDesignExpression createFieldExpression(final String fieldName) {
338                 final JRDesignExpression expression = new JRDesignExpression();
339
340                 // TODO: Where is this format documented?
341                 expression.setText("$F{" + fieldName + "}");
342                 return expression;
343         }
344
345         /**
346          * @param parentBand
347          * @param x
348          * @param libglomLayoutItemField
349          * @param fieldTitlesY
350          *            TODO
351          * @return
352          */
353         private int addFieldToDetailBand(final JRDesignBand parentBand, final JRDesignBand headerBand, int x,
354                         final LayoutItem_Field libglomLayoutItemField, final int fieldTitlesY) {
355                 final String fieldName = addField(libglomLayoutItemField);
356
357                 // Show the field title:
358                 final JRDesignStaticText textFieldColumn = createFieldTitleElement(x, fieldTitlesY, libglomLayoutItemField,
359                                 false);
360                 textFieldColumn.setStyle(boldStyle);
361                 headerBand.addElement(textFieldColumn);
362
363                 // Show an instance of the field (the field value):
364                 final JRDesignTextField textField = createFieldValueElement(x, fieldName);
365                 textField.setStyle(normalStyle);
366                 parentBand.addElement(textField);
367
368                 x += width;
369                 return x;
370         }
371
372         private int addFieldToGroupBand(final JRDesignBand parentBand, int x, final LayoutItem_Field libglomLayoutItemField) {
373                 final String fieldName = addField(libglomLayoutItemField);
374
375                 // Show the field title:
376                 final JRDesignStaticText textFieldColumn = createFieldTitleElement(x, 0, libglomLayoutItemField, true);
377
378                 // Instead, the field value will be bold, because here it is like a title.
379                 textFieldColumn.setStyle(normalStyle);
380
381                 parentBand.addElement(textFieldColumn);
382                 x += width;
383
384                 // Show an instance of the field (the field value):
385                 final JRDesignTextField textField = createFieldValueElement(x, fieldName);
386                 parentBand.addElement(textField);
387                 textField.setStyle(boldStyle);
388
389                 x += width;
390                 return x;
391         }
392
393         /**
394          * @param x
395          * @param fieldName
396          * @return
397          */
398         private JRDesignTextField createFieldValueElement(final int x, final String fieldName) {
399                 final JRDesignTextField textField = new JRDesignTextField();
400
401                 // Make sure this field starts at the right of the previous field,
402                 // because JasperReports uses absolute positioning.
403                 textField.setY(0);
404                 textField.setX(x);
405                 textField.setWidth(width); // No data will be shown without this.
406
407                 // This only stretches vertically, but that is better than
408                 // nothing.
409                 textField.setStretchWithOverflow(true);
410                 textField.setHeight(height); // We must specify _some_ height.
411
412                 final JRDesignExpression expression = createFieldExpression(fieldName);
413
414                 textField.setExpression(expression);
415                 return textField;
416         }
417
418         /**
419          * @param x
420          * @param y
421          *            TODO
422          * @param libglomLayoutItemField
423          * @return
424          */
425         private JRDesignStaticText createFieldTitleElement(final int x, final int y,
426                         final LayoutItem_Field libglomLayoutItemField, final boolean withColon) {
427                 final JRDesignStaticText textFieldColumn = new JRDesignStaticText();
428
429                 String title = StringUtils.defaultString(libglomLayoutItemField.get_title(this.localeID));
430
431                 // If the title is at the left, instead of above, we need a : to show that it's a title.
432                 if (withColon)
433                         title += ":";
434
435                 textFieldColumn.setText(title);
436                 textFieldColumn.setY(y);
437                 textFieldColumn.setX(x);
438                 textFieldColumn.setWidth(width); // No data will be shown without this.
439                 // textFieldColumn.setStretchWithOverflow(true);
440                 textFieldColumn.setHeight(height); // We must specify _some_ height.
441                 return textFieldColumn;
442         }
443
444         /**
445          * @param libglomLayoutItemField
446          * @return
447          */
448         private String addField(final LayoutItem_Field libglomLayoutItemField) {
449                 fieldsToGet.add(libglomLayoutItemField);
450
451                 final String fieldName = libglomLayoutItemField.get_name();
452                 // System.out.print("fieldName=" + fieldName + "\n");
453
454                 // Tell the JasperDesign about the database field that will be in the SQL query,
455                 // specified later:
456                 final JRDesignField field = new JRDesignField();
457                 field.setName(fieldName); // TODO: Related fields.
458                 field.setValueClass(getClassTypeForGlomType(libglomLayoutItemField));
459
460                 try {
461                         design.addField(field);
462                 } catch (final JRException e2) {
463                         // TODO Auto-generated catch block
464                         e2.printStackTrace();
465                 }
466                 return fieldName;
467         }
468
469         /**
470          * @param libglomLayoutItemField
471          * @return
472          */
473         private Class<?> getClassTypeForGlomType(final LayoutItem_Field libglomLayoutItemField) {
474                 // Choose a suitable java class type for the SQL field:
475                 Class<?> klass = null;
476                 switch (libglomLayoutItemField.get_glom_type()) {
477                 case TYPE_TEXT:
478                         klass = java.lang.String.class;
479                         break;
480                 case TYPE_BOOLEAN:
481                         klass = java.lang.Boolean.class;
482                         break;
483                 case TYPE_NUMERIC:
484                         klass = java.lang.Double.class;
485                         break;
486                 case TYPE_DATE:
487                         klass = java.util.Date.class;
488                         break;
489                 case TYPE_TIME:
490                         klass = java.sql.Time.class;
491                         break;
492                 case TYPE_IMAGE:
493                         klass = java.sql.Blob.class; // TODO: This does not work.
494                         break;
495                 }
496                 return klass;
497         }
498 }