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