Add support for accessing multiple glom documents in the servlet.
[online-glom:gwt-glom.git] / src / main / java / org / glom / web / server / OnlineGlomServiceImpl.java
1 /*
2  * Copyright (C) 2010, 2011 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.beans.PropertyVetoException;
23 import java.io.File;
24 import java.io.FilenameFilter;
25 import java.io.IOException;
26 import java.sql.Connection;
27 import java.sql.Date;
28 import java.sql.ResultSet;
29 import java.sql.SQLException;
30 import java.sql.Statement;
31 import java.sql.Time;
32 import java.text.DateFormat;
33 import java.text.NumberFormat;
34 import java.util.ArrayList;
35 import java.util.Currency;
36 import java.util.Hashtable;
37 import java.util.Locale;
38 import java.util.Properties;
39
40 import org.glom.libglom.BakeryDocument.LoadFailureCodes;
41 import org.glom.libglom.Document;
42 import org.glom.libglom.Field;
43 import org.glom.libglom.FieldFormatting;
44 import org.glom.libglom.FieldVector;
45 import org.glom.libglom.Glom;
46 import org.glom.libglom.LayoutFieldVector;
47 import org.glom.libglom.LayoutGroupVector;
48 import org.glom.libglom.LayoutItem;
49 import org.glom.libglom.LayoutItemVector;
50 import org.glom.libglom.LayoutItem_Field;
51 import org.glom.libglom.NumericFormat;
52 import org.glom.libglom.SortClause;
53 import org.glom.libglom.SortFieldPair;
54 import org.glom.libglom.StringVector;
55 import org.glom.web.client.OnlineGlomService;
56 import org.glom.web.shared.ColumnInfo;
57 import org.glom.web.shared.GlomDocument;
58 import org.glom.web.shared.GlomField;
59 import org.glom.web.shared.LayoutListTable;
60
61 import com.allen_sauer.gwt.log.client.Log;
62 import com.google.gwt.user.server.rpc.RemoteServiceServlet;
63 import com.mchange.v2.c3p0.ComboPooledDataSource;
64 import com.mchange.v2.c3p0.DataSources;
65
66 @SuppressWarnings("serial")
67 public class OnlineGlomServiceImpl extends RemoteServiceServlet implements OnlineGlomService {
68         private class ConfiguredDocument {
69                 private Document document;
70                 private ComboPooledDataSource cpds;
71
72                 public ConfiguredDocument(Document document, ComboPooledDataSource cpds) {
73                         this.cpds = cpds;
74                         this.document = document;
75                 }
76
77                 public Document getDocument() {
78                         return document;
79                 }
80
81                 public ComboPooledDataSource getCpds() {
82                         return cpds;
83                 }
84
85         }
86
87         private final Hashtable<String, ConfiguredDocument> documents = new Hashtable<String, ConfiguredDocument>();
88
89         // TODO implement locale
90         private final Locale locale = Locale.ROOT;
91         private boolean configured = false;
92
93         /*
94          * This is called when the servlet is started or restarted.
95          */
96         public OnlineGlomServiceImpl() {
97                 Glom.libglom_init();
98
99         }
100
101         /*
102          * The properties file can't be loaded in the constructor because the servlet is not yet initialised and
103          * getServletContext() will return null. The work-around for this problem is to initialise the database and glom
104          * document object when makes its first request.
105          */
106         private void configureServlet() {
107                 // TODO get this from a config file
108                 String glomDemoDir = "/home/ben";
109
110                 File file = new File(glomDemoDir);
111
112                 if (!file.isDirectory()) {
113                         // TODO notify user of error
114                         Log.fatal(glomDemoDir + " is not a directory.");
115                 }
116
117                 if (!file.canRead()) {
118                         // TODO notify user of error
119                         Log.fatal("Can't read the files in : " + glomDemoDir);
120                 }
121
122                 File[] glomFiles = file.listFiles(new FilenameFilter() {
123                         @Override
124                         public boolean accept(File dir, String name) {
125                                 return name.endsWith(".glom") ? true : false;
126                         }
127                 });
128
129                 for (File glomFile : glomFiles) {
130                         Document document = new Document();
131                         document.set_file_uri("file://" + glomFile.getAbsolutePath());
132                         int error = 0;
133                         boolean retval = document.load(error);
134                         if (retval == false) {
135                                 String message;
136                                 if (LoadFailureCodes.LOAD_FAILURE_CODE_NOT_FOUND == LoadFailureCodes.swigToEnum(error)) {
137                                         message = "Could not find " + file.getAbsolutePath();
138                                 } else {
139                                         message = "An unknown error occurred when trying to load " + file.getAbsolutePath();
140                                 }
141                                 Log.error(message);
142                                 continue;
143                         }
144
145                         Properties props = new Properties();
146                         String propFileName = "/WEB-INF/OnlineGlom.properties";
147                         try {
148                                 props.load(getServletContext().getResourceAsStream(propFileName));
149                         } catch (IOException e) {
150                                 Log.fatal("Error loading " + propFileName, e);
151                                 // TODO can't continue, notify user of problem
152                         }
153
154                         // load the jdbc driver for this document
155                         ComboPooledDataSource cpds = new ComboPooledDataSource();
156                         try {
157                                 cpds.setDriverClass("org.postgresql.Driver");
158                         } catch (PropertyVetoException e) {
159                                 Log.fatal(
160                                                 "Error loading the PostgreSQL JDBC driver. Is the PostgreSQL JDBC jar available to the servlet?",
161                                                 e);
162                                 // TODO can't continue, notify user of problem
163                                 break;
164                         }
165
166                         cpds.setJdbcUrl("jdbc:postgresql://" + document.get_connection_server() + "/"
167                                         + document.get_connection_database());
168                         // TODO notify user if dbusername or dbpassword are wrong
169                         cpds.setUser(props.getProperty("dbusername"));
170                         cpds.setPassword(props.getProperty("dbpassword"));
171
172                         String documentTitle = document.get_database_title().trim();
173                         ConfiguredDocument configuredDocument = new ConfiguredDocument(document, cpds);
174                         documents.put(documentTitle, configuredDocument);
175                 }
176
177                 configured = true;
178         }
179
180         /*
181          * This is called when the servlet is stopped or restarted.
182          * 
183          * @see javax.servlet.GenericServlet#destroy()
184          */
185         @Override
186         public void destroy() {
187                 Glom.libglom_deinit();
188
189                 if (configured) {
190                         for (String documenTitle : documents.keySet()) {
191                                 ConfiguredDocument configuredDoc = documents.get(documenTitle);
192                                 try {
193                                         DataSources.destroy(configuredDoc.getCpds());
194                                 } catch (SQLException e) {
195                                         Log.error("Error cleaning up the ComboPooledDataSource for " + documenTitle, e);
196                                 }
197                         }
198                 }
199
200         }
201
202         /*
203          * FIXME I think Swig is generating long on 64-bit machines and int on 32-bit machines - need to keep this constant
204          * http://stackoverflow.com/questions/1590831/safely-casting-long-to-int-in-java
205          */
206         private static int safeLongToInt(long l) {
207                 if (l < Integer.MIN_VALUE || l > Integer.MAX_VALUE) {
208                         throw new IllegalArgumentException(l + " cannot be cast to int without changing its value.");
209                 }
210                 return (int) l;
211         }
212
213         public GlomDocument getGlomDocument(String documentTitle) {
214                 if (!configured)
215                         configureServlet();
216
217                 Document document = documents.get(documentTitle).getDocument();
218                 GlomDocument glomDocument = new GlomDocument();
219
220                 // get arrays of table names and titles, and find the default table index
221                 StringVector tablesVec = document.get_table_names();
222
223                 int numTables = safeLongToInt(tablesVec.size());
224                 // we don't know how many tables will be hidden so we'll use half of the number of tables for the default size
225                 // of the ArrayList
226                 ArrayList<String> tableNames = new ArrayList<String>(numTables / 2);
227                 ArrayList<String> tableTitles = new ArrayList<String>(numTables / 2);
228                 boolean foundDefaultTable = false;
229                 int visibleIndex = 0;
230                 for (int i = 0; i < numTables; i++) {
231                         String tableName = tablesVec.get(i);
232                         if (!document.get_table_is_hidden(tableName)) {
233                                 tableNames.add(tableName);
234                                 // JNI is "expensive", the comparison will only be called if we haven't already found the default table
235                                 if (!foundDefaultTable && tableName.equals(document.get_default_table())) {
236                                         glomDocument.setDefaultTableIndex(visibleIndex);
237                                         foundDefaultTable = true;
238                                 }
239                                 tableTitles.add(document.get_table_title(tableName));
240                                 visibleIndex++;
241                         }
242                 }
243
244                 // set everything we need
245                 glomDocument.setTableNames(tableNames);
246                 glomDocument.setTableTitles(tableTitles);
247
248                 return glomDocument;
249         }
250
251         public LayoutListTable getLayoutListTable(String documentTitle, String table) {
252                 if (!configured)
253                         configureServlet();
254
255                 ConfiguredDocument configuredDoc = documents.get(documentTitle);
256                 Document document = configuredDoc.getDocument();
257                 LayoutListTable tableInfo = new LayoutListTable();
258
259                 // access the layout list
260                 LayoutGroupVector layoutListVec = document.get_data_layout_groups("list", table);
261                 ColumnInfo[] columns = null;
262                 LayoutFieldVector layoutFields = new LayoutFieldVector();
263                 int listViewLayoutGroupSize = safeLongToInt(layoutListVec.size());
264                 if (listViewLayoutGroupSize > 0) {
265                         // a layout list is defined, we can use it to for the LayoutListTable
266                         if (listViewLayoutGroupSize > 1)
267                                 Log.warn(documentTitle + " " + table + ": The size of the list view layout group for table " + table
268                                                 + " is greater than 1. Attempting to use the first item for the layout list view.");
269                         LayoutItemVector layoutItemsVec = layoutListVec.get(0).get_items();
270
271                         // find the defined layout list fields
272                         int numItems = safeLongToInt(layoutItemsVec.size());
273                         columns = new ColumnInfo[numItems];
274                         for (int i = 0; i < numItems; i++) {
275                                 // TODO add support for other LayoutItems (Text, Image, Button)
276                                 LayoutItem item = layoutItemsVec.get(i);
277                                 LayoutItem_Field layoutItemField = LayoutItem_Field.cast_dynamic(item);
278                                 if (layoutItemField != null) {
279                                         layoutFields.add(layoutItemField);
280                                         columns[i] = new ColumnInfo(
281                                                         layoutItemField.get_title_or_name(),
282                                                         getColumnInfoHorizontalAlignment(layoutItemField.get_formatting_used_horizontal_alignment()),
283                                                         getColumnInfoGlomFieldType(layoutItemField.get_glom_type()));
284                                 }
285                         }
286                 } else {
287                         // no layout list is defined, use the table fields as the layout list
288                         FieldVector fieldsVec = document.get_table_fields(table);
289
290                         // find the fields to display in the layout list
291                         int numItems = safeLongToInt(fieldsVec.size());
292                         columns = new ColumnInfo[numItems];
293                         for (int i = 0; i < numItems; i++) {
294                                 Field field = fieldsVec.get(i);
295                                 LayoutItem_Field layoutItemField = new LayoutItem_Field();
296                                 layoutItemField.set_full_field_details(field);
297                                 layoutFields.add(layoutItemField);
298                                 columns[i] = new ColumnInfo(layoutItemField.get_title_or_name(),
299                                                 getColumnInfoHorizontalAlignment(layoutItemField.get_formatting_used_horizontal_alignment()),
300                                                 getColumnInfoGlomFieldType(layoutItemField.get_glom_type()));
301                         }
302                 }
303
304                 tableInfo.setColumns(columns);
305
306                 // Get the number of rows a query with the table name and layout fields would return. This is needed for the
307                 // list view pager.
308                 Connection conn = null;
309                 Statement st = null;
310                 ResultSet rs = null;
311                 try {
312                         // Setup and execute the count query. Special care needs to be take to ensure that the results will be based
313                         // on a cursor so that large amounts of memory are not consumed when the query retrieve a large amount of
314                         // data. Here's the relevant PostgreSQL documentation:
315                         // http://jdbc.postgresql.org/documentation/83/query.html#query-with-cursor
316                         ComboPooledDataSource cpds = configuredDoc.getCpds();
317                         conn = cpds.getConnection();
318                         conn.setAutoCommit(false);
319                         st = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
320                         String query = Glom.build_sql_select_count_simple(table, layoutFields);
321                         // TODO Test execution time of this query with when the number of rows in the table is large (say >
322                         // 1,000,000). Test memory usage at the same time (see the todo item in getTableData()).
323                         rs = st.executeQuery(query);
324
325                         // get the number of rows in the query
326                         rs.next();
327                         tableInfo.setNumRows(rs.getInt(1));
328
329                 } catch (SQLException e) {
330                         Log.error(documentTitle + " " + table
331                                         + ": Error calculating number of rows in the query. Setting number of rows to 0.", e);
332                         tableInfo.setNumRows(0);
333                 } finally {
334                         // cleanup everything that has been used
335                         try {
336                                 rs.close();
337                                 st.close();
338                                 conn.close();
339                         } catch (Exception e) {
340                                 Log.error(documentTitle + " " + table
341                                                 + ": Error closing database resources. Subsequent database queries may not work.", e);
342                         }
343                 }
344
345                 return tableInfo;
346         }
347
348         public ArrayList<GlomField[]> getTableData(String documentTitle, String tableName, int start, int length) {
349                 return getTableData(documentTitle, tableName, start, length, false, 0, false);
350         }
351
352         public ArrayList<GlomField[]> getSortedTableData(String documentTitle, String tableName, int start, int length,
353                         int sortColumnIndex, boolean isAscending) {
354                 return getTableData(documentTitle, tableName, start, length, true, sortColumnIndex, isAscending);
355         }
356
357         private ArrayList<GlomField[]> getTableData(String documentTitle, String tableName, int start, int length,
358                         boolean useSortClause, int sortColumnIndex, boolean isAscending) {
359
360                 // FIXME fix LayoutListView to not call this method with empty table or document title
361                 if (documentTitle.isEmpty() || tableName.isEmpty())
362                         return new ArrayList<GlomField[]>();
363
364                 if (!configured)
365                         configureServlet();
366
367                 ConfiguredDocument configuredDoc = documents.get(documentTitle);
368                 Document document = configuredDoc.getDocument();
369
370                 // access the layout list using the defined layout list or the table fields if there's no layout list
371                 LayoutGroupVector layoutListVec = document.get_data_layout_groups("list", tableName);
372                 LayoutFieldVector layoutFields = new LayoutFieldVector();
373                 SortClause sortClause = new SortClause();
374                 int listViewLayoutGroupSize = safeLongToInt(layoutListVec.size());
375                 if (layoutListVec.size() > 0) {
376                         // a layout list is defined, we can use it to for the LayoutListTable
377                         if (listViewLayoutGroupSize > 1)
378                                 Log.warn(documentTitle + ": The size of the list view layout group for table " + tableName
379                                                 + " is greater than 1. Attempting to use the first item for the layout list view.");
380                         LayoutItemVector layoutItemsVec = layoutListVec.get(0).get_items();
381
382                         // find the defined layout list fields
383                         int numItems = safeLongToInt(layoutItemsVec.size());
384                         for (int i = 0; i < numItems; i++) {
385                                 // TODO add support for other LayoutItems (Text, Image, Button)
386                                 LayoutItem item = layoutItemsVec.get(i);
387                                 LayoutItem_Field layoutItemfield = LayoutItem_Field.cast_dynamic(item);
388                                 if (layoutItemfield != null) {
389                                         // use this field in the layout
390                                         layoutFields.add(layoutItemfield);
391
392                                         // create a sort clause if it's a primary key and we're not asked to sort a specific column
393                                         if (!useSortClause) {
394                                                 Field details = layoutItemfield.get_full_field_details();
395                                                 if (details != null && details.get_primary_key()) {
396                                                         sortClause.addLast(new SortFieldPair(layoutItemfield, true)); // ascending
397                                                 }
398                                         }
399                                 }
400                         }
401                 } else {
402                         // no layout list is defined, use the table fields as the layout list
403                         FieldVector fieldsVec = document.get_table_fields(tableName);
404
405                         // find the fields to display in the layout list
406                         int numItems = safeLongToInt(fieldsVec.size());
407                         for (int i = 0; i < numItems; i++) {
408                                 Field field = fieldsVec.get(i);
409                                 LayoutItem_Field layoutItemField = new LayoutItem_Field();
410                                 layoutItemField.set_full_field_details(field);
411                                 layoutFields.add(layoutItemField);
412
413                                 // create a sort clause if it's a primary key and we're not asked to sort a specific column
414                                 if (!useSortClause) {
415                                         if (field.get_primary_key()) {
416                                                 sortClause.addLast(new SortFieldPair(layoutItemField, true)); // ascending
417                                         }
418                                 }
419                         }
420                 }
421
422                 // create a sort clause for the column we've been asked to sort
423                 if (useSortClause) {
424                         LayoutItem item = layoutFields.get(sortColumnIndex);
425                         LayoutItem_Field field = LayoutItem_Field.cast_dynamic(item);
426                         if (field != null)
427                                 sortClause.addLast(new SortFieldPair(field, isAscending));
428                         else {
429                                 Log.error(documentTitle + " " + tableName + ": Error getting LayoutItem_Field for column index "
430                                                 + sortColumnIndex + ". Cannot create a sort clause for this column.");
431                         }
432
433                 }
434
435                 ArrayList<GlomField[]> rowsList = new ArrayList<GlomField[]>();
436                 Connection conn = null;
437                 Statement st = null;
438                 ResultSet rs = null;
439                 try {
440                         // Setup and execute the query. Special care needs to be take to ensure that the results will be based on a
441                         // cursor so that large amounts of memory are not consumed when the query retrieve a large amount of data.
442                         // Here's the relevant PostgreSQL documentation:
443                         // http://jdbc.postgresql.org/documentation/83/query.html#query-with-cursor
444                         ComboPooledDataSource cpds = configuredDoc.getCpds();
445                         conn = cpds.getConnection();
446                         conn.setAutoCommit(false);
447                         st = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
448                         st.setFetchSize(length);
449                         String query = Glom.build_sql_select_simple(tableName, layoutFields, sortClause) + " OFFSET " + start;
450                         // TODO Test memory usage before and after we execute the query that would result in a large ResultSet.
451                         // We need to ensure that the JDBC driver is in fact returning a cursor based result set that has a low
452                         // memory footprint. Check the difference between this value before and after the query:
453                         // Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()
454                         // Test the execution time at the same time (see the todo item in getLayoutListTable()).
455                         rs = st.executeQuery(query);
456
457                         // get the data we've been asked for
458                         int rowCount = 0;
459                         while (rs.next() && rowCount <= length) {
460                                 int layoutFieldsSize = safeLongToInt(layoutFields.size());
461                                 GlomField[] rowArray = new GlomField[layoutFieldsSize];
462                                 for (int i = 0; i < layoutFieldsSize; i++) {
463                                         // make a new GlomField to set the text and colours
464                                         rowArray[i] = new GlomField();
465
466                                         // get foreground and background colours
467                                         LayoutItem_Field field = layoutFields.get(i);
468                                         FieldFormatting formatting = field.get_formatting_used();
469                                         String fgcolour = formatting.get_text_format_color_foreground();
470                                         if (!fgcolour.isEmpty())
471                                                 rowArray[i].setFGColour(convertGdkColorToHtmlColour(fgcolour));
472                                         String bgcolour = formatting.get_text_format_color_background();
473                                         if (!bgcolour.isEmpty())
474                                                 rowArray[i].setBGColour(convertGdkColorToHtmlColour(bgcolour));
475
476                                         // Convert the field value to a string based on the glom type. We're doing the formatting on the
477                                         // server side for now but it might be useful to move this to the client side.
478                                         switch (field.get_glom_type()) {
479                                         case TYPE_TEXT:
480                                                 String text = rs.getString(i + 1);
481                                                 rowArray[i].setText(text != null ? text : "");
482                                                 break;
483                                         case TYPE_BOOLEAN:
484                                                 rowArray[i].setBoolean(rs.getBoolean(i + 1));
485                                                 break;
486                                         case TYPE_NUMERIC:
487                                                 // Take care of the numeric formatting before converting the number to a string.
488                                                 NumericFormat numFormatGlom = formatting.getM_numeric_format();
489                                                 // There's no isCurrency() method in the glom NumericFormat class so we're assuming that the
490                                                 // number should be formatted as a currency if the currency code string is not empty.
491                                                 String currencyCode = numFormatGlom.getM_currency_symbol();
492                                                 NumberFormat numFormatJava = null;
493                                                 boolean useGlomCurrencyCode = false;
494                                                 if (currencyCode.length() == 3) {
495                                                         // Try to format the currency using the Java Locales system.
496                                                         try {
497                                                                 Currency currency = Currency.getInstance(currencyCode);
498                                                                 Log.info(documentTitle
499                                                                                 + " "
500                                                                                 + tableName
501                                                                                 + ": A valid ISO 4217 currency code is being used. Overriding the numeric formatting with information from the locale.");
502                                                                 int digits = currency.getDefaultFractionDigits();
503                                                                 numFormatJava = NumberFormat.getCurrencyInstance(locale);
504                                                                 numFormatJava.setCurrency(currency);
505                                                                 numFormatJava.setMinimumFractionDigits(digits);
506                                                                 numFormatJava.setMaximumFractionDigits(digits);
507                                                         } catch (IllegalArgumentException e) {
508                                                                 Log.warn(documentTitle
509                                                                                 + " "
510                                                                                 + tableName
511                                                                                 + ": "
512                                                                                 + currencyCode
513                                                                                 + " is not a valid ISO 4217 code. Manually setting currency code with this value.");
514                                                                 // The currency code is not this is not an ISO 4217 currency code.
515                                                                 // We're going to manually set the currency code and use the glom numeric formatting.
516                                                                 useGlomCurrencyCode = true;
517                                                                 numFormatJava = getJavaNumberFormat(numFormatGlom);
518                                                         }
519                                                 } else if (currencyCode.length() > 0) {
520                                                         Log.warn(documentTitle + " " + tableName + ": " + currencyCode
521                                                                         + " is not a valid ISO 4217 code. Manually setting currency code with this value.");
522                                                         // The length of the currency code is > 0 and != 3; this is not an ISO 4217 currency code.
523                                                         // We're going to manually set the currency code and use the glom numeric formatting.
524                                                         useGlomCurrencyCode = true;
525                                                         numFormatJava = getJavaNumberFormat(numFormatGlom);
526                                                 } else {
527                                                         // The length of the currency code is 0; the number is not a currency.
528                                                         numFormatJava = getJavaNumberFormat(numFormatGlom);
529                                                 }
530
531                                                 // TODO: Do I need to do something with NumericFormat.get_default_precision() from libglom?
532
533                                                 double number = rs.getDouble(i + 1);
534                                                 if (number < 0) {
535                                                         if (formatting.getM_numeric_format().getM_alt_foreground_color_for_negatives())
536                                                                 // overrides the set foreground colour
537                                                                 rowArray[i].setFGColour(convertGdkColorToHtmlColour(NumericFormat
538                                                                                 .get_alternative_color_for_negatives()));
539                                                 }
540
541                                                 // Finally convert the number to text using the glom currency string if required.
542                                                 if (useGlomCurrencyCode) {
543                                                         rowArray[i].setText(currencyCode + " " + numFormatJava.format(number));
544                                                 } else {
545                                                         rowArray[i].setText(numFormatJava.format(number));
546                                                 }
547                                                 break;
548                                         case TYPE_DATE:
549                                                 Date date = rs.getDate(i + 1);
550                                                 if (date != null) {
551                                                         DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.MEDIUM, locale);
552                                                         rowArray[i].setText(dateFormat.format(date));
553                                                 } else {
554                                                         rowArray[i].setText("");
555                                                 }
556                                                 break;
557                                         case TYPE_TIME:
558                                                 Time time = rs.getTime(i + 1);
559                                                 if (time != null) {
560                                                         DateFormat timeFormat = DateFormat.getTimeInstance(DateFormat.MEDIUM, locale);
561                                                         rowArray[i].setText(timeFormat.format(time));
562                                                 } else {
563                                                         rowArray[i].setText("");
564                                                 }
565                                                 break;
566                                         case TYPE_IMAGE:
567                                                 byte[] image = rs.getBytes(i + 1);
568                                                 if (image != null) {
569                                                         // TODO implement field TYPE_IMAGE
570                                                         rowArray[i].setText("Image (FIXME)");
571                                                 } else {
572                                                         rowArray[i].setText("");
573                                                 }
574                                                 break;
575                                         case TYPE_INVALID:
576                                         default:
577                                                 Log.warn(documentTitle + " " + tableName
578                                                                 + ": Invalid LayoutItem Field type. Using empty string for value.");
579                                                 rowArray[i].setText("");
580                                                 break;
581                                         }
582                                 }
583
584                                 // add the row of GlomFields to the ArrayList we're going to return and update the row count
585                                 rowsList.add(rowArray);
586                                 rowCount++;
587                         }
588                 } catch (SQLException e) {
589                         Log.error(documentTitle + " " + tableName + ": Error executing database query.", e);
590                         // TODO: somehow notify user of problem
591                 } finally {
592                         // cleanup everything that has been used
593                         try {
594                                 rs.close();
595                                 st.close();
596                                 conn.close();
597                         } catch (Exception e) {
598                                 Log.error(documentTitle + " " + tableName
599                                                 + ": Error closing database resources. Subsequent database queries may not work.", e);
600                         }
601                 }
602                 return rowsList;
603         }
604
605         public ArrayList<String> getDemoDatabaseTitles() {
606                 if (!configured)
607                         configureServlet();
608
609                 ArrayList<String> documentTitles = new ArrayList<String>();
610                 for (String title : documents.keySet()) {
611                         documentTitles.add(title);
612                 }
613                 return documentTitles;
614         }
615
616         private NumberFormat getJavaNumberFormat(NumericFormat numFormatGlom) {
617                 NumberFormat numFormatJava = NumberFormat.getInstance(locale);
618                 if (numFormatGlom.getM_decimal_places_restricted()) {
619                         int digits = safeLongToInt(numFormatGlom.getM_decimal_places());
620                         numFormatJava.setMinimumFractionDigits(digits);
621                         numFormatJava.setMaximumFractionDigits(digits);
622                 }
623                 numFormatJava.setGroupingUsed(numFormatGlom.getM_use_thousands_separator());
624                 return numFormatJava;
625         }
626
627         /*
628          * Converts a Gdk::Color (16-bits per channel) to an HTML colour (8-bits per channel) by discarding the least
629          * significant 8-bits in each channel.
630          */
631         private String convertGdkColorToHtmlColour(String gdkColor) {
632                 if (gdkColor.length() == 13)
633                         return gdkColor.substring(0, 3) + gdkColor.substring(5, 7) + gdkColor.substring(9, 11);
634                 else if (gdkColor.length() == 7) {
635                         // FIXME will this happen in on 32-bit?
636                         Log.warn("convertGdkColorToHtmlColour(): Expected a 13 character string but received a 7 character string. Returning received string.");
637                         return gdkColor;
638                 } else {
639                         Log.error("convertGdkColorToHtmlColour(): Did not receive a 13 or 7 character string. Returning black HTML colour code.");
640                         return "#000000";
641                 }
642         }
643
644         /*
645          * This method converts a FieldFormatting.HorizontalAlignment to the equivalent ColumnInfo.HorizontalAlignment. The
646          * need for this comes from the fact that the GWT HorizontalAlignment classes can't be used with RPC and there's no
647          * easy way to use the java-libglom FieldFormatting.HorizontalAlignment enum with RPC. An enum identical to
648          * FieldFormatting.HorizontalAlignment is included in the ColumnInfo class.
649          */
650         private ColumnInfo.HorizontalAlignment getColumnInfoHorizontalAlignment(
651                         FieldFormatting.HorizontalAlignment alignment) {
652                 switch (alignment) {
653                 case HORIZONTAL_ALIGNMENT_AUTO:
654                         return ColumnInfo.HorizontalAlignment.HORIZONTAL_ALIGNMENT_AUTO;
655                 case HORIZONTAL_ALIGNMENT_LEFT:
656                         return ColumnInfo.HorizontalAlignment.HORIZONTAL_ALIGNMENT_LEFT;
657                 case HORIZONTAL_ALIGNMENT_RIGHT:
658                         return ColumnInfo.HorizontalAlignment.HORIZONTAL_ALIGNMENT_RIGHT;
659                 default:
660                         Log.error("getColumnInfoGlomFieldType(): Recieved an alignment that I don't know about: "
661                                         + FieldFormatting.HorizontalAlignment.class.getName() + "." + alignment.toString() + ". Returning "
662                                         + ColumnInfo.HorizontalAlignment.HORIZONTAL_ALIGNMENT_RIGHT.toString() + ".");
663                         return ColumnInfo.HorizontalAlignment.HORIZONTAL_ALIGNMENT_RIGHT;
664                 }
665         }
666
667         /*
668          * This method converts a Field.glom_field_type to the equivalent ColumnInfo.FieldType. The need for this comes from
669          * the fact that the GWT FieldType classes can't be used with RPC and there's no easy way to use the java-libglom
670          * Field.glom_field_type enum with RPC. An enum identical to FieldFormatting.glom_field_type is included in the
671          * ColumnInfo class.
672          */
673         private ColumnInfo.GlomFieldType getColumnInfoGlomFieldType(Field.glom_field_type type) {
674                 switch (type) {
675                 case TYPE_BOOLEAN:
676                         return ColumnInfo.GlomFieldType.TYPE_BOOLEAN;
677                 case TYPE_DATE:
678                         return ColumnInfo.GlomFieldType.TYPE_DATE;
679                 case TYPE_IMAGE:
680                         return ColumnInfo.GlomFieldType.TYPE_IMAGE;
681                 case TYPE_NUMERIC:
682                         return ColumnInfo.GlomFieldType.TYPE_NUMERIC;
683                 case TYPE_TEXT:
684                         return ColumnInfo.GlomFieldType.TYPE_TEXT;
685                 case TYPE_TIME:
686                         return ColumnInfo.GlomFieldType.TYPE_TIME;
687                 case TYPE_INVALID:
688                         Log.info("getColumnInfoGlomFieldType(): Returning TYPE_INVALID.");
689                         return ColumnInfo.GlomFieldType.TYPE_INVALID;
690                 default:
691                         Log.error("getColumnInfoGlomFieldType(): Recieved a type that I don't know about: "
692                                         + Field.glom_field_type.class.getName() + "." + type.toString() + ". Returning "
693                                         + ColumnInfo.GlomFieldType.TYPE_INVALID.toString() + ".");
694                         return ColumnInfo.GlomFieldType.TYPE_INVALID;
695                 }
696         }
697
698 }