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