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