Enable the table selector in the DetailsView.
[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.io.File;
23 import java.io.FilenameFilter;
24 import java.io.IOException;
25 import java.io.InputStream;
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.LayoutItem_Portal;
52 import org.glom.libglom.NumericFormat;
53 import org.glom.libglom.SortClause;
54 import org.glom.libglom.SortFieldPair;
55 import org.glom.libglom.StringVector;
56 import org.glom.web.client.OnlineGlomService;
57 import org.glom.web.shared.Documents;
58 import org.glom.web.shared.GlomDocument;
59 import org.glom.web.shared.GlomField;
60 import org.glom.web.shared.layout.Formatting;
61 import org.glom.web.shared.layout.LayoutGroup;
62 import org.glom.web.shared.layout.LayoutItemField;
63
64 import com.google.gwt.user.server.rpc.RemoteServiceServlet;
65 import com.mchange.v2.c3p0.ComboPooledDataSource;
66 import com.mchange.v2.c3p0.DataSources;
67
68 /**
69  * The servlet for retrieving layout information from libglom and data from the underlying PostgreSQL database.
70  * 
71  * TODO: move methods that that require a glom document object to the ConfiguredDocument class.
72  * 
73  * @author Ben Konrath <ben@bagu.org>
74  */
75 @SuppressWarnings("serial")
76 public class OnlineGlomServiceImpl extends RemoteServiceServlet implements OnlineGlomService {
77
78         // convenience class to for dealing with the Online Glom configuration file
79         private class OnlineGlomProperties extends Properties {
80                 public String getKey(String value) {
81                         for (String key : stringPropertyNames()) {
82                                 if (getProperty(key).trim().equals(value))
83                                         return key;
84                         }
85                         return null;
86                 }
87         }
88
89         private final Hashtable<String, ConfiguredDocument> documentMapping = new Hashtable<String, ConfiguredDocument>();
90         // TODO implement locale
91         private final Locale locale = Locale.ROOT;
92
93         /*
94          * This is called when the servlet is started or restarted.
95          */
96         public OnlineGlomServiceImpl() throws Exception {
97
98                 // Find the configuration file. See this thread for background info:
99                 // http://stackoverflow.com/questions/2161054/where-to-place-properties-files-in-a-jsp-servlet-web-application
100                 OnlineGlomProperties config = new OnlineGlomProperties();
101                 InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("onlineglom.properties");
102                 if (is == null) {
103                         Log.fatal("onlineglom.properties not found.");
104                         throw new IOException();
105                 }
106                 config.load(is);
107
108                 // check if we can read the configured glom file directory
109                 String documentDirName = config.getProperty("glom.document.directory");
110                 File documentDir = new File(documentDirName);
111                 if (!documentDir.isDirectory()) {
112                         Log.fatal(documentDirName + " is not a directory.");
113                         throw new IOException();
114                 }
115                 if (!documentDir.canRead()) {
116                         Log.fatal("Can't read the files in : " + documentDirName);
117                         throw new IOException();
118                 }
119
120                 // get and check the glom files in the specified directory
121                 final String glomFileExtension = ".glom";
122                 File[] glomFiles = documentDir.listFiles(new FilenameFilter() {
123                         @Override
124                         public boolean accept(File dir, String name) {
125                                 return name.endsWith(glomFileExtension);
126                         }
127                 });
128                 Glom.libglom_init();
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: " + glomFile.getAbsolutePath();
138                                 } else {
139                                         message = "An unknown error occurred when trying to load file: " + glomFile.getAbsolutePath();
140                                 }
141                                 Log.error(message);
142                                 // continue with for loop because there may be other documents in the directory
143                                 continue;
144                         }
145
146                         ConfiguredDocument configuredDocument = new ConfiguredDocument(document);
147                         // check if a username and password have been set and work for the current document
148                         String filename = glomFile.getName();
149                         String key = config.getKey(filename);
150                         if (key != null) {
151                                 String[] keyArray = key.split("\\.");
152                                 if (keyArray.length == 3 && "filename".equals(keyArray[2])) {
153                                         // username/password could be set, let's check to see if it works
154                                         String usernameKey = key.replaceAll(keyArray[2], "username");
155                                         String passwordKey = key.replaceAll(keyArray[2], "password");
156                                         configuredDocument.setUsernameAndPassword(config.getProperty(usernameKey),
157                                                         config.getProperty(passwordKey));
158                                 }
159                         }
160
161                         // check the if the global username and password have been set and work with this document
162                         if (!configuredDocument.isAuthenticated()) {
163                                 configuredDocument.setUsernameAndPassword(config.getProperty("glom.document.username"),
164                                                 config.getProperty("glom.document.password"));
165                         }
166
167                         // The key for the hash table is the file name without the .glom extension and with spaces ( ) replaced with
168                         // pluses (+). The space/plus replacement makes the key more friendly for URLs.
169                         String hashKey = filename.substring(0, glomFile.getName().length() - glomFileExtension.length()).replace(
170                                         ' ', '+');
171                         documentMapping.put(hashKey, configuredDocument);
172
173                 }
174         }
175
176         /*
177          * This is called when the servlet is stopped or restarted.
178          * 
179          * @see javax.servlet.GenericServlet#destroy()
180          */
181         @Override
182         public void destroy() {
183                 Glom.libglom_deinit();
184
185                 for (String documenTitle : documentMapping.keySet()) {
186                         ConfiguredDocument configuredDoc = documentMapping.get(documenTitle);
187                         try {
188                                 DataSources.destroy(configuredDoc.getCpds());
189                         } catch (SQLException e) {
190                                 Log.error(documenTitle, "Error cleaning up the ComboPooledDataSource.", e);
191                         }
192                 }
193
194         }
195
196         public GlomDocument getGlomDocument(String documentID) {
197
198                 Document document = documentMapping.get(documentID).getDocument();
199                 GlomDocument glomDocument = new GlomDocument();
200
201                 // get arrays of table names and titles, and find the default table index
202                 StringVector tablesVec = document.get_table_names();
203
204                 int numTables = safeLongToInt(tablesVec.size());
205                 // we don't know how many tables will be hidden so we'll use half of the number of tables for the default size
206                 // of the ArrayList
207                 ArrayList<String> tableNames = new ArrayList<String>(numTables / 2);
208                 ArrayList<String> tableTitles = new ArrayList<String>(numTables / 2);
209                 boolean foundDefaultTable = false;
210                 int visibleIndex = 0;
211                 for (int i = 0; i < numTables; i++) {
212                         String tableName = tablesVec.get(i);
213                         if (!document.get_table_is_hidden(tableName)) {
214                                 tableNames.add(tableName);
215                                 // JNI is "expensive", the comparison will only be called if we haven't already found the default table
216                                 if (!foundDefaultTable && tableName.equals(document.get_default_table())) {
217                                         glomDocument.setDefaultTableIndex(visibleIndex);
218                                         foundDefaultTable = true;
219                                 }
220                                 tableTitles.add(document.get_table_title(tableName));
221                                 visibleIndex++;
222                         }
223                 }
224
225                 // set everything we need
226                 glomDocument.setTableNames(tableNames);
227                 glomDocument.setTableTitles(tableTitles);
228
229                 return glomDocument;
230         }
231
232         /*
233          * (non-Javadoc)
234          * 
235          * @see org.glom.web.client.OnlineGlomService#getDefaultLayoutListTable(java.lang.String)
236          */
237         @Override
238         public LayoutGroup getDefaultListLayout(String documentID) {
239                 GlomDocument glomDocument = getGlomDocument(documentID);
240                 String tableName = glomDocument.getTableNames().get(glomDocument.getDefaultTableIndex());
241                 LayoutGroup layoutGroup = getListLayout(documentID, tableName);
242                 layoutGroup.setDefaultTableName(tableName);
243                 return layoutGroup;
244         }
245
246         public LayoutGroup getListLayout(String documentID, String tableName) {
247                 ConfiguredDocument configuredDoc = documentMapping.get(documentID);
248                 Document document = configuredDoc.getDocument();
249
250                 // access the layout list
251                 LayoutGroupVector layoutGroupVec = document.get_data_layout_groups("list", tableName);
252                 int listViewLayoutGroupSize = safeLongToInt(layoutGroupVec.size());
253                 org.glom.libglom.LayoutGroup libglomLayoutGroup = null;
254                 if (listViewLayoutGroupSize > 0) {
255                         // a list layout group is defined; we can use the first group as the list
256                         if (listViewLayoutGroupSize > 1)
257                                 Log.warn(documentID, tableName,
258                                                 "The size of the list layout group is greater than 1. Attempting to use the first item for the layout list view.");
259
260                         libglomLayoutGroup = layoutGroupVec.get(0);
261                 } else {
262                         // a list layout group is *not* defined; we are going make a libglom layout group from the list of fields
263                         Log.info(documentID, tableName,
264                                         "A list layout is not defined for this table. Displaying a list layout based on the field list.");
265
266                         FieldVector fieldsVec = document.get_table_fields(tableName);
267                         libglomLayoutGroup = new org.glom.libglom.LayoutGroup();
268                         for (int i = 0; i < fieldsVec.size(); i++) {
269                                 Field field = fieldsVec.get(i);
270                                 LayoutItem_Field layoutItemField = new LayoutItem_Field();
271                                 layoutItemField.set_full_field_details(field);
272                                 libglomLayoutGroup.add_item(layoutItemField);
273                         }
274                 }
275
276                 // confirm the libglom LayoutGroup is not null as per the method's precondition
277                 if (libglomLayoutGroup == null) {
278                         Log.error(documentID, tableName, "A LayoutGroup was not found. Returning null.");
279                         return null;
280                 }
281
282                 LayoutGroup layoutGroup = getLayoutGroup(documentID, tableName, libglomLayoutGroup);
283
284                 // use the same fields list as will be used for the query
285                 LayoutFieldVector fieldsToGet = getFieldsToShowForSQLQuery(document, tableName, "list");
286                 layoutGroup.setExpectedResultSize(getResultSizeOfSQLQuery(documentID, tableName, fieldsToGet));
287
288                 // Set the primary key index for the table and add a LayoutItemField for the primary key to the end of the item
289                 // list in the LayoutGroup if it doesn't already contain a primary key.
290                 int primaryKeyIndex = getPrimaryKeyIndex(fieldsToGet);
291                 if (primaryKeyIndex < 0) {
292                         LayoutItem_Field libglomLayoutItemField = getPrimaryKeyLayoutItemFromFields(document, tableName);
293                         layoutGroup.addItem(convertToGWTGlomLayoutItemField(libglomLayoutItemField));
294                         layoutGroup.setPrimaryKeyIndex(layoutGroup.getItems().size() - 1);
295                         layoutGroup.setHiddenPrimaryKey(true);
296
297                 } else {
298                         layoutGroup.setPrimaryKeyIndex(primaryKeyIndex);
299                 }
300                 return layoutGroup;
301         }
302
303         private LayoutItem_Field getPrimaryKeyLayoutItemFromFields(Document document, String tableName) {
304                 Field primaryKey = null;
305                 FieldVector fieldVec = document.get_table_fields(tableName);
306                 for (int i = 0; i < fieldVec.size(); i++) {
307                         Field field = fieldVec.get(i);
308                         if (field != null && field.get_primary_key()) {
309                                 primaryKey = field;
310                                 break;
311                         }
312                 }
313                 if (primaryKey == null) {
314                         Log.fatal(document.get_database_title(), tableName,
315                                         "A primary key was not found in the FieldVector for this table.");
316                         // TODO throw exception
317                 }
318
319                 LayoutItem_Field libglomLayoutItemField = new LayoutItem_Field();
320                 libglomLayoutItemField.set_full_field_details(primaryKey);
321                 return libglomLayoutItemField;
322         }
323
324         /*
325          * Gets the primary key index of the LayoutFieldVector.
326          */
327         private int getPrimaryKeyIndex(LayoutFieldVector layoutFieldVec) {
328                 for (int i = 0; i < layoutFieldVec.size(); i++) {
329                         LayoutItem_Field layoutItemField = layoutFieldVec.get(i);
330                         Field field = layoutItemField.get_full_field_details();
331                         if (field != null && field.get_primary_key())
332                                 return i;
333                 }
334                 return -1;
335         }
336
337         /*
338          * Get the number of rows a query with the table name and layout fields would return. This is needed for the /* list
339          * view pager.
340          */
341         private int getResultSizeOfSQLQuery(String documentID, String tableName, LayoutFieldVector fieldsToGet) {
342                 ConfiguredDocument configuredDoc = documentMapping.get(documentID);
343                 if (!configuredDoc.isAuthenticated())
344                         return -1;
345                 Connection conn = null;
346                 Statement st = null;
347                 ResultSet rs = null;
348                 try {
349                         // Setup and execute the count query. Special care needs to be take to ensure that the results will be based
350                         // on a cursor so that large amounts of memory are not consumed when the query retrieve a large amount of
351                         // data. Here's the relevant PostgreSQL documentation:
352                         // http://jdbc.postgresql.org/documentation/83/query.html#query-with-cursor
353                         ComboPooledDataSource cpds = configuredDoc.getCpds();
354                         conn = cpds.getConnection();
355                         conn.setAutoCommit(false);
356                         st = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
357                         String query = Glom.build_sql_select_count_simple(tableName, fieldsToGet);
358                         // TODO Test execution time of this query with when the number of rows in the table is large (say >
359                         // 1,000,000). Test memory usage at the same time (see the todo item in getTableData()).
360                         rs = st.executeQuery(query);
361
362                         // get the number of rows in the query
363                         rs.next();
364                         return rs.getInt(1);
365
366                 } catch (SQLException e) {
367                         Log.error(documentID, tableName, "Error calculating number of rows in the query.", e);
368                         return -1;
369                 } finally {
370                         // cleanup everything that has been used
371                         try {
372                                 if (rs != null)
373                                         rs.close();
374                                 if (st != null)
375                                         st.close();
376                                 if (conn != null)
377                                         conn.close();
378                         } catch (Exception e) {
379                                 Log.error(documentID, tableName,
380                                                 "Error closing database resources. Subsequent database queries may not work.", e);
381                         }
382                 }
383         }
384
385         // FIXME Check if we can use getFieldsToShowForSQLQuery() in these methods
386         public ArrayList<GlomField[]> getListData(String documentID, String tableName, int start, int length) {
387                 return getListData(documentID, tableName, start, length, false, 0, false);
388         }
389
390         public ArrayList<GlomField[]> getSortedListData(String documentID, String tableName, int start, int length,
391                         int sortColumnIndex, boolean isAscending) {
392                 return getListData(documentID, tableName, start, length, true, sortColumnIndex, isAscending);
393         }
394
395         private ArrayList<GlomField[]> getListData(String documentID, String tableName, int start, int length,
396                         boolean useSortClause, int sortColumnIndex, boolean isAscending) {
397
398                 ConfiguredDocument configuredDoc = documentMapping.get(documentID);
399                 if (!configuredDoc.isAuthenticated())
400                         return new ArrayList<GlomField[]>();
401                 Document document = configuredDoc.getDocument();
402
403                 // access the layout list using the defined layout list or the table fields if there's no layout list
404                 LayoutGroupVector layoutListVec = document.get_data_layout_groups("list", tableName);
405                 LayoutFieldVector layoutFields = new LayoutFieldVector();
406                 SortClause sortClause = new SortClause();
407                 int listViewLayoutGroupSize = safeLongToInt(layoutListVec.size());
408                 if (layoutListVec.size() > 0) {
409                         // a layout list is defined, we can use it to for the LayoutListTable
410                         if (listViewLayoutGroupSize > 1)
411                                 Log.warn(documentID, tableName, "The size of the list view layout group for table is greater than 1. "
412                                                 + "Attempting to use the first item for the layout list view.");
413                         LayoutItemVector layoutItemsVec = layoutListVec.get(0).get_items();
414
415                         // find the defined layout list fields
416                         int numItems = safeLongToInt(layoutItemsVec.size());
417                         for (int i = 0; i < numItems; i++) {
418                                 // TODO add support for other LayoutItems (Text, Image, Button)
419                                 LayoutItem item = layoutItemsVec.get(i);
420                                 LayoutItem_Field layoutItemfield = LayoutItem_Field.cast_dynamic(item);
421                                 if (layoutItemfield != null) {
422                                         // use this field in the layout
423                                         layoutFields.add(layoutItemfield);
424
425                                         // create a sort clause if it's a primary key and we're not asked to sort a specific column
426                                         if (!useSortClause) {
427                                                 Field details = layoutItemfield.get_full_field_details();
428                                                 if (details != null && details.get_primary_key()) {
429                                                         sortClause.addLast(new SortFieldPair(layoutItemfield, true)); // ascending
430                                                 }
431                                         }
432                                 }
433                         }
434                 } else {
435                         // no layout list is defined, use the table fields as the layout list
436                         FieldVector fieldsVec = document.get_table_fields(tableName);
437
438                         // find the fields to display in the layout list
439                         int numItems = safeLongToInt(fieldsVec.size());
440                         for (int i = 0; i < numItems; i++) {
441                                 Field field = fieldsVec.get(i);
442                                 LayoutItem_Field layoutItemField = new LayoutItem_Field();
443                                 layoutItemField.set_full_field_details(field);
444                                 layoutFields.add(layoutItemField);
445
446                                 // create a sort clause if it's a primary key and we're not asked to sort a specific column
447                                 if (!useSortClause) {
448                                         if (field.get_primary_key()) {
449                                                 sortClause.addLast(new SortFieldPair(layoutItemField, true)); // ascending
450                                         }
451                                 }
452                         }
453                 }
454
455                 // create a sort clause for the column we've been asked to sort
456                 if (useSortClause) {
457                         LayoutItem item = layoutFields.get(sortColumnIndex);
458                         LayoutItem_Field field = LayoutItem_Field.cast_dynamic(item);
459                         if (field != null)
460                                 sortClause.addLast(new SortFieldPair(field, isAscending));
461                         else {
462                                 Log.error(documentID, tableName, "Error getting LayoutItem_Field for column index " + sortColumnIndex
463                                                 + ". Cannot create a sort clause for this column.");
464                         }
465                 }
466
467                 // Add a LayoutItem_Field for the primary key to the end of the LayoutFieldVector if it doesn't already contain
468                 // a primary key.
469                 // TODO Can we use a cached LayoutGroup object to find out if we need to add a LayoutItem_Field object for the
470                 // primary key field?
471                 if (getPrimaryKeyIndex(layoutFields) < 0) {
472                         layoutFields.add(getPrimaryKeyLayoutItemFromFields(document, tableName));
473                 }
474
475                 ArrayList<GlomField[]> rowsList = new ArrayList<GlomField[]>();
476                 Connection conn = null;
477                 Statement st = null;
478                 ResultSet rs = null;
479                 try {
480                         // Setup the JDBC driver and get the query. Special care needs to be take to ensure that the results will be
481                         // based on a cursor so that large amounts of memory are not consumed when the query retrieve a large amount
482                         // of data. Here's the relevant PostgreSQL documentation:
483                         // http://jdbc.postgresql.org/documentation/83/query.html#query-with-cursor
484                         ComboPooledDataSource cpds = configuredDoc.getCpds();
485                         conn = cpds.getConnection();
486                         conn.setAutoCommit(false);
487                         st = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
488                         st.setFetchSize(length);
489                         String query = Glom.build_sql_select_simple(tableName, layoutFields, sortClause) + " OFFSET " + start;
490                         // TODO Test memory usage before and after we execute the query that would result in a large ResultSet.
491                         // We need to ensure that the JDBC driver is in fact returning a cursor based result set that has a low
492                         // memory footprint. Check the difference between this value before and after the query:
493                         // Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()
494                         // Test the execution time at the same time (see the todo item in getLayoutListTable()).
495                         rs = st.executeQuery(query);
496
497                         // get the results from the ResultSet
498                         rowsList = getData(documentID, tableName, length, layoutFields, rs);
499                 } catch (SQLException e) {
500                         Log.error(documentID, tableName, "Error executing database query.", e);
501                         // TODO: somehow notify user of problem
502                 } finally {
503                         // cleanup everything that has been used
504                         try {
505                                 if (rs != null)
506                                         rs.close();
507                                 if (st != null)
508                                         st.close();
509                                 if (conn != null)
510                                         conn.close();
511                         } catch (Exception e) {
512                                 Log.error(documentID, tableName,
513                                                 "Error closing database resources. Subsequent database queries may not work.", e);
514                         }
515                 }
516                 return rowsList;
517         }
518
519         private ArrayList<GlomField[]> getData(String documentID, String tableName, int length,
520                         LayoutFieldVector layoutFields, ResultSet rs) throws SQLException {
521
522                 // get the data we've been asked for
523                 int rowCount = 0;
524                 ArrayList<GlomField[]> rowsList = new ArrayList<GlomField[]>();
525                 while (rs.next() && rowCount <= length) {
526                         int layoutFieldsSize = safeLongToInt(layoutFields.size());
527                         GlomField[] rowArray = new GlomField[layoutFieldsSize];
528                         for (int i = 0; i < layoutFieldsSize; i++) {
529                                 // make a new GlomField to set the text and colours
530                                 rowArray[i] = new GlomField();
531
532                                 // get foreground and background colours
533                                 LayoutItem_Field field = layoutFields.get(i);
534                                 FieldFormatting formatting = field.get_formatting_used();
535                                 String fgcolour = formatting.get_text_format_color_foreground();
536                                 if (!fgcolour.isEmpty())
537                                         rowArray[i].setFGColour(convertGdkColorToHtmlColour(fgcolour));
538                                 String bgcolour = formatting.get_text_format_color_background();
539                                 if (!bgcolour.isEmpty())
540                                         rowArray[i].setBGColour(convertGdkColorToHtmlColour(bgcolour));
541
542                                 // Convert the field value to a string based on the glom type. We're doing the formatting on the
543                                 // server side for now but it might be useful to move this to the client side.
544                                 switch (field.get_glom_type()) {
545                                 case TYPE_TEXT:
546                                         String text = rs.getString(i + 1);
547                                         rowArray[i].setText(text != null ? text : "");
548                                         break;
549                                 case TYPE_BOOLEAN:
550                                         rowArray[i].setBoolean(rs.getBoolean(i + 1));
551                                         break;
552                                 case TYPE_NUMERIC:
553                                         // Take care of the numeric formatting before converting the number to a string.
554                                         NumericFormat numFormatGlom = formatting.getM_numeric_format();
555                                         // There's no isCurrency() method in the glom NumericFormat class so we're assuming that the
556                                         // number should be formatted as a currency if the currency code string is not empty.
557                                         String currencyCode = numFormatGlom.getM_currency_symbol();
558                                         NumberFormat numFormatJava = null;
559                                         boolean useGlomCurrencyCode = false;
560                                         if (currencyCode.length() == 3) {
561                                                 // Try to format the currency using the Java Locales system.
562                                                 try {
563                                                         Currency currency = Currency.getInstance(currencyCode);
564                                                         Log.info(documentID, tableName, "A valid ISO 4217 currency code is being used."
565                                                                         + " Overriding the numeric formatting with information from the locale.");
566                                                         int digits = currency.getDefaultFractionDigits();
567                                                         numFormatJava = NumberFormat.getCurrencyInstance(locale);
568                                                         numFormatJava.setCurrency(currency);
569                                                         numFormatJava.setMinimumFractionDigits(digits);
570                                                         numFormatJava.setMaximumFractionDigits(digits);
571                                                 } catch (IllegalArgumentException e) {
572                                                         Log.warn(documentID, tableName, currencyCode + " is not a valid ISO 4217 code."
573                                                                         + " Manually setting currency code with this value.");
574                                                         // The currency code is not this is not an ISO 4217 currency code.
575                                                         // We're going to manually set the currency code and use the glom numeric formatting.
576                                                         useGlomCurrencyCode = true;
577                                                         numFormatJava = convertToJavaNumberFormat(numFormatGlom);
578                                                 }
579                                         } else if (currencyCode.length() > 0) {
580                                                 Log.warn(documentID, tableName, currencyCode + " is not a valid ISO 4217 code."
581                                                                 + " Manually setting currency code with this value.");
582                                                 // The length of the currency code is > 0 and != 3; this is not an ISO 4217 currency code.
583                                                 // We're going to manually set the currency code and use the glom numeric formatting.
584                                                 useGlomCurrencyCode = true;
585                                                 numFormatJava = convertToJavaNumberFormat(numFormatGlom);
586                                         } else {
587                                                 // The length of the currency code is 0; the number is not a currency.
588                                                 numFormatJava = convertToJavaNumberFormat(numFormatGlom);
589                                         }
590
591                                         // TODO: Do I need to do something with NumericFormat.get_default_precision() from libglom?
592
593                                         double number = rs.getDouble(i + 1);
594                                         if (number < 0) {
595                                                 if (formatting.getM_numeric_format().getM_alt_foreground_color_for_negatives())
596                                                         // overrides the set foreground colour
597                                                         rowArray[i].setFGColour(convertGdkColorToHtmlColour(NumericFormat
598                                                                         .get_alternative_color_for_negatives()));
599                                         }
600
601                                         // Finally convert the number to text using the glom currency string if required.
602                                         if (useGlomCurrencyCode) {
603                                                 rowArray[i].setText(currencyCode + " " + numFormatJava.format(number));
604                                         } else {
605                                                 rowArray[i].setText(numFormatJava.format(number));
606                                         }
607                                         break;
608                                 case TYPE_DATE:
609                                         Date date = rs.getDate(i + 1);
610                                         if (date != null) {
611                                                 DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.MEDIUM, locale);
612                                                 rowArray[i].setText(dateFormat.format(date));
613                                         } else {
614                                                 rowArray[i].setText("");
615                                         }
616                                         break;
617                                 case TYPE_TIME:
618                                         Time time = rs.getTime(i + 1);
619                                         if (time != null) {
620                                                 DateFormat timeFormat = DateFormat.getTimeInstance(DateFormat.MEDIUM, locale);
621                                                 rowArray[i].setText(timeFormat.format(time));
622                                         } else {
623                                                 rowArray[i].setText("");
624                                         }
625                                         break;
626                                 case TYPE_IMAGE:
627                                         byte[] image = rs.getBytes(i + 1);
628                                         if (image != null) {
629                                                 // TODO implement field TYPE_IMAGE
630                                                 rowArray[i].setText("Image (FIXME)");
631                                         } else {
632                                                 rowArray[i].setText("");
633                                         }
634                                         break;
635                                 case TYPE_INVALID:
636                                 default:
637                                         Log.warn(documentID, tableName, "Invalid LayoutItem Field type. Using empty string for value.");
638                                         rowArray[i].setText("");
639                                         break;
640                                 }
641                         }
642
643                         // add the row of GlomFields to the ArrayList we're going to return and update the row count
644                         rowsList.add(rowArray);
645                         rowCount++;
646                 }
647
648                 return rowsList;
649         }
650
651         public Documents getDocuments() {
652                 Documents documents = new Documents();
653                 for (String documentID : documentMapping.keySet()) {
654                         ConfiguredDocument configuredDoc = documentMapping.get(documentID);
655                         documents.addDocuemnt(documentID, configuredDoc.getDocument().get_database_title());
656                 }
657                 return documents;
658         }
659
660         /*
661          * This method safely converts longs from libglom into ints. This method was taken from stackoverflow:
662          * 
663          * http://stackoverflow.com/questions/1590831/safely-casting-long-to-int-in-java
664          */
665         private int safeLongToInt(long value) {
666                 if (value < Integer.MIN_VALUE || value > Integer.MAX_VALUE) {
667                         throw new IllegalArgumentException(value + " cannot be cast to int without changing its value.");
668                 }
669                 return (int) value;
670         }
671
672         private NumberFormat convertToJavaNumberFormat(NumericFormat numFormatGlom) {
673                 NumberFormat numFormatJava = NumberFormat.getInstance(locale);
674                 if (numFormatGlom.getM_decimal_places_restricted()) {
675                         int digits = safeLongToInt(numFormatGlom.getM_decimal_places());
676                         numFormatJava.setMinimumFractionDigits(digits);
677                         numFormatJava.setMaximumFractionDigits(digits);
678                 }
679                 numFormatJava.setGroupingUsed(numFormatGlom.getM_use_thousands_separator());
680                 return numFormatJava;
681         }
682
683         /*
684          * Converts a Gdk::Color (16-bits per channel) to an HTML colour (8-bits per channel) by discarding the least
685          * significant 8-bits in each channel.
686          */
687         private String convertGdkColorToHtmlColour(String gdkColor) {
688                 if (gdkColor.length() == 13)
689                         return gdkColor.substring(0, 3) + gdkColor.substring(5, 7) + gdkColor.substring(9, 11);
690                 else if (gdkColor.length() == 7) {
691                         // This shouldn't happen but let's deal with it if it does.
692                         Log.warn("Expected a 13 character string but received a 7 character string. Returning received string.");
693                         return gdkColor;
694                 } else {
695                         Log.error("Did not receive a 13 or 7 character string. Returning black HTML colour code.");
696                         return "#000000";
697                 }
698         }
699
700         /*
701          * This method converts a FieldFormatting.HorizontalAlignment to the equivalent ColumnInfo.HorizontalAlignment. The
702          * need for this comes from the fact that the GWT HorizontalAlignment classes can't be used with RPC and there's no
703          * easy way to use the java-libglom FieldFormatting.HorizontalAlignment enum with RPC. An enum identical to
704          * FieldFormatting.HorizontalAlignment is included in the ColumnInfo class.
705          */
706         private Formatting.HorizontalAlignment convertToGWTGlomHorizonalAlignment(
707                         FieldFormatting.HorizontalAlignment alignment) {
708                 switch (alignment) {
709                 case HORIZONTAL_ALIGNMENT_AUTO:
710                         return Formatting.HorizontalAlignment.HORIZONTAL_ALIGNMENT_AUTO;
711                 case HORIZONTAL_ALIGNMENT_LEFT:
712                         return Formatting.HorizontalAlignment.HORIZONTAL_ALIGNMENT_LEFT;
713                 case HORIZONTAL_ALIGNMENT_RIGHT:
714                         return Formatting.HorizontalAlignment.HORIZONTAL_ALIGNMENT_RIGHT;
715                 default:
716                         Log.error("Recieved an alignment that I don't know about: "
717                                         + FieldFormatting.HorizontalAlignment.class.getName() + "." + alignment.toString() + ". Returning "
718                                         + Formatting.HorizontalAlignment.HORIZONTAL_ALIGNMENT_RIGHT.toString() + ".");
719                         return Formatting.HorizontalAlignment.HORIZONTAL_ALIGNMENT_RIGHT;
720                 }
721         }
722
723         /*
724          * This method converts a Field.glom_field_type to the equivalent ColumnInfo.FieldType. The need for this comes from
725          * the fact that the GWT FieldType classes can't be used with RPC and there's no easy way to use the java-libglom
726          * Field.glom_field_type enum with RPC. An enum identical to FieldFormatting.glom_field_type is included in the
727          * ColumnInfo class.
728          */
729         private LayoutItemField.GlomFieldType convertToGWTGlomFieldType(Field.glom_field_type type) {
730                 switch (type) {
731                 case TYPE_BOOLEAN:
732                         return LayoutItemField.GlomFieldType.TYPE_BOOLEAN;
733                 case TYPE_DATE:
734                         return LayoutItemField.GlomFieldType.TYPE_DATE;
735                 case TYPE_IMAGE:
736                         return LayoutItemField.GlomFieldType.TYPE_IMAGE;
737                 case TYPE_NUMERIC:
738                         return LayoutItemField.GlomFieldType.TYPE_NUMERIC;
739                 case TYPE_TEXT:
740                         return LayoutItemField.GlomFieldType.TYPE_TEXT;
741                 case TYPE_TIME:
742                         return LayoutItemField.GlomFieldType.TYPE_TIME;
743                 case TYPE_INVALID:
744                         Log.info("Returning TYPE_INVALID.");
745                         return LayoutItemField.GlomFieldType.TYPE_INVALID;
746                 default:
747                         Log.error("Recieved a type that I don't know about: " + Field.glom_field_type.class.getName() + "."
748                                         + type.toString() + ". Returning " + LayoutItemField.GlomFieldType.TYPE_INVALID.toString() + ".");
749                         return LayoutItemField.GlomFieldType.TYPE_INVALID;
750                 }
751         }
752
753         /*
754          * (non-Javadoc)
755          * 
756          * @see org.glom.web.client.OnlineGlomService#isAuthenticated(java.lang.String)
757          */
758         public boolean isAuthenticated(String documentID) {
759                 return documentMapping.get(documentID).isAuthenticated();
760         }
761
762         /*
763          * (non-Javadoc)
764          * 
765          * @see org.glom.web.client.OnlineGlomService#checkAuthentication(java.lang.String, java.lang.String,
766          * java.lang.String)
767          */
768         public boolean checkAuthentication(String documentID, String username, String password) {
769                 ConfiguredDocument configuredDoc = documentMapping.get(documentID);
770                 try {
771                         return configuredDoc.setUsernameAndPassword(username, password);
772                 } catch (SQLException e) {
773                         Log.error(documentID, "Unknown SQL Error checking the database authentication.", e);
774                         return false;
775                 }
776         }
777
778         /*
779          * (non-Javadoc)
780          * 
781          * @see org.glom.web.client.OnlineGlomService#getDetailsLayoutGroup(java.lang.String, java.lang.String)
782          */
783         public ArrayList<LayoutGroup> getDetailsLayout(String documentID, String tableName) {
784                 ConfiguredDocument configuredDoc = documentMapping.get(documentID);
785                 Document document = configuredDoc.getDocument();
786
787                 // Use the default table if the table name hasn't been set or if the table name isn't in the glom document.
788                 // The last check guards against SQL injection attacks since the table name could come from the URL.
789                 if (tableName == null || tableName.isEmpty() || !document.get_table_is_known(tableName)) {
790                         tableName = document.get_default_table();
791                 }
792
793                 LayoutGroupVector layoutGroupVec = document.get_data_layout_groups("details", tableName);
794
795                 ArrayList<LayoutGroup> layoutGroups = new ArrayList<LayoutGroup>();
796                 for (int i = 0; i < layoutGroupVec.size(); i++) {
797                         org.glom.libglom.LayoutGroup libglomLayoutGroup = layoutGroupVec.get(i);
798
799                         if (libglomLayoutGroup == null)
800                                 continue;
801
802                         layoutGroups.add(getLayoutGroup(documentID, tableName, libglomLayoutGroup));
803                 }
804                 return layoutGroups;
805         }
806
807         /*
808          * Gets a GWT-Glom LayoutGroup object for the specified libglom LayoutGroup object. This is used for getting layout
809          * information for the list and details views.
810          * 
811          * @param documentID Glom document identifier
812          * 
813          * @param tableName table name in the specified Glom document
814          * 
815          * @param libglomLayoutGroup libglom LayoutGroup to convert
816          * 
817          * @precondition libglomLayoutGroup must not be null
818          * 
819          * @return {@link LayoutGroup} object that represents the layout for the specified {@link
820          * org.glom.libglom.LayoutGroup}
821          */
822         private LayoutGroup getLayoutGroup(String documentID, String tableName,
823                         org.glom.libglom.LayoutGroup libglomLayoutGroup) {
824                 LayoutGroup layoutGroup = new LayoutGroup();
825                 layoutGroup.setColumnCount(safeLongToInt(libglomLayoutGroup.get_columns_count()));
826
827                 // look at each child item
828                 LayoutItemVector layoutItemsVec = libglomLayoutGroup.get_items();
829                 for (int i = 0; i < layoutItemsVec.size(); i++) {
830                         org.glom.libglom.LayoutItem libglomLayoutItem = layoutItemsVec.get(i);
831
832                         // just a safety check
833                         if (libglomLayoutItem == null)
834                                 continue;
835
836                         org.glom.web.shared.layout.LayoutItem layoutItem = null;
837                         org.glom.libglom.LayoutGroup group = org.glom.libglom.LayoutGroup.cast_dynamic(libglomLayoutItem);
838                         if (group != null) {
839                                 // recurse into child groups
840                                 layoutItem = getLayoutGroup(documentID, tableName, group);
841                         } else {
842                                 // create GWT-Glom LayoutItem types based on the the libglom type
843                                 // TODO add support for other LayoutItems (Text, Image, Button etc.)
844                                 LayoutItem_Field libglomLayoutField = LayoutItem_Field.cast_dynamic(libglomLayoutItem);
845                                 if (libglomLayoutField != null) {
846                                         layoutItem = convertToGWTGlomLayoutItemField(libglomLayoutField);
847                                 } else {
848                                         Log.info(documentID, tableName,
849                                                         "Ignoring unknown LayoutItem of type " + libglomLayoutItem.get_part_type_name() + ".");
850                                         continue;
851                                 }
852
853                         }
854
855                         layoutItem.setTitle(libglomLayoutItem.get_title_or_name());
856                         layoutGroup.addItem(layoutItem);
857                 }
858
859                 return layoutGroup;
860         }
861
862         private LayoutItemField convertToGWTGlomLayoutItemField(LayoutItem_Field libglomLayoutField) {
863                 LayoutItemField layoutItemField = new LayoutItemField();
864
865                 // set type
866                 layoutItemField.setType(convertToGWTGlomFieldType(libglomLayoutField.get_glom_type()));
867
868                 // set formatting
869                 Formatting formatting = new Formatting();
870                 formatting.setHorizontalAlignment(convertToGWTGlomHorizonalAlignment(libglomLayoutField
871                                 .get_formatting_used_horizontal_alignment()));
872                 layoutItemField.setFormatting(formatting);
873
874                 return layoutItemField;
875         }
876
877         public GlomField[] getDetailsData(String documentID, String tableName, String primaryKeyValue) {
878
879                 ConfiguredDocument configuredDoc = documentMapping.get(documentID);
880                 Document document = configuredDoc.getDocument();
881
882                 // Use the default table if the table name hasn't been set or if the table name isn't in the glom document.
883                 // The last check guards against SQL injection attacks since the table name could come from the URL.
884                 if (tableName == null || tableName.isEmpty() || !document.get_table_is_known(tableName)) {
885                         tableName = document.get_default_table();
886                 }
887
888                 LayoutFieldVector fieldsToGet = getFieldsToShowForSQLQuery(document, tableName, "details");
889
890                 if (fieldsToGet == null || fieldsToGet.size() <= 0) {
891                         Log.warn(documentID, tableName, "Didn't find any fields to show. Returning null.");
892                         return null;
893                 }
894
895                 // get primary key for the table to use in the SQL query
896                 Field primaryKey = null;
897                 FieldVector fieldsVec = document.get_table_fields(tableName);
898                 for (int i = 0; i < safeLongToInt(fieldsVec.size()); i++) {
899                         Field field = fieldsVec.get(i);
900                         if (field.get_primary_key()) {
901                                 primaryKey = field;
902                                 break;
903                         }
904                 }
905
906                 if (primaryKey == null) {
907                         Log.error(documentID, tableName, "Couldn't find primary key in table. Returning null.");
908                         return null;
909                 }
910
911                 ArrayList<GlomField[]> rowsList = new ArrayList<GlomField[]>();
912                 Connection conn = null;
913                 Statement st = null;
914                 ResultSet rs = null;
915                 try {
916                         // Setup the JDBC driver and get the query.
917                         ComboPooledDataSource cpds = configuredDoc.getCpds();
918                         conn = cpds.getConnection();
919                         st = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
920                         String query = Glom.build_sql_select_with_key(tableName, fieldsToGet, primaryKey, primaryKeyValue);
921                         rs = st.executeQuery(query);
922
923                         // get the results from the ResultSet
924                         // using 2 as a length parameter so we can log a warning if appropriate
925                         rowsList = getData(documentID, tableName, 2, fieldsToGet, rs);
926                 } catch (SQLException e) {
927                         Log.error(documentID, tableName, "Error executing database query.", e);
928                         // TODO: somehow notify user of problem
929                         return null;
930                 } finally {
931                         // cleanup everything that has been used
932                         try {
933                                 if (rs != null)
934                                         rs.close();
935                                 if (st != null)
936                                         st.close();
937                                 if (conn != null)
938                                         conn.close();
939                         } catch (Exception e) {
940                                 Log.error(documentID, tableName,
941                                                 "Error closing database resources. Subsequent database queries may not work.", e);
942                         }
943                 }
944
945                 if (rowsList.size() == 0) {
946                         Log.error(documentID, tableName, "The query returned an empty ResultSet. Returning null.");
947                         return null;
948                 } else if (rowsList.size() > 1 && primaryKeyValue != null && !primaryKeyValue.isEmpty()) {
949                         // only log a warning if the result size is greater than 1 and the primaryKeyValue was set
950                         Log.warn(documentID, tableName,
951                                         "The query did not return the expected unique result. Returning the first result in the set.");
952                 }
953
954                 return rowsList.get(0);
955
956         }
957
958         /*
959          * Gets a LayoutFieldVector to use when generating an SQL query.
960          */
961         private LayoutFieldVector getFieldsToShowForSQLQuery(Document document, String tableName, String layoutName) {
962                 LayoutGroupVector layoutGroupVec = document.get_data_layout_groups(layoutName, tableName);
963                 LayoutFieldVector layoutFieldVector = new LayoutFieldVector();
964
965                 // special case for list layouts that don't have a defined layout group
966                 if ("list".equals(layoutName) && layoutGroupVec.size() == 0) {
967                         FieldVector fieldsVec = document.get_table_fields(tableName);
968                         for (int i = 0; i < fieldsVec.size(); i++) {
969                                 Field field = fieldsVec.get(i);
970                                 LayoutItem_Field layoutItemField = new LayoutItem_Field();
971                                 layoutItemField.set_full_field_details(field);
972                                 layoutFieldVector.add(layoutItemField);
973                         }
974                         return layoutFieldVector;
975                 }
976
977                 // We will show the fields that the document says we should:
978                 for (int i = 0; i < layoutGroupVec.size(); i++) {
979                         org.glom.libglom.LayoutGroup layoutGroup = layoutGroupVec.get(i);
980
981                         // Get the fields:
982                         ArrayList<LayoutItem_Field> layoutItemsFields = getFieldsToShowForSQLQueryAddGroup(document, tableName,
983                                         layoutGroup);
984                         for (LayoutItem_Field layoutItem_Field : layoutItemsFields) {
985                                 layoutFieldVector.add(layoutItem_Field);
986                         }
987                 }
988                 return layoutFieldVector;
989         }
990
991         private ArrayList<LayoutItem_Field> getFieldsToShowForSQLQueryAddGroup(Document document, String tableName,
992                         org.glom.libglom.LayoutGroup layoutGroup) {
993
994                 ArrayList<LayoutItem_Field> layoutItemFields = new ArrayList<LayoutItem_Field>();
995                 LayoutItemVector items = layoutGroup.get_items();
996                 for (int i = 0; i < items.size(); i++) {
997                         LayoutItem layoutItem = items.get(i);
998
999                         LayoutItem_Field layoutItemField = LayoutItem_Field.cast_dynamic(layoutItem);
1000                         if (layoutItemField != null) {
1001                                 // the layoutItem is a LayoutItem_Field
1002                                 FieldVector fields;
1003                                 if (layoutItemField.get_has_relationship_name()) {
1004                                         // layoutItemField is a field in a related table
1005                                         fields = document.get_table_fields(layoutItemField.get_table_used(tableName));
1006                                 } else {
1007                                         // layoutItemField is a field in this table
1008                                         fields = document.get_table_fields(tableName);
1009                                 }
1010
1011                                 // set the layoutItemFeild with details from its Field in the document and
1012                                 // add it to the list to be returned
1013                                 for (int j = 0; j < fields.size(); j++) {
1014                                         // check the names to see if they're the same
1015                                         // this works because we're using the field list from the related table if necessary
1016                                         if (layoutItemField.get_name().equals(fields.get(j).get_name())) {
1017                                                 Field field = fields.get(j);
1018                                                 if (field != null) {
1019                                                         layoutItemField.set_full_field_details(field);
1020                                                         layoutItemFields.add(layoutItemField);
1021                                                 } else {
1022                                                         Log.warn(document.get_database_title(), tableName,
1023                                                                         "LayoutItem_Field " + layoutItemField.get_layout_display_name()
1024                                                                                         + " not found in document field list.");
1025                                                 }
1026                                                 break;
1027                                         }
1028                                 }
1029
1030                         } else {
1031                                 // the layoutItem is not a LayoutItem_Field
1032                                 org.glom.libglom.LayoutGroup subLayoutGroup = org.glom.libglom.LayoutGroup.cast_dynamic(layoutItem);
1033                                 if (subLayoutGroup != null) {
1034                                         // the layoutItem is a LayoutGroup
1035                                         LayoutItem_Portal layoutItemPortal = LayoutItem_Portal.cast_dynamic(layoutItem);
1036                                         if (layoutItemPortal == null) {
1037                                                 // The subGroup is not a LayoutItem_Portal.
1038                                                 // We're ignoring portals because they are filled by means of a separate SQL query.
1039                                                 layoutItemFields
1040                                                                 .addAll(getFieldsToShowForSQLQueryAddGroup(document, tableName, subLayoutGroup));
1041                                         }
1042                                 }
1043                         }
1044                 }
1045                 return layoutItemFields;
1046         }
1047
1048 }