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