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