DetailsActivity: Check for authentication here too.
[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.text.DateFormat;
25 import java.text.DecimalFormat;
26 import java.text.SimpleDateFormat;
27 import java.util.ArrayList;
28 import java.util.HashMap;
29 import java.util.List;
30 import java.util.Locale;
31
32 import net.sf.jasperreports.engine.JRException;
33 import net.sf.jasperreports.engine.JRExporterParameter;
34 import net.sf.jasperreports.engine.JasperCompileManager;
35 import net.sf.jasperreports.engine.JasperFillManager;
36 import net.sf.jasperreports.engine.JasperPrint;
37 import net.sf.jasperreports.engine.JasperReport;
38 import net.sf.jasperreports.engine.design.JRDesignBand;
39 import net.sf.jasperreports.engine.design.JRDesignExpression;
40 import net.sf.jasperreports.engine.design.JRDesignField;
41 import net.sf.jasperreports.engine.design.JRDesignGroup;
42 import net.sf.jasperreports.engine.design.JRDesignLine;
43 import net.sf.jasperreports.engine.design.JRDesignQuery;
44 import net.sf.jasperreports.engine.design.JRDesignSection;
45 import net.sf.jasperreports.engine.design.JRDesignStaticText;
46 import net.sf.jasperreports.engine.design.JRDesignStyle;
47 import net.sf.jasperreports.engine.design.JRDesignTextField;
48 import net.sf.jasperreports.engine.design.JasperDesign;
49 import net.sf.jasperreports.engine.export.JRHtmlExporterParameter;
50 import net.sf.jasperreports.engine.export.JRXhtmlExporter;
51
52 import org.apache.commons.lang3.StringUtils;
53 import org.glom.web.server.libglom.Document;
54 import org.glom.web.shared.TypedDataItem;
55 import org.glom.web.shared.libglom.Field.GlomFieldType;
56 import org.glom.web.shared.libglom.NumericFormat;
57 import org.glom.web.shared.libglom.Report;
58 import org.glom.web.shared.libglom.layout.Formatting;
59 import org.glom.web.shared.libglom.layout.LayoutGroup;
60 import org.glom.web.shared.libglom.layout.LayoutItem;
61 import org.glom.web.shared.libglom.layout.LayoutItemField;
62 import org.glom.web.shared.libglom.layout.SortClause;
63 import org.glom.web.shared.libglom.layout.UsesRelationship;
64 import org.glom.web.shared.libglom.layout.reportparts.LayoutItemGroupBy;
65 import org.glom.web.shared.libglom.layout.reportparts.LayoutItemVerticalGroup;
66 import org.jooq.Condition;
67
68 /**
69  * @author Murray Cumming <murrayc@openimus.com>
70  * 
71  */
72 public class ReportGenerator {
73
74         private static class Position {
75                 public Position(final int x, final int y) {
76                         this.x = x;
77                         this.y = y;
78                 }
79
80                 public Position(final Position pos) {
81                         this.x = pos.x;
82                         this.y = pos.y;
83                 }
84
85                 public int x = 0;
86                 public int y = 0;
87         }
88
89         final int height = 30; // Points, as specified later.
90         // An arbitrary width, because we must specify _some_ width:
91         final int width = 100; // Points, as specified later.
92
93         List<LayoutItemField> fieldsToGet = new ArrayList<LayoutItemField>();
94         SortClause sortClause = new SortClause();
95         String localeID;
96
97         final JasperDesign design = new JasperDesign();
98         JRDesignStyle titleStyle = new JRDesignStyle();
99         JRDesignStyle normalStyle = new JRDesignStyle();
100         JRDesignStyle fieldTitleStyle = new JRDesignStyle();
101
102         ReportGenerator(final String localeID) {
103                 this.localeID = StringUtils.defaultString(localeID);
104         }
105
106         /**
107          */
108         public String generateReport(final Document glomDocument, final String tableName, final Report report,
109                         final Connection connection, final String quickFind) {
110
111                 final LayoutGroup layout_group = report.getLayoutGroup();
112
113                 design.setName(report.getTitle(localeID)); // TODO: Actually, we want the title.
114
115                 titleStyle.setName("Sans_Title");
116                 titleStyle.setFontName("DejaVu Sans");
117                 titleStyle.setFontSize(24);
118                 normalStyle.setName("Sans_Normal");
119                 normalStyle.setDefault(true);
120                 normalStyle.setFontName("DejaVu Sans");
121                 normalStyle.setFontSize(12);
122                 normalStyle.setBlankWhenNull(true); // Avoid "null" appearing in reports.
123                 fieldTitleStyle.setName("Sans_Bold");
124                 fieldTitleStyle.setFontName("DejaVu Sans");
125                 fieldTitleStyle.setFontSize(12);
126                 fieldTitleStyle.setBold(true);
127                 fieldTitleStyle.setBlankWhenNull(true); // Avoid "null" appearing in reports when this is used for a GroupBy
128                                                                                                 // title.
129                 try {
130                         design.addStyle(titleStyle);
131                         design.addStyle(normalStyle);
132                         design.addStyle(fieldTitleStyle);
133                 } catch (final JRException ex) {
134                         // TODO Auto-generated catch block
135                         ex.printStackTrace();
136                 }
137
138                 final JRDesignBand titleBand = new JRDesignBand();
139                 titleBand.setHeight(height);
140                 final JRDesignStaticText staticTitle = new JRDesignStaticText();
141                 staticTitle.setText(report.getTitle(localeID));
142                 staticTitle.setY(0);
143                 staticTitle.setX(0);
144                 staticTitle.setWidth(width * 5); // No data will be shown without this.
145                 // staticTitle.setStretchWithOverflow(true);
146                 staticTitle.setHeight(height); // We must specify _some_ height.
147                 staticTitle.setStyle(titleStyle);
148                 titleBand.addElement(staticTitle);
149                 design.setTitle(titleBand);
150
151                 final JRDesignBand detailBand = new JRDesignBand();
152                 detailBand.setHeight(height + 20);
153
154                 final JRDesignBand headerBand = new JRDesignBand();
155                 headerBand.setHeight(height + 20);
156
157                 fieldsToGet = new ArrayList<LayoutItemField>();
158                 final int x = 0;
159                 addGroupToReport(layout_group, detailBand, x, headerBand, 0);
160
161                 design.setColumnHeader(headerBand);
162                 ((JRDesignSection) design.getDetailSection()).addBand(detailBand);
163
164                 // Later versions of libglom actually return an empty SqlExpr when quickFindValue is empty,
165                 // but let's be sure:
166                 Condition whereClause = null;
167                 if (!StringUtils.isEmpty(quickFind)) {
168                         final TypedDataItem quickFindValue = new TypedDataItem();
169                         quickFindValue.setText(quickFind);
170                         whereClause = SqlUtils.getFindWhereClauseQuick(glomDocument, tableName, quickFindValue);
171                 }
172
173                 String sqlQuery = "";
174                 if (!fieldsToGet.isEmpty()) {
175                         sqlQuery = SqlUtils.buildSqlSelectWithWhereClause(tableName, fieldsToGet, whereClause, sortClause);
176                 } else {
177                         Log.info("generateReport(): fieldsToGet is empty.");
178                 }
179
180                 final JRDesignQuery query = new JRDesignQuery();
181                 query.setText(sqlQuery); // TODO: Extra sort clause to sort the rows within the groups.
182                 design.setQuery(query);
183
184                 JasperReport jasperreport;
185                 try {
186                         jasperreport = JasperCompileManager.compileReport(design);
187                 } catch (final JRException ex) {
188                         ex.printStackTrace();
189                         return "Failed to Generate HTML: compileReport() failed.";
190                 }
191
192                 JasperPrint print;
193                 try {
194                         final HashMap<String, Object> parameters = new HashMap<String, Object>();
195                         parameters.put("ReportTitle", report.getTitle(localeID)); // TODO: Use the title, not the name.
196                         print = JasperFillManager.fillReport(jasperreport, parameters, connection);
197                 } catch (final JRException ex) {
198                         ex.printStackTrace();
199                         return "Failed to Generate HTML: fillReport() failed.";
200                 }
201
202                 final ByteArrayOutputStream output = new ByteArrayOutputStream();
203
204                 // We use this because there is no JasperExportManager.exportReportToHtmlStream() method.
205                 // JasperExportManager.exportReportToXmlStream(print, output);
206                 try {
207                         final JRXhtmlExporter exporter = new JRXhtmlExporter();
208                         exporter.setParameter(JRExporterParameter.JASPER_PRINT, print);
209                         exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, output);
210
211                         // Use points instead of pixels for sizes, because pixels are silly
212                         // in HTML:
213                         exporter.setParameter(JRHtmlExporterParameter.SIZE_UNIT, "pt");
214
215                         // Avoid the page breaks, because they do not make sense for HTML:
216                         // TODO: These do not seem to preven the page break gap.
217                         exporter.setParameter(JRHtmlExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS, Boolean.TRUE);
218                         exporter.setParameter(JRHtmlExporterParameter.BETWEEN_PAGES_HTML, "");
219
220                         exporter.exportReport();
221                 } catch (final JRException ex) {
222                         ex.printStackTrace();
223                         return "Failed to Generate HTML: exportReport() failed.";
224                 }
225
226                 // System.out.print(output.toString() + "\n");
227                 final String html = output.toString();
228
229                 // This does not work because jasperReports does not put individual rows in separate table rows.
230                 // jasperReports just puts the whole thing in one table row.
231                 // Remove the arbitrary width and height that JasperReports forced us to specify:
232                 // html = html.replaceAll("position:absolute;", "");
233                 // html = html.replaceAll("top:(\\d*)pt;", "");
234                 // html = html.replaceAll("left:(\\d*)pt;", "");
235                 // html = html.replaceAll("height:(\\d*)pt;", "");
236                 // html = html.replaceAll("width:(\\d*)pt;", "");
237                 // html = html.replaceAll("overflow: hidden;", "");
238
239                 return html;
240         }
241
242         /**
243          * A vertical group lays the fields out vertically instead of horizontally, with titles to the left.
244          * 
245          * @param layout_group
246          * @param parentBand
247          * @param x
248          * @param fieldTitlesY
249          *            TODO
250          * @param height
251          */
252         private Position addVerticalGroupToReport(final LayoutItemVerticalGroup layout_group,
253                         final JRDesignBand parentBand, final Position pos) {
254                 Position pos_result = new Position(pos);
255
256                 final List<LayoutItem> layoutItemsVec = layout_group.getItems();
257                 final int numItems = Utils.safeLongToInt(layoutItemsVec.size());
258                 for (int i = 0; i < numItems; i++) {
259                         final LayoutItem libglomLayoutItem = layoutItemsVec.get(i);
260
261                         if (libglomLayoutItem instanceof LayoutItemField) {
262                                 final LayoutItemField libglomLayoutItemField = (LayoutItemField) libglomLayoutItem;
263                                 pos_result = addFieldToDetailBandVertical(parentBand, pos_result, libglomLayoutItemField);
264                                 pos_result.x = pos.x;
265                         } else {
266
267                                 // TODO: Handle other item types.
268
269                                 // Recurse into sub-groups:
270                                 // TODO: x = addGroupToReport(libglomLayoutGroup, parentBand, x, fieldTitlesBand, thisFieldTitlesY);
271                         }
272                 }
273
274                 pos_result.x += width * 2;
275                 return pos_result;
276         }
277
278         /**
279          * @param layout_group
280          * @param parentBand
281          * @param x
282          * @param fieldTitlesY
283          *            TODO
284          * @param height
285          */
286         private Position addGroupToReport(final LayoutGroup layout_group, final JRDesignBand parentBand, final int x,
287                         final JRDesignBand headerBand, final int fieldTitlesY) {
288
289                 Position pos_result = new Position(x, 0);
290
291                 /**
292                  * * If this is a vertical group then we will lay the fields out vertically instead of horizontally.
293                  */
294                 if (layout_group instanceof LayoutItemVerticalGroup) {
295                         final LayoutItemVerticalGroup verticalGroup = (LayoutItemVerticalGroup) layout_group;
296                         return addVerticalGroupToReport(verticalGroup, parentBand, pos_result);
297                 }
298
299                 // Where we put the field titles depends on whether we are in a group-by:
300                 JRDesignBand fieldTitlesBand = headerBand;
301                 int thisFieldTitlesY = fieldTitlesY; // If they are in a group title then they must be lower.
302
303                 final List<LayoutItem> layoutItemsVec = layout_group.getItems();
304                 final int numItems = Utils.safeLongToInt(layoutItemsVec.size());
305                 for (int i = 0; i < numItems; i++) {
306                         final LayoutItem libglomLayoutItem = layoutItemsVec.get(i);
307
308                         if (libglomLayoutItem instanceof LayoutItemField) {
309                                 final LayoutItemField libglomLayoutItemField = (LayoutItemField) libglomLayoutItem;
310                                 pos_result = addFieldToDetailBand(parentBand, headerBand, pos_result.x, libglomLayoutItemField,
311                                                 thisFieldTitlesY, pos_result.y);
312                         } else if (libglomLayoutItem instanceof LayoutGroup) {
313                                 final LayoutGroup libglomLayoutGroup = (LayoutGroup) libglomLayoutItem;
314
315                                 if (libglomLayoutGroup instanceof LayoutItemGroupBy) {
316                                         final LayoutItemGroupBy libglomGroupBy = (LayoutItemGroupBy) libglomLayoutGroup;
317                                         final LayoutItemField fieldGroupBy = libglomGroupBy.getFieldGroupBy();
318                                         if (fieldGroupBy == null) {
319                                                 continue;
320                                         }
321
322                                         final String fieldName = addField(fieldGroupBy);
323                                         if (StringUtils.isEmpty(fieldName)) {
324                                                 continue;
325                                         }
326
327                                         // We must sort by the group field,
328                                         // so that JasperReports can start a new group when its value changes.
329                                         // Note that this is not like a SQL GROUP BY.
330                                         final SortClause.SortField pair = new SortClause.SortField();
331                                         pair.field = fieldGroupBy;
332                                         pair.ascending = true;
333                                         sortClause.add(pair);
334
335                                         final JRDesignGroup group = new JRDesignGroup();
336                                         group.setName(fieldName);
337
338                                         // Show the field value:
339                                         final JRDesignExpression expression = createFieldExpression(fieldGroupBy);
340                                         group.setExpression(expression);
341
342                                         try {
343                                                 design.addGroup(group);
344                                         } catch (final JRException e) {
345                                                 // TODO Auto-generated catch block
346                                                 e.printStackTrace();
347                                         }
348
349                                         // Show the group-by field:
350                                         final JRDesignBand groupBand = new JRDesignBand();
351
352                                         // TODO: Use height instead of height*2 if there are no child fields,
353                                         // for instance if the only child is a sub group-by.
354                                         groupBand.setHeight(height * 2); // Enough height for the title and the field titles.
355                                         ((JRDesignSection) group.getGroupHeaderSection()).addBand(groupBand);
356
357                                         // Put the field titles inside the group-by instead of just at the top of the page.
358                                         // (or instead of just in the parent group-by):
359                                         fieldTitlesBand = groupBand;
360                                         thisFieldTitlesY = height;
361
362                                         /*
363                                          * final JRDesignBand footerBand = new JRDesignBand(); footerBand.setHeight(height);
364                                          * ((JRDesignSection) group.getGroupFooterSection()).addBand(footerBand);
365                                          */
366
367                                         int groupX = addFieldToGroupBand(groupBand, x, fieldGroupBy);
368
369                                         // Show the secondary fields:
370                                         final LayoutGroup groupSecondaries = libglomGroupBy.getSecondaryFields();
371                                         if (groupSecondaries != null) {
372                                                 groupX = addSecondaryFieldsToGroupBand(groupSecondaries, groupBand, groupX);
373                                         }
374
375                                         final JRDesignLine line = new JRDesignLine();
376                                         final int lineheight = 1;
377                                         line.setX(0);
378
379                                         // TODO: Automatically place it below the text, though that needs us to know how much height the
380                                         // text really needs.
381                                         line.setY(height - 15);
382
383                                         // TODO: Make it as wide as needed by the details band.
384                                         line.setWidth(groupX);
385                                         line.setHeight(lineheight);
386                                         groupBand.addElement(line);
387                                 }
388
389                                 // Recurse into sub-groups:
390                                 pos_result = addGroupToReport(libglomLayoutGroup, parentBand, pos_result.x, fieldTitlesBand,
391                                                 thisFieldTitlesY);
392                         }
393                 }
394
395                 return pos_result;
396         }
397
398         private int addSecondaryFieldsToGroupBand(final LayoutGroup layout_group, final JRDesignBand groupBand, int x) {
399                 final List<LayoutItem> layoutItemsVec = layout_group.getItems();
400                 final int numItems = Utils.safeLongToInt(layoutItemsVec.size());
401                 for (int i = 0; i < numItems; i++) {
402                         final LayoutItem libglomLayoutItem = layoutItemsVec.get(i);
403
404                         if (libglomLayoutItem instanceof LayoutItemField) {
405                                 final LayoutItemField libglomLayoutItemField = (LayoutItemField) libglomLayoutItem;
406                                 x = addFieldToGroupBand(groupBand, x, libglomLayoutItemField);
407                         } else if (libglomLayoutItem instanceof LayoutGroup) {
408                                 final LayoutGroup libglomLayoutGroup = (LayoutGroup) libglomLayoutItem;
409
410                                 // We do not expect LayoutItem_GroupBy in the secondary fields:
411                                 // final LayoutItem_GroupBy libglomGroupBy = LayoutItem_GroupBy.cast_dynamic(libglomLayoutGroup);
412
413                                 // Recurse into sub-groups:
414                                 x = addSecondaryFieldsToGroupBand(libglomLayoutGroup, groupBand, x);
415                         }
416                 }
417
418                 return x;
419         }
420
421         /**
422          * @param libglomLayoutItemField
423          * @return
424          */
425         private JRDesignExpression createFieldExpression(final LayoutItemField libglomLayoutItemField) {
426                 final JRDesignExpression expression = new JRDesignExpression();
427
428                 final String fieldName = libglomLayoutItemField.getName(); // TODO: Is this enough for related fields?
429
430                 // TODO: Where is this format documented?
431                 expression.setText("$F{" + fieldName + "}");
432                 return expression;
433         }
434
435         /**
436          * @param parentBand
437          * @param x
438          * @param libglomLayoutItemField
439          * @param fieldTitlesY
440          *            TODO
441          * @return
442          */
443         private Position addFieldToDetailBand(final JRDesignBand parentBand, final JRDesignBand headerBand, final int x,
444                         final LayoutItemField libglomLayoutItemField, final int fieldTitlesY, final int fieldY) {
445                 addField(libglomLayoutItemField);
446
447                 // Show the field title:
448                 final JRDesignStaticText textFieldColumn = createFieldTitleElement(new Position(x, fieldTitlesY),
449                                 libglomLayoutItemField, false);
450                 textFieldColumn.setStyle(fieldTitleStyle);
451                 headerBand.addElement(textFieldColumn);
452
453                 // Show an instance of the field (the field value):
454                 final JRDesignTextField textField = createFieldValueElement(new Position(x, 0), libglomLayoutItemField);
455                 textField.setStyle(normalStyle);
456                 parentBand.addElement(textField);
457
458                 return new Position(x + width, 0);
459         }
460
461         /**
462          * @param parentBand
463          * @param x
464          * @param libglomLayoutItemField
465          * @param fieldTitlesY
466          *            TODO
467          * @return
468          */
469         private Position addFieldToDetailBandVertical(final JRDesignBand parentBand, final Position pos,
470                         final LayoutItemField libglomLayoutItemField) {
471                 addField(libglomLayoutItemField);
472
473                 final Position pos_result = new Position(pos);
474
475                 // Make the band high enough if necessary:
476                 if (parentBand.getHeight() < (pos_result.y + height)) {
477                         parentBand.setHeight(pos_result.y + height + 20);
478                 }
479
480                 // Show the field title:
481                 final JRDesignStaticText textFieldColumn = createFieldTitleElement(pos_result, libglomLayoutItemField, true);
482                 textFieldColumn.setStyle(fieldTitleStyle);
483                 parentBand.addElement(textFieldColumn);
484                 pos_result.x += width;
485
486                 // Show an instance of the field (the field value):
487                 final JRDesignTextField textField = createFieldValueElement(pos_result, libglomLayoutItemField);
488                 textField.setStyle(normalStyle);
489                 parentBand.addElement(textField);
490
491                 pos_result.x += width;
492
493                 pos_result.y += height;
494
495                 return pos_result;
496         }
497
498         private int addFieldToGroupBand(final JRDesignBand parentBand, final int x,
499                         final LayoutItemField libglomLayoutItemField) {
500                 addField(libglomLayoutItemField);
501
502                 final Position pos = new Position(x, 0);
503
504                 // Show the field title:
505                 final JRDesignStaticText textFieldColumn = createFieldTitleElement(pos, libglomLayoutItemField, true);
506
507                 // Instead, the field value will be bold, because here it is like a title.
508                 textFieldColumn.setStyle(normalStyle);
509
510                 parentBand.addElement(textFieldColumn);
511                 pos.x += width;
512
513                 // Show an instance of the field (the field value):
514                 final JRDesignTextField textField = createFieldValueElement(pos, libglomLayoutItemField);
515                 parentBand.addElement(textField);
516                 textField.setStyle(fieldTitleStyle);
517
518                 pos.x += width;
519                 return pos.x;
520         }
521
522         /**
523          * @param x
524          * @param libglomLayoutItemField
525          * @return
526          */
527         private JRDesignTextField createFieldValueElement(final Position pos, final LayoutItemField libglomLayoutItemField) {
528                 final JRDesignTextField textField = new JRDesignTextField();
529
530                 // Make sure this field starts at the right of the previous field,
531                 // because JasperReports uses absolute positioning.
532                 textField.setY(pos.y);
533                 textField.setX(pos.x);
534                 textField.setWidth(width); // No data will be shown without this.
535
536                 // This only stretches vertically, but that is better than
537                 // nothing.
538                 textField.setStretchWithOverflow(true);
539                 textField.setHeight(height); // We must specify _some_ height.
540
541                 final JRDesignExpression expression = createFieldExpression(libglomLayoutItemField);
542                 textField.setExpression(expression);
543
544                 if (libglomLayoutItemField.getGlomType() == GlomFieldType.TYPE_NUMERIC) {
545                         // Numeric formatting:
546                         final Formatting formatting = libglomLayoutItemField.getFormattingUsed();
547                         final NumericFormat numericFormat = formatting.getNumericFormat();
548
549                         final DecimalFormat format = new DecimalFormat();
550                         format.setMaximumFractionDigits(numericFormat.getDecimalPlaces());
551                         format.setGroupingUsed(numericFormat.getUseThousandsSeparator());
552
553                         // TODO: Use numericFormat.get_currency_symbol(), possibly via format.setCurrency().
554                         textField.setPattern(format.toPattern());
555                 } else if (libglomLayoutItemField.getGlomType() == GlomFieldType.TYPE_DATE) {
556                         // Date formatting
557                         // TODO: Use a 4-digit-year short form, somehow.
558                         try // We use a try block because getDateInstance() is not guaranteed to return a SimpleDateFormat.
559                         {
560                                 final SimpleDateFormat format = (SimpleDateFormat) DateFormat.getDateInstance(DateFormat.SHORT,
561                                                 Locale.ROOT);
562
563                                 textField.setPattern(format.toPattern());
564                         } catch (final Exception ex) {
565                                 Log.info("ReportGenerator: The cast of SimpleDateFormat failed.");
566                         }
567                 } else if (libglomLayoutItemField.getGlomType() == GlomFieldType.TYPE_TIME) {
568                         // Time formatting
569                         try // We use a try block because getDateInstance() is not guaranteed to return a SimpleDateFormat.
570                         {
571                                 final SimpleDateFormat format = (SimpleDateFormat) DateFormat.getTimeInstance(DateFormat.SHORT,
572                                                 Locale.ROOT);
573
574                                 textField.setPattern(format.toPattern());
575                         } catch (final Exception ex) {
576                                 Log.info("ReportGenerator: The cast of SimpleDateFormat failed.");
577                         }
578                 }
579
580                 return textField;
581         }
582
583         /**
584          * @param x
585          * @param y
586          *            TODO
587          * @param libglomLayoutItemField
588          * @return
589          */
590         private JRDesignStaticText createFieldTitleElement(final Position pos,
591                         final LayoutItemField libglomLayoutItemField, final boolean withColon) {
592                 final JRDesignStaticText textFieldColumn = new JRDesignStaticText();
593
594                 String title = StringUtils.defaultString(libglomLayoutItemField.getTitle(this.localeID));
595
596                 // If the title is at the left, instead of above, we need a : to show that it's a title.
597                 if (withColon) {
598                         title += ":";
599                 }
600
601                 textFieldColumn.setText(title);
602                 textFieldColumn.setY(pos.y);
603                 textFieldColumn.setX(pos.x);
604                 textFieldColumn.setWidth(width); // No data will be shown without this.
605                 // textFieldColumn.setStretchWithOverflow(true);
606                 textFieldColumn.setHeight(height); // We must specify _some_ height.
607                 return textFieldColumn;
608         }
609
610         /**
611          * @param libglomLayoutItemField
612          * @return
613          */
614         private String addField(final LayoutItemField libglomLayoutItemField) {
615
616                 final String fieldName = libglomLayoutItemField.getName(); // TODO: Is this enough for related fields?
617
618                 // Avoid an unnamed field:
619                 if (StringUtils.isEmpty(fieldName)) {
620                         Log.info("addField(): Ignoring LayoutItemField with no field name");
621                         return fieldName;
622                 }
623
624                 // Avoid adding duplicate fields,
625                 // because JasperDesign.addField() throws a "Duplicate declaration of field" exception.
626                 for (int i = 0; i < fieldsToGet.size(); ++i) {
627                         final UsesRelationship thisField = fieldsToGet.get(i);
628                         if (thisField.equals(libglomLayoutItemField)) {
629                                 return fieldName;
630                         }
631                 }
632
633                 fieldsToGet.add(libglomLayoutItemField);
634
635                 // System.out.print("fieldName=" + fieldName + "\n");
636
637                 // Tell the JasperDesign about the database field that will be in the SQL query,
638                 // specified later:
639                 final JRDesignField field = new JRDesignField();
640                 field.setName(fieldName); // TODO: Related fields.
641
642                 final Class<?> klass = getClassTypeForGlomType(libglomLayoutItemField);
643                 if (klass != null) {
644                         field.setValueClass(klass);
645                 } else {
646                         Log.info("getClassTypeForGlomType() returned null");
647                 }
648
649                 try {
650                         design.addField(field);
651                 } catch (final JRException e2) {
652                         // TODO Auto-generated catch block
653                         e2.printStackTrace();
654                 }
655
656                 return fieldName;
657         }
658
659         /**
660          * @param libglomLayoutItemField
661          * @return
662          */
663         private Class<?> getClassTypeForGlomType(final LayoutItemField libglomLayoutItemField) {
664                 // Choose a suitable java class type for the SQL field:
665                 Class<?> klass = null;
666
667                 final GlomFieldType glom_type = libglomLayoutItemField.getGlomType();
668                 switch (glom_type) {
669                 case TYPE_TEXT:
670                         klass = java.lang.String.class;
671                         break;
672                 case TYPE_BOOLEAN:
673                         klass = java.lang.Boolean.class;
674                         break;
675                 case TYPE_NUMERIC:
676                         klass = java.lang.Double.class;
677                         break;
678                 case TYPE_DATE:
679                         klass = java.util.Date.class;
680                         break;
681                 case TYPE_TIME:
682                         klass = java.sql.Time.class;
683                         break;
684                 case TYPE_IMAGE:
685                         klass = java.sql.Blob.class; // TODO: This does not work.
686                         break;
687                 case TYPE_INVALID:
688                         Log.info("getClassTypeForGlomType() returning null for TYPE_INVALID glom type. Field name="
689                                         + libglomLayoutItemField.getLayoutDisplayName());
690                 default:
691                         Log.info("getClassTypeForGlomType() returning null for glom type: " + glom_type + ". Field name="
692                                         + libglomLayoutItemField.getLayoutDisplayName());
693                         break;
694                 }
695                 return klass;
696         }
697 }