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